Programs & Examples On #Lnk2005

0

Already defined in .obj - no double inclusions

This is not a compiler error: the error is coming from the linker. After compilation, the linker will merge the object files resulting from the compilation of each of your translation units (.cpp files).

The linker finds out that you have the same symbol defined multiple times in different translation units, and complains about it (it is a violation of the One Definition Rule).

The reason is most certainly that main.cpp includes client.cpp, and both these files are individually processed by the compiler to produce two separate object files. Therefore, all the symbols defined in the client.cpp translation unit will be defined also in the main.cpp translation unit. This is one of the reasons why you do not usually #include .cpp files.

Put the definition of your class in a separate client.hpp file which does not contain also the definitions of the member functions of that class; then, let client.cpp and main.cpp include that file (I mean #include). Finally, leave in client.cpp the definitions of your class's member functions.

client.h

#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif

class SocketClient // Or whatever the name is...
{

// ...

    bool read(int, char*); // Or whatever the name is...

//  ...
};

#endif

client.cpp

#include "Client.h"

// ...

bool SocketClient::read(int, char*)
{
    // Implementation  goes here...
}

// ... (add the definitions for all other member functions)

main.h

#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
//              ^^ Notice this!

main.cpp

#include "main.h"

Mismatch Detected for 'RuntimeLibrary'

(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)

This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)

To correct this error, you need to go into your Project Properties (and/or those of the libraries you are using,) then into C/C++, then Code Generation, and check the value of Runtime Library; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)

There are currently four options for this setting:

  1. Multithreaded Debug
  2. Multithreaded Debug DLL
  3. Multithreaded Release
  4. Multithreaded Release DLL

Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.

Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.

For (some) more information, you can see these (linked from a comment above):

  1. Linker Tools Warning LNK4098 on MSDN
  2. /MD, /ML, /MT, /LD (Use Run-Time Library) on MSDN
  3. Build errors with VC11 Beta - mixing MTd libs with MDd exes fail to link on Bugzilla@Mozilla

UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)

If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)

The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.

Consider for example that the above two pieces of code are called A and B. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)

Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)

The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.

All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)

This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.

What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!

error LNK2005, already defined?

Presence of int k; in the header file causes symbol k to be defined within each translation unit this header is included to while linker expects it to be defined only once (aka One Definition Rule Violation).

While suggestion involving extern are not wrong, extern is a C-ism and should not be used.

Pre C++17 solution that would allow variable in header file to be defined in multiple translation units without causing ODR violation would be conversion to template:

template<typename x_Dummy = void> class
t_HeaderVariableHolder
{
    public: static int s_k;
};

template<typename x_Dummy> int t_HeaderVariableHolder<x_Dummy>::s_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return t_HeaderVariableHolder<>::s_k;
}

With C++17 things become much simpler as it allows inline variables:

inline int g_k{};

// Getter is necessary to decouple variable storage implementation details from access to it.
inline int & Get_K() noexcept
{
    return g_k;
}

How to start working with GTest and CMake

Yours and VladLosevs' solutions are probably better than mine. If you want a brute-force solution, however, try this:

SET(CMAKE_EXE_LINKER_FLAGS /NODEFAULTLIB:\"msvcprtd.lib;MSVCRTD.lib\")

FOREACH(flag_var
    CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
    CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES "/MD")
        string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
    endif(${flag_var} MATCHES "/MD")
ENDFOREACH(flag_var)

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Some readers will have another issue and need this fix. read the links below. the same problem occured with visual studio 2015 with the advent of windows sdk 10 which brings up libucrt. ucrt is the windows implementation of C Runtime (CRT) aka the posix runtime library. You most likely have code that was ported from unix... Welcome to the drawback

https://support.microsoft.com/en-us/help/148652/a-lnk2005-error-occurs-when-the-crt-library-and-mfc-libraries-are-linked-in-the-wrong-order-in-visual-c

https://github.com/lordmulder/libsndfile-MSVC/blob/master/src/sf_unistd.h

https://lists.gnu.org/archive/html/bug-gnulib/2011-09/msg00224.html

https://msdn.microsoft.com/en-us/library/y23kc048.aspx

https://blogs.msdn.microsoft.com/vcblog/2015/03/03/introducing-the-universal-crt/

Which mime type should I use for mp3

Your best bet would be using the RFC defined mime-type audio/mpeg.

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

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

You can use:

<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>

Or this:

textbox.Style["text-align"] = "center"; //right, left

PHP file_get_contents() and setting request headers

Actually, upon further reading on the file_get_contents() function:

// Create a stream
$opts = [
    "http" => [
        "method" => "GET",
        "header" => "Accept-language: en\r\n" .
            "Cookie: foo=bar\r\n"
    ]
];

// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
// DOCS: https://www.php.net/manual/en/function.file-get-contents.php
$file = file_get_contents('http://www.example.com/', false, $context);

You may be able to follow this pattern to achieve what you are seeking to, I haven't personally tested this though. (and if it doesn't work, feel free to check out my other answer)

How to restart remote MySQL server running on Ubuntu linux?

I SSH'ed into my AWS Lightsail wordpress instance, the following worked: sudo /opt/bitnami/ctlscript.sh restart mysql I learnt this here: https://docs.bitnami.com/aws/infrastructure/mysql/administration/control-services/

Find the max of two or more columns with pandas

You can get the maximum like this:

>>> import pandas as pd
>>> df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
>>> df
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]]
   A  B
0  1 -2
1  2  8
2  3  1
>>> df[["A", "B"]].max(axis=1)
0    1
1    8
2    3

and so:

>>> df["C"] = df[["A", "B"]].max(axis=1)
>>> df
   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

If you know that "A" and "B" are the only columns, you could even get away with

>>> df["C"] = df.max(axis=1)

And you could use .apply(max, axis=1) too, I guess.

Leap year calculation

Return true if the input year is a leap year

Basic modern day code:

  If year mod 4 = 0, then leap year
  if year mod 100 then normal year
  if year mod 400 then leap year
  else normal year

Todays rule started 1582 AD Julian calendar rule with every 4th year started 46BC but is not coherent before 10 AD as declared by Cesar. They did however add some leap years every 3rd year now and then in the years before: Leap years were therefore 45 BC, 42 BC, 39 BC, 36 BC, 33 BC, 30 BC, 27 BC, 24 BC, 21 BC, 18 BC, 15 BC, 12 BC, 9 BC, 8 AD, 12 AD Before year 45BC leap year was not added.

The year 0 do not exist as it is ...2BC 1BC 1AD 2AD... for some calculation this can be an issue.

function isLeapYear(year: Integer): Boolean;
begin
  result := false;
  if year > 1582 then // Todays calendar rule was started in year 1582 
    result := ((year mod 4 = 0) and (not(year mod 100 = 0))) or (year mod 400 = 0)
  else if year > 10 then // Between year 10 and year 1582 every 4th year was a leap year 
    result := year mod 4 = 0
  else //Between year -45 and year 10 only certain years was leap year, every 3rd year but the entire time
    case year of
      -45, -42, -39, -36, -33, -30, -27, -24, -21, -18, -15, -12, -9:
        result := true;
    end;
end;

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.

For that we have provide one setter method for myobj and set the myobj value with mocked object.

class MyClass {
    MyInterface myObj;

    public void abc() {
        myObj.myMethodToBeVerified (new String("a"), new String("b"));
    }

    public void setMyObj(MyInterface obj)
    {
        this.myObj=obj;
    }
}

In our Test class, we have to write below code

class MyClassTest {

MyClass myClass = new MyClass();

    @Mock
    MyInterface myInterface;

    @test
    testAbc() {
        myclass.setMyObj(myInterface); //it is good to have in @before method
        myClass.abc();
        verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
     }
}

AngularJS - Binding radio buttons to models with boolean values

You might take a look at this:

https://github.com/michaelmoussa/ng-boolean-radio/

This guy wrote a custom directive to get around the issue that "true" and "false" are strings, not booleans.

Redirect after Login on WordPress

The Theme My Login plugin may help - it allows you to redirect users of specific roles to specific pages.

SQL join format - nested inner joins

Since you've already received help on the query, I'll take a poke at your syntax question:

The first query employs some lesser-known ANSI SQL syntax which allows you to nest joins between the join and on clauses. This allows you to scope/tier your joins and probably opens up a host of other evil, arcane things.

Now, while a nested join cannot refer any higher in the join hierarchy than its immediate parent, joins above it or outside of its branch can refer to it... which is precisely what this ugly little guy is doing:

select
 count(*)
from Table1 as t1
join Table2 as t2
    join Table3 as t3
    on t2.Key = t3.Key                   -- join #1
    and t2.Key2 = t3.Key2 
on t1.DifferentKey = t3.DifferentKey     -- join #2  

This looks a little confusing because join #2 is joining t1 to t2 without specifically referencing t2... however, it references t2 indirectly via t3 -as t3 is joined to t2 in join #1. While that may work, you may find the following a bit more (visually) linear and appealing:

select
 count(*)
from Table1 as t1
    join Table3 as t3
        join Table2 as t2
        on t2.Key = t3.Key                   -- join #1
        and t2.Key2 = t3.Key2   
    on t1.DifferentKey = t3.DifferentKey     -- join #2

Personally, I've found that nesting in this fashion keeps my statements tidy by outlining each tier of the relationship hierarchy. As a side note, you don't need to specify inner. join is implicitly inner unless explicitly marked otherwise.

How to sum the values of a JavaScript object?

If you're using lodash you can do something like

_.sum(_.values({ 'a': 1 , 'b': 2 , 'c':3 })) 

How do you force a makefile to rebuild a target

The -B switch to make, whose long form is --always-make, tells make to disregard timestamps and make the specified targets. This may defeat the purpose of using make, but it may be what you need.

Difference between 'struct' and 'typedef struct' in C++?

There is a difference, but subtle. Look at it this way: struct Foo introduces a new type. The second one creates an alias called Foo (and not a new type) for an unnamed struct type.

7.1.3 The typedef specifier

1 [...]

A name declared with the typedef specifier becomes a typedef-name. Within the scope of its declaration, a typedef-name is syntactically equivalent to a keyword and names the type associated with the identifier in the way described in Clause 8. A typedef-name is thus a synonym for another type. A typedef-name does not introduce a new type the way a class declaration (9.1) or enum declaration does.

8 If the typedef declaration defines an unnamed class (or enum), the first typedef-name declared by the declaration to be that class type (or enum type) is used to denote the class type (or enum type) for linkage purposes only (3.5). [ Example:

typedef struct { } *ps, S; // S is the class name for linkage purposes

So, a typedef always is used as an placeholder/synonym for another type.

Create dynamic variable name

This is not possible, it will give you a compile time error,

You can use array for this type of requirement .

For your Reference :

http://msdn.microsoft.com/en-us/library/aa288453%28v=vs.71%29.aspx

Is it possible to modify a string of char in C?

All are good answers explaining why you cannot modify string literals because they are placed in read-only memory. However, when push comes to shove, there is a way to do this. Check out this example:

#include <sys/mman.h>
#include <unistd.h>
#include <stddef.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

int take_me_back_to_DOS_times(const void *ptr, size_t len);

int main()
{
    const *data = "Bender is always sober.";
    printf("Before: %s\n", data);
    if (take_me_back_to_DOS_times(data, sizeof(data)) != 0)
        perror("Time machine appears to be broken!");
    memcpy((char *)data + 17, "drunk!", 6);
    printf("After: %s\n", data);

    return 0;
}

int take_me_back_to_DOS_times(const void *ptr, size_t len)
{
    int pagesize;
    unsigned long long pg_off;
    void *page;

    pagesize = sysconf(_SC_PAGE_SIZE);
    if (pagesize < 0)
        return -1;
    pg_off = (unsigned long long)ptr % (unsigned long long)pagesize;
    page = ((char *)ptr - pg_off);
    if (mprotect(page, len + pg_off, PROT_READ | PROT_WRITE | PROT_EXEC) == -1)
        return -1;
    return 0;
}

I have written this as part of my somewhat deeper thoughts on const-correctness, which you might find interesting (I hope :)).

Hope it helps. Good Luck!

How to delete/remove nodes on Firebase

The problem is that you call remove on the root of your Firebase:

ref = new Firebase("myfirebase.com")
ref.remove();

This will remove the entire Firebase through the API.

You'll typically want to remove specific child nodes under it though, which you do with:

ref.child(key).remove();

Best way to compare 2 XML documents in Java

I required the same functionality as requested in the main question. As I was not allowed to use any 3rd party libraries, I have created my own solution basing on @Archimedes Trajano solution.

Following is my solution.

import java.io.ByteArrayInputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.junit.Assert;
import org.w3c.dom.Document;

/**
 * Asserts for asserting XML strings.
 */
public final class AssertXml {

    private AssertXml() {
    }

    private static Pattern NAMESPACE_PATTERN = Pattern.compile("xmlns:(ns\\d+)=\"(.*?)\"");

    /**
     * Asserts that two XML are of identical content (namespace aliases are ignored).
     * 
     * @param expectedXml expected XML
     * @param actualXml actual XML
     * @throws Exception thrown if XML parsing fails
     */
    public static void assertEqualXmls(String expectedXml, String actualXml) throws Exception {
        // Find all namespace mappings
        Map<String, String> fullnamespace2newAlias = new HashMap<String, String>();
        generateNewAliasesForNamespacesFromXml(expectedXml, fullnamespace2newAlias);
        generateNewAliasesForNamespacesFromXml(actualXml, fullnamespace2newAlias);

        for (Entry<String, String> entry : fullnamespace2newAlias.entrySet()) {
            String newAlias = entry.getValue();
            String namespace = entry.getKey();
            Pattern nsReplacePattern = Pattern.compile("xmlns:(ns\\d+)=\"" + namespace + "\"");
            expectedXml = transletaNamespaceAliasesToNewAlias(expectedXml, newAlias, nsReplacePattern);
            actualXml = transletaNamespaceAliasesToNewAlias(actualXml, newAlias, nsReplacePattern);
        }

        // nomralize namespaces accoring to given mapping

        DocumentBuilder db = initDocumentParserFactory();

        Document expectedDocuemnt = db.parse(new ByteArrayInputStream(expectedXml.getBytes(Charset.forName("UTF-8"))));
        expectedDocuemnt.normalizeDocument();

        Document actualDocument = db.parse(new ByteArrayInputStream(actualXml.getBytes(Charset.forName("UTF-8"))));
        actualDocument.normalizeDocument();

        if (!expectedDocuemnt.isEqualNode(actualDocument)) {
            Assert.assertEquals(expectedXml, actualXml); //just to better visualize the diffeences i.e. in eclipse
        }
    }


    private static DocumentBuilder initDocumentParserFactory() throws ParserConfigurationException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(false);
        dbf.setCoalescing(true);
        dbf.setIgnoringElementContentWhitespace(true);
        dbf.setIgnoringComments(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db;
    }

    private static String transletaNamespaceAliasesToNewAlias(String xml, String newAlias, Pattern namespacePattern) {
        Matcher nsMatcherExp = namespacePattern.matcher(xml);
        if (nsMatcherExp.find()) {
            xml = xml.replaceAll(nsMatcherExp.group(1) + "[:]", newAlias + ":");
            xml = xml.replaceAll(nsMatcherExp.group(1) + "=", newAlias + "=");
        }
        return xml;
    }

    private static void generateNewAliasesForNamespacesFromXml(String xml, Map<String, String> fullnamespace2newAlias) {
        Matcher nsMatcher = NAMESPACE_PATTERN.matcher(xml);
        while (nsMatcher.find()) {
            if (!fullnamespace2newAlias.containsKey(nsMatcher.group(2))) {
                fullnamespace2newAlias.put(nsMatcher.group(2), "nsTr" + (fullnamespace2newAlias.size() + 1));
            }
        }
    }

}

It compares two XML strings and takes care of any mismatching namespace mappings by translating them to unique values in both input strings.

Can be fine tuned i.e. in case of translation of namespaces. But for my requirements just does the job.

java IO Exception: Stream Closed

You call writer.close(); in writeToFile so the writer has been closed the second time you call writeToFile.

Why don't you merge FileStatus into writeToFile?

Add a space (" ") after an element using :after

Explanation

It's worth noting that your code does insert a space

h2::after {
  content: " ";
}

However, it's immediately removed.

From Anonymous inline boxes,

White space content that would subsequently be collapsed away according to the 'white-space' property does not generate any anonymous inline boxes.

And from The 'white-space' processing model,

If a space (U+0020) at the end of a line has 'white-space' set to 'normal', 'nowrap', or 'pre-line', it is also removed.

Solution

So if you don't want the space to be removed, set white-space to pre or pre-wrap.

_x000D_
_x000D_
h2 {_x000D_
  text-decoration: underline;_x000D_
}_x000D_
h2.space::after {_x000D_
  content: " ";_x000D_
  white-space: pre;_x000D_
}
_x000D_
<h2>I don't have space:</h2>_x000D_
<h2 class="space">I have space:</h2>
_x000D_
_x000D_
_x000D_

Do not use non-breaking spaces (U+00a0). They are supposed to prevent line breaks between words. They are not supposed to be used as non-collapsible space, that wouldn't be semantic.

How do I save a stream to a file in C#?

private void SaveFileStream(String path, Stream stream)
{
    var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
    stream.CopyTo(fileStream);
    fileStream.Dispose();
}

How do I update the GUI from another thread?

Salvete! Having searched for this question, I found the answers by FrankG and Oregon Ghost to be the easiest most useful to me. Now, I code in Visual Basic and ran this snippet through a convertor; so I'm not sure quite how it turns out.

I have a dialog form called form_Diagnostics, which has a richtext box, called updateDiagWindow, which I am using as a sort of logging display. I needed to be able to update its text from all threads. The extra lines allow the window to automatically scroll to the newest lines.

And so, I can now update the display with one line, from anywhere in the entire program in the manner which you think it would work without any threading:

  form_Diagnostics.updateDiagWindow(whatmessage);

Main Code (put this inside of your form's class code):

#region "---------Update Diag Window Text------------------------------------"
// This sub allows the diag window to be updated by all threads
public void updateDiagWindow(string whatmessage)
{
    var _with1 = diagwindow;
    if (_with1.InvokeRequired) {
        _with1.Invoke(new UpdateDiagDelegate(UpdateDiag), whatmessage);
    } else {
        UpdateDiag(whatmessage);
    }
}
// This next line makes the private UpdateDiagWindow available to all threads
private delegate void UpdateDiagDelegate(string whatmessage);
private void UpdateDiag(string whatmessage)
{
    var _with2 = diagwindow;
    _with2.appendtext(whatmessage);
    _with2.SelectionStart = _with2.Text.Length;
    _with2.ScrollToCaret();
}
#endregion

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

This is supposedly because you trying to make cross-domain request, or something that is clarified as it. You could try adding header('Access-Control-Allow-Origin: *'); to the requested file.

Also, such problem is sometimes occurs on server-sent events implementation in case of using event-source or XHR polling in IE 8-10 (which confused me first time).

get the margin size of an element with jquery

From jQuery's website

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

PG::ConnectionBad - could not connect to server: Connection refused

I just run this command sudo service postgresql restart and everything worked again.

Android Studio Gradle Configuration with name 'default' not found

Everything looks fine at first blush, but some poking around on here found an answer that could be helpful: https://stackoverflow.com/a/16905808/7944

Even the original answer writer doesn't sound super confident, but it's worth following up on. Also, you didn't say anything about your directory structure and so I'm assuming it's boring default stuff, but can't know for sure.

Access camera from a browser

You can use HTML5 for this:

<video autoplay></video>
<script>
  var onFailSoHard = function(e) {
    console.log('Reeeejected!', e);
  };

  // Not showing vendor prefixes.
  navigator.getUserMedia({video: true, audio: true}, function(localMediaStream) {
    var video = document.querySelector('video');
    video.src = window.URL.createObjectURL(localMediaStream);

    // Note: onloadedmetadata doesn't fire in Chrome when using it with getUserMedia.
    // See crbug.com/110938.
    video.onloadedmetadata = function(e) {
      // Ready to go. Do some stuff.
    };
  }, onFailSoHard);
</script>

Source

How to rotate x-axis tick labels in Pandas barplot

Try this -

plt.xticks(rotation=90)

enter image description here

Saving an image in OpenCV

I had the same problem on Windows Vista, I just added this code before cvQueryFrame:

cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 720);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 480);

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Like the answer above but here is using bootstrap 3 names and colours:

_x000D_
_x000D_
/*css to add back colours for badges and make use of the colours*/_x000D_
.badge-default {_x000D_
  background-color: #999999;_x000D_
}_x000D_
_x000D_
.badge-primary {_x000D_
  background-color: #428bca;_x000D_
}_x000D_
_x000D_
.badge-success {_x000D_
  background-color: #5cb85c;_x000D_
}_x000D_
_x000D_
.badge-info {_x000D_
  background-color: #5bc0de;_x000D_
}_x000D_
_x000D_
.badge-warning {_x000D_
  background-color: #f0ad4e;_x000D_
}_x000D_
_x000D_
.badge-danger {_x000D_
  background-color: #d9534f;_x000D_
}
_x000D_
_x000D_
_x000D_

Multiple "order by" in LINQ

This should work for you:

var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

What's the difference between `raw_input()` and `input()` in Python 3?

Python 2:

  • raw_input() takes exactly what the user typed and passes it back as a string.

  • input() first takes the raw_input() and then performs an eval() on it as well.

The main difference is that input() expects a syntactically correct python statement where raw_input() does not.

Python 3:

  • raw_input() was renamed to input() so now input() returns the exact string.
  • Old input() was removed.

If you want to use the old input(), meaning you need to evaluate a user input as a python statement, you have to do it manually by using eval(input()).

How to check if a date is greater than another in Java?

You can use Date.before() or Date.after() or Date.equals() for date comparison.

Taken from here:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDiff {

    public static void main( String[] args )
    {
        compareDates("2017-01-13 00:00:00", "2017-01-14 00:00:00");// output will be Date1 is before Date2
        compareDates("2017-01-13 00:00:00", "2017-01-12 00:00:00");//output will be Date1 is after Date2
        compareDates("2017-01-13 00:00:00", "2017-01-13 10:20:30");//output will be Date1 is before Date2 because date2 is ahead of date 1 by 10:20:30 hours
        compareDates("2017-01-13 00:00:00", "2017-01-13 00:00:00");//output will be Date1 is equal Date2 because both date and time are equal
    }

    public static void compareDates(String d1,String d2)
    {
        try{
            // If you already have date objects then skip 1

            //1
            // Create 2 dates starts
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf.parse(d1);
            Date date2 = sdf.parse(d2);

            System.out.println("Date1"+sdf.format(date1));
            System.out.println("Date2"+sdf.format(date2));System.out.println();

            // Create 2 dates ends
            //1

            // Date object is having 3 methods namely after,before and equals for comparing
            // after() will return true if and only if date1 is after date 2
            if(date1.after(date2)){
                System.out.println("Date1 is after Date2");
            }
            // before() will return true if and only if date1 is before date2
            if(date1.before(date2)){
                System.out.println("Date1 is before Date2");
            }

            //equals() returns true if both the dates are equal
            if(date1.equals(date2)){
                System.out.println("Date1 is equal Date2");
            }

            System.out.println();
        }
        catch(ParseException ex){
            ex.printStackTrace();
        }
    }

    public static void compareDates(Date date1,Date date2)
    {
        // if you already have date objects then skip 1
        //1

        //1

        //date object is having 3 methods namely after,before and equals for comparing
        //after() will return true if and only if date1 is after date 2
        if(date1.after(date2)){
            System.out.println("Date1 is after Date2");
        }

        //before() will return true if and only if date1 is before date2
        if(date1.before(date2)){
            System.out.println("Date1 is before Date2");
        }

        //equals() returns true if both the dates are equal
        if(date1.equals(date2)){
            System.out.println("Date1 is equal Date2");
        }

        System.out.println();
    }
}

Print array elements on separate lines in Bash?

Another useful variant is pipe to tr:

echo "${my_array[@]}" | tr ' ' '\n'

This looks simple and compact

How do you do natural logs (e.g. "ln()") with numpy in Python?

You could simple just do the reverse by making the base of log to e.

import math

e = 2.718281

math.log(e, 10) = 2.302585093
ln(10) = 2.30258093

How to get a DOM Element from a JQuery Selector

You can access the raw DOM element with:

$("table").get(0);

or more simply:

$("table")[0];

There isn't actually a lot you need this for however (in my experience). Take your checkbox example:

$(":checkbox").click(function() {
  if ($(this).is(":checked")) {
    // do stuff
  }
});

is more "jquery'ish" and (imho) more concise. What if you wanted to number them?

$(":checkbox").each(function(i, elem) {
  $(elem).data("index", i);
});
$(":checkbox").click(function() {
  if ($(this).is(":checked") && $(this).data("index") == 0) {
    // do stuff
  }
});

Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.

Java Command line arguments

public class YourClass {
    public static void main(String[] args) {
        if (args.length > 0 && args[0].equals("a")){
            //...
        }
    }
}

Skip download if files exist in wget?

When running Wget with -r or -p, but without -N, -nd, or -nc, re-downloading a file will result in the new copy simply overwriting the old.

So adding -nc will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.

See more info at GNU.

Updating a local repository with changes from a GitHub repository

This should work for every default repo:

git pull origin master

If your default branch is different than master, you will need to specify the branch name:

git pull origin my_default_branch_name

Mod of negative number is melting my brain

I like the trick presented by Peter N Lewis on this thread: "If n has a limited range, then you can get the result you want simply by adding a known constant multiple of [the divisor] that is greater that the absolute value of the minimum."

So if I have a value d that is in degrees and I want to take

d % 180f

and I want to avoid the problems if d is negative, then instead I just do this:

(d + 720f) % 180f

This assumes that although d may be negative, it is known that it will never be more negative than -720.

Getting a slice of keys from a map

This is an old question, but here's my two cents. PeterSO's answer is slightly more concise, but slightly less efficient. You already know how big it's going to be so you don't even need to use append:

keys := make([]int, len(mymap))

i := 0
for k := range mymap {
    keys[i] = k
    i++
}

In most situations it probably won't make much of a difference, but it's not much more work, and in my tests (using a map with 1,000,000 random int64 keys and then generating the array of keys ten times with each method), it was about 20% faster to assign members of the array directly than to use append.

Although setting the capacity eliminates reallocations, append still has to do extra work to check if you've reached capacity on each append.

org.xml.sax.SAXParseException: Content is not allowed in prolog

To fix the BOM issue on Unix / Linux systems:

  1. Check if there's an unwanted BOM character: hexdump -C myfile.xml | more An unwanted BOM character will appear at the start of the file as ...<?xml>

  2. Alternatively, do file myfile.xml. A file with a BOM character will appear as: myfile.xml: XML 1.0 document text, UTF-8 Unicode (with BOM) text

  3. Fix a single file with: tail -c +4 myfile.xml > temp.xml && mv temp.xml myfile.xml

  4. Repeat 1 or 2 to check the file has been sanitised. Probably also sensible to do view myfile.xml to check contents have stayed.

Here's a bash script to sanitise a whole folder of XML files:

#!/usr/bin/env bash

# This script is to sanitise XML files to remove any BOM characters

has_bom() { head -c3 "$1" | LC_ALL=C grep -qe '\xef\xbb\xbf'; }

for filename in *.xml ; do
  if has_bom ${filename}; then
    tail -c +4 ${filename} > temp.xml
    mv temp.xml ${filename}
  fi
done

How can you represent inheritance in a database?

The another way to do it, is using the INHERITS component. For example:

CREATE TABLE person (
    id int ,
    name varchar(20),
    CONSTRAINT pessoa_pkey PRIMARY KEY (id)
);

CREATE TABLE natural_person (
    social_security_number varchar(11),
    CONSTRAINT pessoaf_pkey PRIMARY KEY (id)
) INHERITS (person);


CREATE TABLE juridical_person (
    tin_number varchar(14),
    CONSTRAINT pessoaj_pkey PRIMARY KEY (id)
) INHERITS (person);

Thus it's possible to define a inheritance between tables.

How to auto-reload files in Node.js?

solution at: http://github.com/shimondoodkin/node-hot-reload

notice that you have to take care by yourself of the references used.

that means if you did : var x=require('foo'); y=x;z=x.bar; and hot reloaded it.

it means you have to replace the references stored in x, y and z. in the hot reaload callback function.

some people confuse hot reload with auto restart my nodejs-autorestart module also has upstart integration to enable auto start on boot. if you have a small app auto restart is fine, but when you have a large app hot reload is more suitable. simply because hot reload is faster.

Also I like my node-inflow module.

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

convert a JavaScript string variable to decimal/money

This works:

var num = parseFloat(document.getElementById(amtid4).innerHTML, 10).toFixed(2);

How to make a select with array contains value clause in psql

SELECT * FROM table WHERE arr && '{s}'::text[];

Compare two arrays for containment.

What should every programmer know about security?

  1. Why is is important.
  2. It is all about trade-offs.
  3. Cryptography is largely a distraction from security.

How to change a PG column to NULLABLE TRUE?

From the fine manual:

ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;

There's no need to specify the type when you're just changing the nullability.

Spring Boot Rest Controller how to return different HTTP status codes?

A nice way is to use Spring's ResponseStatusException

Rather than returning a ResponseEntityor similar you simply throw the ResponseStatusException from the controller with an HttpStatus and cause, for example:

throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Cause description here");

or:

throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "Cause description here");

This results in a response to the client containing the HTTP status (e.g. 400 Bad request) with a body like:

{
  "timestamp": "2020-07-09T04:43:04.695+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "Cause description here",
  "path": "/test-api/v1/search"
}

Get Root Directory Path of a PHP project

You could also use realpath.

realpath(".") returns your document root.

You can call realpath with your specific path. Note that it will NOT work if the target folder or file does not exist. In such case it will return false, which could be useful for testing if a file exists.

In my case I needed to specify a path for a new file to be written to disk, and the solution was to append the path relative to document root:

$filepath = realpath(".") . "/path/to/newfile.txt";

Hope this helps anyone.

Call Activity method from adapter

if (parent.getContext() instanceof yourActivity) {
  //execute code
}

this condition will enable you to execute something if the Activity which has the GroupView that requesting views from the getView() method of your adapter is yourActivity

NOTE : parent is that GroupView

How to generate auto increment field in select query

here's for SQL server, Oracle, PostgreSQL which support window functions.

SELECT  ROW_NUMBER() OVER (ORDER BY first_name, last_name)  Sequence_no,
        first_name,
        last_name
FROM    tableName

Multiple select in Visual Studio?

From Visual Studio 2017 Version 15.8, Ctrl + Alt + Click is now supposed to be a built-in way to manage multiple carets.

https://blogs.msdn.microsoft.com/visualstudio/2018/08/30/improving-your-productivity-in-the-visual-studio-editor/

How to display loading message when an iFrame is loading?

$('iframe').load(function(){
      $(".loading").remove();
    alert("iframe is done loading")
}).show();


<iframe src="http://www.google.com" style="display:none;" width="600" height="300"/>
<div class="loading" style="width:600px;height:300px;">iframe loading</div>

Build project into a JAR automatically in Eclipse

Creating a builder launcher is an issue since 2 projects cannot have the same external tool build name. Each name has to be unique. I am currently facing this issue to automate my build and copy the JAR to an external location.

I am using IBM's Zip Builder, but that is just a help but not doing the real.

People can try using IBM ZIP Creation plugin. http://www.ibm.com/developerworks/websphere/library/techarticles/0112_deboer/deboer2.html#download

Is there a method for String conversion to Title Case?

Here's another take based on @dfa's and @scottb's answers that handles any non-letter/digit characters:

public final class TitleCase {

    public static String toTitleCase(String input) {

        StringBuilder titleCase = new StringBuilder(input.length());
        boolean nextTitleCase = true;

        for (char c : input.toLowerCase().toCharArray()) {
            if (!Character.isLetterOrDigit(c)) {
                nextTitleCase = true;
            } else if (nextTitleCase) {
                c = Character.toTitleCase(c);
                nextTitleCase = false;
            }
            titleCase.append(c);
        }

        return titleCase.toString();
    }

}

Given input:

MARY ÄNN O’CONNEŽ-ŠUSLIK

the output is

Mary Änn O’Connež-Šuslik

Simple pthread! C++

Because the main thread exits.

Put a sleep in the main thread.

cout << "Hello";
sleep(1);

return 0;

The POSIX standard does not specify what happens when the main thread exits.
But in most implementations this will cause all spawned threads to die.

So in the main thread you should wait for the thread to die before you exit. In this case the simplest solution is just to sleep and give the other thread a chance to execute. In real code you would use pthread_join();

#include <iostream>
#include <pthread.h>
using namespace std;

#if defined(__cplusplus)
extern "C"
#endif
void *print_message(void*)
{
    cout << "Threading\n";
}



int main() 
{
    pthread_t t1;

    pthread_create(&t1, NULL, &print_message, NULL);
    cout << "Hello";

    void* result;
    pthread_join(t1,&result);

    return 0;
}

How to loop over a Class attributes in Java?

Accessing the fields directly is not really good style in java. I would suggest creating getter and setter methods for the fields of your bean and then using then Introspector and BeanInfo classes from the java.beans package.

MyBean bean = new MyBean();
BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.class);
for (PropertyDescriptor propertyDesc : beanInfo.getPropertyDescriptors()) {
    String propertyName = propertyDesc.getName();
    Object value = propertyDesc.getReadMethod().invoke(bean);
}

What is the most efficient way to deep clone an object in JavaScript?

There are a lot of answers, but none of them gave the desired effect I needed. I wanted to utilize the power of jQuery's deep copy... However, when it runs into an array, it simply copies the reference to the array and deep copies the items in it. To get around this, I made a nice little recursive function that will create a new array automatically.

(It even checks for kendo.data.ObservableArray if you want it to! Though, make sure you make sure you call kendo.observable(newItem) if you want the Arrays to be observable again.)

So, to fully copy an existing item, you just do this:

var newItem = jQuery.extend(true, {}, oldItem);
createNewArrays(newItem);


function createNewArrays(obj) {
    for (var prop in obj) {
        if ((kendo != null && obj[prop] instanceof kendo.data.ObservableArray) || obj[prop] instanceof Array) {
            var copy = [];
            $.each(obj[prop], function (i, item) {
                var newChild = $.extend(true, {}, item);
                createNewArrays(newChild);
                copy.push(newChild);
            });
            obj[prop] = copy;
        }
    }
}

In Bash, how can I check if a string begins with some value?

I prefer the other methods already posted, but some people like to use:

case "$HOST" in 
    user1|node*) 
            echo "yes";;
        *)
            echo "no";;
esac

Edit:

I've added your alternates to the case statement above

In your edited version you have too many brackets. It should look like this:

if [[ $HOST == user1 || $HOST == node* ]];

How to configure PHP to send e-mail?

Usually a good place to start when you run into problems is the manual. The page on configuring email explains that there's a big difference between the PHP mail command running on MSWindows and on every other operating system; it's a good idea when posting a question to provide relevant information on how that part of your system is configured and what operating system it is running on.

Your PHP is configured to talk to an SMTP server - the default for an MSWindows machine, but either you have no MTA installed or it's blocking connections. While for a commercial website running your own MTA robably comes quite high on the list of things to do, it is not a trivial exercise - you really need to know what you're doing to get one configured and running securely. It would make a lot more sense in your case to use a service configured and managed by someone else.

Since you'll be connecting to a remote MTA using a gmail address, then you should probably use Gmail's server; you will need SMTP authenticaton and probably SSL support - neither of which are supported by the mail() function in PHP. There's a simple example here using swiftmailer with gmail or here's an example using phpmailer

Calling startActivity() from outside of an Activity context

If you are invoking share Intent in Cordova plugin, setting the Flag will not help. Instead use this -

cordova.getActivity().startActivity(Intent.createChooser(shareIntent, "title"));

How can I create a two dimensional array in JavaScript?

This is mentioned in a few of the comments, but using Array.fill() will help construct a 2-d array:

function create2dArr(x,y) {
    var arr = [];
    for(var i = 0; i < y; i++) {
        arr.push(Array(x).fill(0));
    }
    return arr; 
}

this will result in an array of length x, y times in the returned array.

Nesting queries in SQL

Query below should help you achieve what you want.

select scountry, headofstate from data 
where data.scountry like 'a%'and ttlppl>=100000

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

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

though i take the url from an input, it's easy adjustable to the real url.

var value = 0;

$('#check').click(function()
{
    var originalURL = $('#test').val();
    var exists = originalURL.indexOf('&view-all');

    if(exists === -1)
    {
        $('#test').val(originalURL + '&view-all=value' + value++);
    }
    else
    {
        $('#test').val(originalURL.substr(0, exists + 15) + value++);
    }
});

http://jsfiddle.net/8YPh9/31/

How can I get the list of files in a directory using C or C++?

Unfortunately the C++ standard does not define a standard way of working with files and folders in this way.

Since there is no cross platform way, the best cross platform way is to use a library such as the boost filesystem module.

Cross platform boost method:

The following function, given a directory path and a file name, recursively searches the directory and its sub-directories for the file name, returning a bool, and if successful, the path to the file that was found.

bool find_file(const path & dir_path,         // in this directory,
               const std::string & file_name, // search for this name,
               path & path_found)             // placing path here if found
{
    if (!exists(dir_path)) 
        return false;

    directory_iterator end_itr; // default construction yields past-the-end

    for (directory_iterator itr(dir_path); itr != end_itr; ++itr)
    {
        if (is_directory(itr->status()))
        {
            if (find_file(itr->path(), file_name, path_found)) 
                return true;
        }
        else if (itr->leaf() == file_name) // see below
        {
            path_found = itr->path();
            return true;
        }
    }
    return false;
}

Source from the boost page mentioned above.

For Unix/Linux based systems:

You can use opendir / readdir / closedir.

Sample code which searches a directory for entry ``name'' is:

len = strlen(name);
dirp = opendir(".");
while ((dp = readdir(dirp)) != NULL)
        if (dp->d_namlen == len && !strcmp(dp->d_name, name)) {
                (void)closedir(dirp);
                return FOUND;
        }
(void)closedir(dirp);
return NOT_FOUND;

Source code from the above man pages.

For a windows based systems:

You can use the Win32 API FindFirstFile / FindNextFile / FindClose functions.

The following C++ example shows you a minimal use of FindFirstFile.

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA FindFileData;
   HANDLE hFind;

   if( argc != 2 )
   {
      _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]);
      return;
   }

   _tprintf (TEXT("Target file is %s\n"), argv[1]);
   hFind = FindFirstFile(argv[1], &FindFileData);
   if (hFind == INVALID_HANDLE_VALUE) 
   {
      printf ("FindFirstFile failed (%d)\n", GetLastError());
      return;
   } 
   else 
   {
      _tprintf (TEXT("The first file found is %s\n"), 
                FindFileData.cFileName);
      FindClose(hFind);
   }
}

Source code from the above msdn pages.

How to group an array of objects by key

With lodash/fp you can create a function with _.flow() that 1st groups by a key, and then map each group, and omits a key from each item:

_x000D_
_x000D_
const { flow, groupBy, mapValues, map, omit } = _;_x000D_
_x000D_
const groupAndOmitBy = key => flow(_x000D_
  groupBy(key),_x000D_
  mapValues(map(omit(key)))_x000D_
);_x000D_
_x000D_
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
const groupAndOmitMake = groupAndOmitBy('make');_x000D_
_x000D_
const result = groupAndOmitMake(cars);_x000D_
_x000D_
console.log(result);
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
_x000D_
_x000D_
_x000D_

How to prevent the "Confirm Form Resubmission" dialog?

Quick Answer

Use different methods to load the form and save/process form.

Example.

Login.php

Load login form at Login/index Validate login at Login/validate

On Success

Redirect the user to User/dashboard

On failure

Redirect the user to login/index

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

If you use linq and want to keep your code short, I recommand to always use !=null

And this is why:

Let imagine we have some class Foo with a nullable double variable SomeDouble

public class Foo
{
    public double? SomeDouble;
    //some other properties
}   

If somewhere in our code we want to get all Foo with a non null SomeDouble values from a collection of Foo (assuming some foos in the collection can be null too), we end up with at least three way to write our function (if we use C# 6) :

public IEnumerable<Foo> GetNonNullFoosWithSomeDoubleValues(IEnumerable<Foo> foos)
{
     return foos.Where(foo => foo?.SomeDouble != null);
     return foos.Where(foo=>foo?.SomeDouble.HasValue); // compile time error
     return foos.Where(foo=>foo?.SomeDouble.HasValue == true); 
     return foos.Where(foo=>foo != null && foo.SomeDouble.HasValue); //if we don't use C#6
}

And in this kind of situation I recommand to always go for the shorter one

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

Your target domain might refuse to send you information. This can work as a filter based on browser agent or any other header information. This is a defense against bots, crawlers or any unwanted applications.

Dialog with transparent background in Android

For anyone using a custom dialog with a custom class you need to change the transparency in the class add this line in the onCreate():

getWindow().setBackgroundDrawableResource(android.R.color.transparent);

AutoComplete TextBox in WPF

You can find one in the WPF Toolkit, which is also available via NuGet.

This article demos how to create a textbox which can auto-suggest items at runtime based on input, in this case, disk drive folders. WPF AutoComplete Folder TextBox

Also take a look at this nice Reusable WPF Autocomplete TextBox, it was for me very usable.

ansible: lineinfile for several lines?

Here is a noise-free version of the solution which is to use with_items:

- name: add lines
  lineinfile: 
    dest: fruits.txt
    line: '{{ item }}'
  with_items:
    - 'Orange'
    - 'Apple'
    - 'Banana' 

For each item, if the item exists in fruits.txt no action is taken.

If the item does not exist it will be appended to the end of the file.

Easy-peasy.

Using Caps Lock as Esc in Mac OS X

Open up Keyboard preferences and click modifier keys... you can change the caps lock key to control, option, escape, or command.

enter image description here

What is the Java equivalent of PHP var_dump?

I like to use GSON because it's often already a dependency of the type of projects I'm working on:

public static String getDump(Object o) {
    return new GsonBuilder().setPrettyPrinting().create().toJson(o);
}

Or substitute GSON for any other JSON library you use.

Onclick function based on element id

Make sure your code is in DOM Ready as pointed by rocket-hazmat

.click()

$('#RootNode').click(function(){
  //do something
});

document.getElementById("RootNode").onclick = function(){//do something}


.on()

Use event Delegation/

$(document).on("click", "#RootNode", function(){
   //do something
});


Try

Wrap Code in Dom Ready

$(document).ready(function(){
    $('#RootNode').click(function(){
     //do something
    });
});

Is there a math nCr function in python?

Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, use math.factorial:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) / f(r) / f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

In Python 3, use the integer division // instead of / to avoid overflows:

return f(n) // f(r) // f(n-r)

Output

6

Symfony2 Setting a default choice field selection

The form should map the species->id value automatically to the selected entity select field. For example if your have a Breed entity that has a OnetoOne relationship with a Species entity in a join table called 'breed_species':

class Breed{

    private $species;

    /**
    * @ORM\OneToOne(targetEntity="BreedSpecies", mappedBy="breed")
    */
    private $breedSpecies;

    public function getSpecies(){
       return $breedSpecies->getSpecies();
    }

    private function getBreedSpecies(){
       return $this->$breedSpecies;
    }
}

The field 'species' in the form class should pick up the species->id value from the 'species' attribute object in the Breed class passed to the form.

Alternatively, you can explicitly set the value by explicitly passing the species entity into the form using SetData():

    $breedForm = $this->createForm( new BreedForm(), $breed );
    $species   = $breed->getBreedSpecies()->getSpecies();

    $breedForm->get('species')->setData( $species );

    return $this->render( 'AcmeBundle:Computer:edit.html.twig'
                        , array( 'breed'     => $breed
                               , 'breedForm' => $breedForm->createView()
            )
    );

Compare two files line by line and generate the difference in another file

You could use diff with following output formatting:

diff --old-line-format='' --unchanged-line-format='' file1 file2

--old-line-format='' , disable output for file1 if line was differ compare in file2.
--unchanged-line-format='', disable output if lines were same.

Get current application physical path within Application_Start

 protected void Application_Start(object sender, EventArgs e)
 {
     string path = Server.MapPath("/");
     //or 
     string path2 = Server.MapPath("~");
     //depends on your application needs

 }

How can I convert a string with dot and comma into a float in Python

Just remove the , with replace():

float("123,456.908".replace(',',''))

How to format LocalDate to string?

With the help of ProgrammersBlock posts I came up with this. My needs were slightly different. I needed to take a string and return it as a LocalDate object. I was handed code that was using the older Calendar and SimpleDateFormat. I wanted to make it a little more current. This is what I came up with.

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;


    void ExampleFormatDate() {

    LocalDate formattedDate = null;  //Declare LocalDate variable to receive the formatted date.
    DateTimeFormatter dateTimeFormatter;  //Declare date formatter
    String rawDate = "2000-01-01";  //Test string that holds a date to format and parse.

    dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;

    //formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
    //First, the rawDate string is formatted according to DateTimeFormatter.  Second, that formatted string is parsed into
    //the LocalDate formattedDate object.
    formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));

}

Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.

How to change content on hover

This little and simple trick I just learnt may help someone trying to avoid :before or :after pseudo elements altogether (for whatever reason) in changing text on hover. You can add both texts in the HTML, but vary the CSS 'display' property based on hover. Assuming the second text 'Add' has a class named 'add-label'; here is a little modification:

span.add-label{
 display:none;
}
.item:hover span.align{
 display:none;
}
.item:hover span.add-label{
 display:block;
}

Here is a demonstration on codepen: https://codepen.io/ifekt/pen/zBaEVJ

What does print(... sep='', '\t' ) mean?

sep='' ignore whiteSpace. see the code to understand.Without sep=''

from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
    print(*i)

output:

HACK 2
A C
A H
A K
C A
C H
C K
H A
H C
H K
K A
K C
K H

using sep='' The code and output.

from itertools import permutations
s,k = input().split()
for i in list(permutations(sorted(s), int(k))):
    print(*i,sep='')

output:

HACK 2
AC
AH
AK
CA
CH
CK
HA
HC
HK
KA
KC
KH

How to add a margin to a table row <tr>

A way to mimic the margin on the row would be to use the pseudo selector to add some spacing on the td.

.highlight td::before, .highlight td::after
{
  content:"";
  height:10px;
  display:block;
}

This way anything marked with the highlight class will be separated top and bottom.

https://jsfiddle.net/d0zmsrfs/

Latest jQuery version on Google's CDN

Here's an updated link.

There are updated now and then, just keep checking for the latest version.

Getting started with OpenCV 2.4 and MinGW on Windows 7

The instructions in @bsdnoobz answer are indeed helpful, but didn't get OpenCV to work on my system.

Apparently I needed to compile the library myself in order to get it to work, and not count on the pre-built binaries (which caused my programs to crash, probably due to incompatibility with my system).

I did get it to work, and wrote a comprehensive guide for compiling and installing OpenCV, and configuring Netbeans to work with it.

For completeness, it is also provided below.


When I first started using OpenCV, I encountered two major difficulties:

  1. Getting my programs NOT to crash immediately.
  2. Making Netbeans play nice, and especially getting timehe debugger to work.

I read many tutorials and "how-to" articles, but none was really comprehensive and thorough. Eventually I succeeded in setting up the environment; and after a while of using this (great) library, I decided to write this small tutorial, which will hopefully help others.

The are three parts to this tutorial:

  1. Compiling and installing OpenCV.
  2. Configuring Netbeans.
  3. An example program.

The environment I use is: Windows 7, OpenCV 2.4.0, Netbeans 7 and MinGW 3.20 (with compiler gcc 4.6.2).

Assumptions: You already have MinGW and Netbeans installed on your system.

Compiling and installing OpenCV

When downloading OpenCV, the archive actually already contains pre-built binaries (compiled libraries and DLL's) in the 'build' folder. At first, I tried using those binaries, assuming somebody had already done the job of compiling for me. That didn't work.

Eventually I figured I have to compile the entire library on my own system in order for it to work properly.

Luckily, the compilation process is rather easy, thanks to CMake. CMake (stands for Cross-platform Make) is a tool which generates makefiles specific to your compiler and platform. We will use CMake in order to configure our building and compilation settings, generate a 'makefile', and then compile the library.

The steps are:

  1. Download CMake and install it (in the installation wizard choose to add CMake to the system PATH).
  2. Download the 'release' version of OpenCV.
  3. Extract the archive to a directory of your choice. I will be using c:/opencv/.
  4. Launch CMake GUI.
    1. Browse for the source directory c:/opencv/.
    2. Choose where to build the binaries. I chose c:/opencv/release.
      CMake Configuration - 1
    3. Click 'Configure'. In the screen that opens choose the generator according to your compiler. In our case it's 'MinGW Makefiles'.
      CMake Configuration - 2
    4. Wait for everything to load, afterwards you will see this screen:
      CMake Configuration - 3
    5. Change the settings if you want, or leave the defaults. When you're done, press 'Configure' again. You should see 'Configuration done' at the log window, and the red background should disappear from all the cells.
      CMake Configuration - 4
    6. At this point CMake is ready to generate the makefile with which we will compile OpenCV with our compiler. Click 'Generate' and wait for the makefile to be generated. When the process is finished you should see 'Generating done'. From this point we will no longer need CMake.
  5. Open MinGW shell (The following steps can also be done from Windows' command prompt).
    1. Enter the directory c:/opencv/release/.
    2. Type mingw32-make and press enter. This should start the compilation process.
      MinGW Make
      MinGW Make - Compilation
    3. When the compilation is done OpenCV's binaries are ready to be used.
    4. For convenience, we should add the directory C:/opencv/release/bin to the system PATH. This will make sure our programs can find the needed DLL's to run.

Configuring Netbeans

Netbeans should be told where to find the header files and the compiled libraries (which were created in the previous section).

The header files are needed for two reasons: for compilation and for code completion. The compiled libraries are needed for the linking stage.

Note: In order for debugging to work, the OpenCV DLL's should be available, which is why we added the directory which contains them to the system PATH (previous section, step 5.4).

First, you should verify that Netbeans is configured correctly to work with MinGW. Please see the screenshot below and verify your settings are correct (considering paths changes according to your own installation). Also note that the make command should be from msys and not from Cygwin.

Netbeans MinGW Configuration

Next, for each new project you create in Netbeans, you should define the include path (the directory which contains the header files), the libraries path and the specific libraries you intend to use. Right-click the project name in the 'projects' pane, and choose 'properties'. Add the include path (modify the path according to your own installation):

Netbeans Project Include Path

Add the libraries path:

Netbeans Libraries Path

Add the specific libraries you intend to use. These libraries will be dynamically linked to your program in the linking stage. Usually you will need the core library plus any other libraries according to the specific needs of your program.

Netbeans Include Libraries

That's it, you are now ready to use OpenCV!

Summary

Here are the general steps you need to complete in order to install OpenCV and use it with Netbeans:

  1. Compile OpenCV with your compiler.
  2. Add the directory which contains the DLL's to your system PATH (in our case: c:/opencv/release/bin).
  3. Add the directory which contains the header files to your project's include path (in our case: c:/opencv/build/include).
  4. Add the directory which contains the compiled libraries to you project's libraries path (in our case: c:/opencv/release/lib).
  5. Add the specific libraries you need to be linked with your project (for example: libopencv_core240.dll.a).

Example - "Hello World" with OpenCV

Here is a small example program which draws the text "Hello World : )" on a GUI window. You can use it to check that your installation works correctly. After compiling and running the program, you should see the following window:

OpenCV Hello World

#include "opencv2/opencv.hpp"
#include "opencv2/highgui/highgui.hpp"

using namespace cv;

int main(int argc, char** argv) {
    //create a gui window:
    namedWindow("Output",1);

    //initialize a 120X350 matrix of black pixels:
    Mat output = Mat::zeros( 120, 350, CV_8UC3 );

    //write text on the matrix:
    putText(output,
            "Hello World :)",
            cvPoint(15,70),
            FONT_HERSHEY_PLAIN,
            3,
            cvScalar(0,255,0),
            4);

    //display the image:
    imshow("Output", output);

    //wait for the user to press any key:
    waitKey(0);

    return 0;
}

PHP DOMDocument loadHTML not encoding UTF-8 correctly

The only thing that worked for me was the accepted answer of

$profile = '<p>???????????????????????9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();

HOWEVER

This brought about new issues, of having <?xml encoding="utf-8" ?> in the output of the document.

The solution for me was then to do

foreach ($doc->childNodes as $xx) {
    if ($xx instanceof \DOMProcessingInstruction) {
        $xx->parentNode->removeChild($xx);
    }
}

Some solutions told me that to remove the xml header, that I had to perform

$dom->saveXML($dom->documentElement);

This didn't work for me as for a partial document (e.g. a doc with two <p> tags), only one of the <p> tags where being returned.

Bash Script : what does #!/bin/bash mean?

In bash script, what does #!/bin/bash at the 1st line mean ?

In Linux system, we have shell which interprets our UNIX commands. Now there are a number of shell in Unix system. Among them, there is a shell called bash which is very very common Linux and it has a long history. This is a by default shell in Linux.

When you write a script (collection of unix commands and so on) you have a option to specify which shell it can be used. Generally you can specify which shell it wold be by using Shebang(Yes that's what it's name).

So if you #!/bin/bash in the top of your scripts then you are telling your system to use bash as a default shell.

Now coming to your second question :Is there a difference between #!/bin/bash and #!/bin/sh ?

The answer is Yes. When you tell #!/bin/bash then you are telling your environment/ os to use bash as a command interpreter. This is hard coded thing.

Every system has its own shell which the system will use to execute its own system scripts. This system shell can be vary from OS to OS(most of the time it will be bash. Ubuntu recently using dash as default system shell). When you specify #!/bin/sh then system will use it's internal system shell to interpreting your shell scripts.

Visit this link for further information where I have explained this topic.

Hope this will eliminate your confusions...good luck.

sizing div based on window width

Live Demo

Here is an actual implementation of what you described. I rewrote your code a bit using the latest best practices to actualize is. If you resize your browser windows under 1000px, the image's left and right side will be cropped using negative margins and it will be 300px narrower.

<style>
   .container {
      position: relative;
      width: 100%;
   }

   .bg {
      position:relative;
      z-index: 1;
      height: 100%;
      min-width: 1000px;
      max-width: 1500px;
      margin: 0 auto;
   }

   .nebula {
      width: 100%;
   }

   @media screen and (max-width: 1000px) {
      .nebula {
         width: 100%;
         overflow: hidden;
         margin: 0 -150px 0 -150px;
      }
   }
</style>

<div class="container">
   <div class="bg">
      <img src="http://i.stack.imgur.com/tFshX.jpg" class="nebula">
   </div>
</div>

Is it possible to create static classes in PHP (like in C#)?

object cannot be defined staticly but this works

final Class B{
  static $var;
  static function init(){
    self::$var = new A();
}
B::init();

BigDecimal to string

// Convert BigDecimal number To String by using below method //

public static String RemoveTrailingZeros(BigDecimal tempDecimal)
{
    tempDecimal = tempDecimal.stripTrailingZeros();
    String tempString = tempDecimal.toPlainString();
    return tempString;
}

// Recall RemoveTrailingZeros
BigDecimal output = new BigDecimal(0);
String str = RemoveTrailingZeros(output);

Git - Ignore node_modules folder everywhere

just add different .gitignore files to mini project 1 and mini project 2. Each of the .gitignore files should /node_modules and you're good to go.

Bootstrap 4 - Glyphicons migration?

It is not shipped with bootstrap 4 yet, but now Bootstrap team is developing their icon library.

https://icons.getbootstrap.com/

https://github.com/twbs/icons

How to run Spring Boot web application in Eclipse itself?

In my case, I had to select the "src/main/java" and select the "Run As" menu Just like this, so that "Spring Boot App" would be displayed as here.

ld.exe: cannot open output file ... : Permission denied

  1. Open task manager -> Processes -> Click on .exe (Fibonacci.exe) -> End Process

    if it doesn't work

  2. Close eclipse IDE (or whatever IDE you use) and repeat step 1.

Create JPA EntityManager without persistence.xml configuration file

Yes you can without using any xml file using spring like this inside a @Configuration class (or its equivalent spring config xml):

@Bean
public LocalContainerEntityManagerFactoryBean emf(){
    properties.put("javax.persistence.jdbc.driver", dbDriverClassName);
    properties.put("javax.persistence.jdbc.url", dbConnectionURL);
    properties.put("javax.persistence.jdbc.user", dbUser); //if needed

    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setPersistenceProviderClass(org.eclipse.persistence.jpa.PersistenceProvider.class); //If your using eclipse or change it to whatever you're using
    emf.setPackagesToScan("com.yourpkg"); //The packages to search for Entities, line required to avoid looking into the persistence.xml
    emf.setPersistenceUnitName(SysConstants.SysConfigPU);
    emf.setJpaPropertyMap(properties);
    emf.setLoadTimeWeaver(new ReflectiveLoadTimeWeaver()); //required unless you know what your doing
    return emf;
}

Bash integer comparison

This script works!

#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
    echo this script requires a 1 or 0 as first parameter.
else
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
fi

But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:

#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
    echo "first parameter is $1"
    xinput set-prop 12 "Device Enabled" $0
else
    echo this script requires a 1 or 0 as first parameter.
fi

The output is the same1:

$ ./tmp.sh 
this script requires a 1 or 0 as first parameter.

$ ./tmp.sh 0
first parameter is 0

$ ./tmp.sh 1
first parameter is 1

$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.

[1] the second fails if the first argument is a string

#1130 - Host ‘localhost’ is not allowed to connect to this MySQL server

Use the IP instead:

DROP USER 'root'@'127.0.0.1'; GRANT ALL PRIVILEGES ON . TO 'root'@'%';

For more possibilities, see this link.

To create the root user, seeing as MySQL is local & all, execute the following from the command line (Start > Run > "cmd" without quotes):

mysqladmin -u root password 'mynewpassword'

Documentation, and Lost root access in MySQL.

Show week number with Javascript?

If you already use Angular, then you could profit $filter('date').

For example:

var myDate = new Date();
var myWeek = $filter('date')(myDate, 'ww');

Auto number column in SharePoint list

If you want something beyond the ID column that's there in all lists, you're probably going to have to resort to an Event Receiver on the list that "calculates" what the value of your unique identified should be or using a custom field type that has the required logic embedded in this. Unfortunately, both of these options will require writing and deploying custom code to the server and deploying assemblies to the GAC, which can be frowned upon in environments where you don't have complete control over the servers.

If you don't need the unique identifier to show up immediately, you could probably generate it via a workflow (either with SharePoint Designer or a custom WF workflow built in Visual Studio).

Unfortunately, calculated columns, which seem like an obvious solution, won't work for this purpose because the ID is not yet assigned when the calculation is attempted. If you go in after the fact and edit the item, the calculation may achieve what you want, but on initial creation of a new item it will not be calculated correctly.

Angularjs on page load call function

you can also use the below code.

function activateController(){
     console.log('HELLO WORLD');
}

$scope.$on('$viewContentLoaded', function ($evt, data) {
    activateController();
});

How can I specify a display?

Try installing the xorg-x11-xauth package.

How do I do a multi-line string in node.js?

As an aside to what folks have been posting here, I've heard that concatenation can be much faster than join in modern javascript vms. Meaning:

var a = 
[ "hey man, this is on a line",
  "and this is on another",
  "and this is on a third"
].join('\n');

Will be slower than:

var a = "hey man, this is on a line\n" + 
        "and this is on another\n" +
        "and this is on a third";    

In certain cases. http://jsperf.com/string-concat-versus-array-join/3

As another aside, I find this one of the more appealing features in Coffeescript. Yes, yes, I know, haters gonna hate.

html = '''
       <strong>
         cup of coffeescript
       </strong>
       '''

Its especially nice for html snippets. I'm not saying its a reason to use it, but I do wish it would land in ecma land :-(.

Josh

Drawing Isometric game worlds

If you have some tiles that exceed the bounds of your diamond, I recommend drawing in depth order:

...1...
..234..
.56789.
..abc..
...d...

Why does PEP-8 specify a maximum line length of 79 characters?

I am a programmer who has to deal with a lot of code on a daily basis. Open source and what has been developed in house.

As a programmer, I find it useful to have many source files open at once, and often organise my desktop on my (widescreen) monitor so that two source files are side by side. I might be programming in both, or just reading one and programming in the other.

I find it dissatisfying and frustrating when one of those source files is >120 characters in width, because it means I can't comfortably fit a line of code on a line of screen. It upsets formatting to line wrap.

I say '120' because that's the level to which I would get annoyed at code being wider than. After that many characters, you should be splitting across lines for readability, let alone coding standards.

I write code with 80 columns in mind. This is just so that when I do leak over that boundary, it's not such a bad thing.

Powershell folder size of folders without listing Subdirectories

This simple solution worked for me as well.

powershell -c "Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"

Using 'starts with' selector on individual class names

I'd recommend making "apple" its own class. You should avoid the starts-with/ends-with if you can because being able to select using div.apple would be a lot faster. That's the more elegant solution. Don't be afraid to split things out into separate classes if it makes the task simpler/faster.

mysql data directory location

Check where is the root folder of mysql with:

mysql_config

How to speed up insertion performance in PostgreSQL

For optimal Insertion performance disable the index if that's an option for you. Other than that, better hardware (disk, memory) is also helpful

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

unexpected T_VARIABLE, expecting T_FUNCTION

put public, protected or private before the $connection.

Read pdf files with php

your initial request is "I have a large PDF file that is a floor map for a building. "

I am afraid to tell you this might be harder than you guess.

Cause the last known lib everyones use to parse pdf is smalot, and this one is known to encounter issue regarding large file.

Here too, Lookig for a real php lib to parse pdf, without any memory peak that need a php configuration to disable memory limit as lot of "developers" does (which I guess is really not advisable).

see this post for more details about smalot performance : https://github.com/smalot/pdfparser/issues/163

jquery (or pure js) simulate enter key pressed for testing

For those who want to do this in pure javascript, look at:

Using standard KeyboardEvent

As Joe comment it, KeyboardEvent is now the standard.

Same example to fire an enter (keyCode 13):

const ke = new KeyboardEvent('keydown', {
    bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);

You can use this page help you to find the right keyboard event.


Outdated answer:

You can do something like (here for Firefox)

var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
    'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);

Postgres "psql not recognized as an internal or external command"

Windows 10

It could be that your server doesn't start automatically on windows 10 and you need to start it yourself after setting your Postgresql path using the following command in cmd:

pg_ctl -D "C:\Program Files\PostgreSQL\11.4\data" start

You need to be inside "C:\Program Files\PostgreSQL\11.4\bin" directory to execute the above command.

EX:

enter image description here

You still need to be inside the bin directory to work with psql

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

Conda command not found

Maybe you should type add this to your .bashrc or .zshrc

export PATH="/anaconda3/bin":$PATH

It worked for me.

How do I address unchecked cast warnings?

In this particular case, I would not store Maps into the HttpSession directly, but instead an instance of my own class, which in turn contains a Map (an implementation detail of the class). Then you can be sure that the elements in the map are of the right type.

But if you anyways want to check that the contents of the Map are of right type, you could use a code like this:

public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("a", 1);
    map.put("b", 2);
    Object obj = map;

    Map<String, Integer> ok = safeCastMap(obj, String.class, Integer.class);
    Map<String, String> error = safeCastMap(obj, String.class, String.class);
}

@SuppressWarnings({"unchecked"})
public static <K, V> Map<K, V> safeCastMap(Object map, Class<K> keyType, Class<V> valueType) {
    checkMap(map);
    checkMapContents(keyType, valueType, (Map<?, ?>) map);
    return (Map<K, V>) map;
}

private static void checkMap(Object map) {
    checkType(Map.class, map);
}

private static <K, V> void checkMapContents(Class<K> keyType, Class<V> valueType, Map<?, ?> map) {
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        checkType(keyType, entry.getKey());
        checkType(valueType, entry.getValue());
    }
}

private static <K> void checkType(Class<K> expectedType, Object obj) {
    if (!expectedType.isInstance(obj)) {
        throw new IllegalArgumentException("Expected " + expectedType + " but was " + obj.getClass() + ": " + obj);
    }
}

What is default list styling (CSS)?

You're resetting the margin on all elements in the second css block. Default margin is 40px - this should solve the problem:

.my_container ul {list-style:disc outside none; margin-left:40px;}

How to set standard encoding in Visual Studio

Do you want the files to save as UTF-8 because you are using special characters that would be lost in ASCII encoding? If that's the case, then there is a VS2008 global setting in Tools > Options > Environment > Documents, named Save documents as Unicode when data cannot be saved in codepage. When this is enabled, VS2008 will save as Unicode if certain characters cannot be represented in the otherwise-default codepage.

Also, which files are not being saved as UTF-8? All of my .cs, .csproj, .sln, .config, .as*x, etc, all save as UTF-8 (with signature, the byte order marks), by default.

How can I load webpage content into a div on page load?

Take a look into jQuery's .load() function:

<script>
    $(function(){
        $('#siteloader').load('http://www.somesitehere.com');
    });
</script>

However, this only works on the same domain of the JS file.

Clang vs GCC for my Linux Development project

I use both Clang and GCC, I find Clang has some useful warnings, but for my own ray-tracing benchmarks - its consistently 5-15% slower then GCC (take that with grain of salt of course, but attempted to use similar optimization flags for both).

So for now I use Clang static analysis and its warnings with complex macros: (though now GCC's warnings are pretty much as good - gcc4.8 - 4.9).

Some considerations:

  • Clang has no OpenMP support, only matters if you take advantage of that but since I do, its a limitation for me. (*****)
  • Cross compilation may not be as well supported (FreeBSD 10 for example still use GCC4.x for ARM), gcc-mingw for example is available on Linux... (YMMV).
  • Some IDE's don't yet support parsing Clangs output (QtCreator for example *****). EDIT: QtCreator now supports Clang's output
  • Some aspects of GCC are better documented and since GCC has been around for longer and is widely used, you might find it easier to get help with warnings / error messages.

***** - these areas are in active development and may soon be supported

How to check for a valid URL in Java?

Judging by the source code for URI, the

public URL(URL context, String spec, URLStreamHandler handler)

constructor does more validation than the other constructors. You might try that one, but YMMV.

How to add an element to Array and shift indexes?

Here is a quasi-oneliner that does it:

String[] prependedArray = new ArrayList<String>() {
  {
    add("newElement");
    addAll(Arrays.asList(originalArray));
  }
}.toArray(new String[0]);

Proper way of checking if row exists in table in PL/SQL block

select nvl(max(1), 0) from mytable;

This statement yields 0 if there are no rows, 1 if you have at least one row in that table. It's way faster than doing a select count(*). The optimizer "sees" that only a single row needs to be fetched to answer the question.

Here's a (verbose) little example:

declare
  YES constant      signtype := 1;
  NO  constant      signtype := 0;
  v_table_has_rows  signtype;
begin

  select nvl(max(YES), NO)
    into v_table_has_rows
    from mytable -- where ...
  ;

  if v_table_has_rows = YES then
    DBMS_OUTPUT.PUT_LINE ('mytable has at least one row');
  end if;

end;

Get current URL with jQuery?

To get the path, you can use:

var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url      = window.location.href;     // Returns full URL (https://example.com/path/example.html)
var origin   = window.location.origin;   // Returns base URL (https://example.com)

Rendering React Components from Array of Objects

this.data presumably contains all the data, so you would need to do something like this:

var stations = [];
var stationData = this.data.stations;

for (var i = 0; i < stationData.length; i++) {
    stations.push(
        <div key={stationData[i].call} className="station">
            Call: {stationData[i].call}, Freq: {stationData[i].frequency}
        </div>
    )
}

render() {
  return (
    <div className="stations">{stations}</div>
  )
}

Or you can use map and arrow functions if you're using ES6:

const stations = this.data.stations.map(station =>
    <div key={station.call} className="station">
      Call: {station.call}, Freq: {station.frequency}
    </div>
);

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

OK, they all have got some similarities, they do the same things for you in different and similar ways, I divide them in 3 main groups as below:


1) Module bundlers

webpack and browserify as popular ones, work like task runners but with more flexibility, aslo it will bundle everything together as your setting, so you can point to the result as bundle.js for example in one single file including the CSS and Javascript, for more details of each, look at the details below:

webpack

webpack is a module bundler for modern JavaScript applications. When webpack processes your application, it recursively builds a dependency graph that includes every module your application needs, then packages all of those modules into a small number of bundles - often only one - to be loaded by the browser.

It is incredibly configurable, but to get started you only need to understand Four Core Concepts: entry, output, loaders, and plugins.

This document is intended to give a high-level overview of these concepts, while providing links to detailed concept specific use-cases.

more here

browserify

Browserify is a development tool that allows us to write node.js-style modules that compile for use in the browser. Just like node, we write our modules in separate files, exporting external methods and properties using the module.exports and exports variables. We can even require other modules using the require function, and if we omit the relative path it’ll resolve to the module in the node_modules directory.

more here


2) Task runners

gulp and grunt are task runners, basically what they do, creating tasks and run them whenever you want, for example you install a plugin to minify your CSS and then run it each time to do minifying, more details about each:

gulp

gulp.js is an open-source JavaScript toolkit by Fractal Innovations and the open source community at GitHub, used as a streaming build system in front-end web development. It is a task runner built on Node.js and Node Package Manager (npm), used for automation of time-consuming and repetitive tasks involved in web development like minification, concatenation, cache busting, unit testing, linting, optimization etc. gulp uses a code-over-configuration approach to define its tasks and relies on its small, single-purposed plugins to carry them out. gulp ecosystem has 1000+ such plugins made available to choose from.

more here

grunt

Grunt is a JavaScript task runner, a tool used to automatically perform frequently used tasks such as minification, compilation, unit testing, linting, etc. It uses a command-line interface to run custom tasks defined in a file (known as a Gruntfile). Grunt was created by Ben Alman and is written in Node.js. It is distributed via npm. Presently, there are more than five thousand plugins available in the Grunt ecosystem.

more here


3) Package managers

package managers, what they do is managing plugins you need in your application and install them for you through github etc using package.json, very handy to update you modules, install them and sharing your app across, more details for each:

npm

npm is a package manager for the JavaScript programming language. It is the default package manager for the JavaScript runtime environment Node.js. It consists of a command line client, also called npm, and an online database of public packages, called the npm registry. The registry is accessed via the client, and the available packages can be browsed and searched via the npm website.

more here

bower

Bower can manage components that contain HTML, CSS, JavaScript, fonts or even image files. Bower doesn’t concatenate or minify code or do anything else - it just installs the right versions of the packages you need and their dependencies. To get started, Bower works by fetching and installing packages from all over, taking care of hunting, finding, downloading, and saving the stuff you’re looking for. Bower keeps track of these packages in a manifest file, bower.json.

more here

and the most recent package manager that shouldn't be missed, it's young and fast in real work environment compare to npm which I was mostly using before, for reinstalling modules, it do double checks the node_modules folder to check the existence of the module, also seems installing the modules takes less time:

yarn

Yarn is a package manager for your code. It allows you to use and share code with other developers from around the world. Yarn does this quickly, securely, and reliably so you don’t ever have to worry.

Yarn allows you to use other developers’ solutions to different problems, making it easier for you to develop your software. If you have problems, you can report issues or contribute back, and when the problem is fixed, you can use Yarn to keep it all up to date.

Code is shared through something called a package (sometimes referred to as a module). A package contains all the code being shared as well as a package.json file which describes the package.

more here


Oracle listener not running and won't start

1.Check the Environment variables (must be set for System and not for user):

ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server
ORACLE_SID = XE

2.Check if you have the right definition in listener.ora

XE =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
    )
  )

DEFAULT_SERVICE_LISTENER = (XE)

3.Restart the service (Services > OracleServiceXE)

After that you may see a new service called OracleXETNSListenerXE.
There is already an old OracleXETNSListener.

I started both and then I was able to make a successful connection.

Edit:

If everything is running but you still can't connect, check if there is no error: ORA-12557: TNS:protocol adapter not loadable.

To correct the error go back to the Environment variables and this time edit the one called: Path. Be sure that C:\oraclexe\app\oracle\product\11.2.0\server\bin is somewhere at the beginning, definitely before any other path pointing to a different version of the Oracle DB.

Cross Browser Flash Detection in Javascript

If you just wanted to check whether flash is enabled, this should be enough.

function testFlash() {

    var support = false;

    //IE only
    if("ActiveXObject" in window) {

        try{
            support = !!(new ActiveXObject("ShockwaveFlash.ShockwaveFlash"));
        }catch(e){
            support = false;
        }

    //W3C, better support in legacy browser
    } else {

        support = !!navigator.mimeTypes['application/x-shockwave-flash'];

    }

    return support;

}

Note: avoid checking enabledPlugin, some mobile browser has tap-to-enable flash plugin, and will trigger false negative.

How do I convert an interval into a number of hours with postgres?

If you convert table field:

  1. Define the field so it contains seconds:

     CREATE TABLE IF NOT EXISTS test (
         ...
         field        INTERVAL SECOND(0)
     );
    
  2. Extract the value. Remember to cast to int other wise you can get an unpleasant surprise once the intervals are big:

    EXTRACT(EPOCH FROM field)::int

How do I toggle an ng-show in AngularJS based on a boolean?

Basically I solved it by NOT-ing the isReplyFormOpen value whenever it is clicked:

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
    <!-- Form -->
</div>

C# error: Use of unassigned local variable

The compiler only knows that the code is or isn't reachable if you use "return". Think of Environment.Exit() as a function that you call, and the compiler don't know that it will close the application.

Why can I not switch branches?

you can reset your branch with HEAD

git reset --hard branch_name

then fetch branches and delete branches which are not on remote from local,

git fetch -p 

How to simulate a click with JavaScript?

const Discord = require("discord.js");
const superagent = require("superagent");

module.exports = {
    name: "hug",
    category: "action",
    description: "hug a user!",
    usage: "hug <user>",
    run: async (client, message, args) => {
    let hugUser = message.mentions.users.first() 
    if(!hugUser) return message.channel.send("You forgot to mention somebody.");
    let hugEmbed2 = new Discord.MessageEmbed()
    .setColor("#36393F")
    .setDescription(`**${message.author.username}** hugged **himself**`)
    .setImage("https://i.kym-cdn.com/photos/images/original/000/859/605/3e7.gif")
     .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
  if (hugUser.id === message.author.id) return message.channel.send(hugEmbed2);
    const {body} = await superagent
    .get(`https://nekos.life/api/v2/img/hug`);

    let hugEmbed = new Discord.MessageEmbed()
    .setDescription(`**${message.author.username}** hugged **${message.mentions.users.first().username}**`)
    .setImage(body.url)
    .setColor("#36393F")
     .setFooter(`© Yuki V5.3.1`, "https://cdn.discordapp.com/avatars/489219428358160385/19ad8d8c2fefd03fa0e1a2e49a2915c4.png")
    message.channel.send(hugEmbed)
}
}

HTML text input field with currency symbol

.currencyinput {
    border: 1px inset #ccc;

    border-left:none;
}
.currencyinput input {
    border: 0;`enter code here`
}

<input type="text" oninput="this.value = this.value.replace(/[^0-9]/.g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" style="text-align:right;border-right:none;outline:none" name="currency"><span class="currencyinput">%</span>

How do I make a Windows batch script completely silent?

Just add a >NUL at the end of the lines producing the messages.

For example,

COPY %scriptDirectory%test.bat %scriptDirectory%test2.bat >NUL

runOnUiThread in fragment

Use a Kotlin extension function

fun Fragment?.runOnUiThread(action: () -> Unit) {
    this ?: return
    if (!isAdded) return // Fragment not attached to an Activity
    activity?.runOnUiThread(action)
}

Then, in any Fragment you can just call runOnUiThread. This keeps calls consistent across activities and fragments.

runOnUiThread {
    // Call your code here
}

NOTE: If Fragment is no longer attached to an Activity, callback will not be called and no exception will be thrown

If you want to access this style from anywhere, you can add a common object and import the method:

object ThreadUtil {
    private val handler = Handler(Looper.getMainLooper())

    fun runOnUiThread(action: () -> Unit) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            handler.post(action)
        } else {
            action.invoke()
        }
    }
}

How to remove numbers from string using Regex.Replace?

text= re.sub('[0-9\n]',' ',text)

install regex in python which is re then do the following code.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It is important to define an id in the model

.DataSource(dataSource => dataSource
        .Ajax()
        .PageSize(20)
        .Model(model => model.Id(p => p.id))
    )

How to use Ajax.ActionLink?

For me this worked after I downloaded AJAX Unobtrusive library via NuGet :

 Search and install via NuGet Packages:   Microsoft.jQuery.Unobtrusive.Ajax

Than add in the view the references to jquery and AJAX Unobtrusive:

@Scripts.Render("~/bundles/jquery")
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"> </script>

Property getters and setters

Setters and getters in Swift apply to computed properties/variables. These properties/variables are not actually stored in memory, but rather computed based on the value of stored properties/variables.

See Apple's Swift documentation on the subject: Swift Variable Declarations.

Remove element from JSON Object

JSfiddle

function deleteEmpty(obj){
        for(var k in obj)
         if(k == "children"){
             if(obj[k]){
                     deleteEmpty(obj[k]);
             }else{
                   delete obj.children;
              } 
         }
    }

for(var i=0; i< a.children.length; i++){
 deleteEmpty(a.children[i])
}

How to set an iframe src attribute from a variable in AngularJS

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller.

You need to inject the $sce service in the controller and trustAsResourceUrl the url there.

In the controller:

function AppCtrl($scope, $sce) {
    // ...
    $scope.setProject = function (id) {
      $scope.currentProject = $scope.projects[id];
      $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    }
}

In the Template:

<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

With my centos 6.7 installation, not only did I have the problem starting httpd with root but also with xauth (getting /usr/bin/xauth: timeout in locking authority file /.Xauthority with underlying permission denied errors)

# setenforce 0

Fixed both issues.

C# - Winforms - Global Variables

public static class MyGlobals
{
  public static string Global1 = "Hello";
  public static string Global2 = "World";
}

public class Foo
{

    private void Method1()
    {
       string example = MyGlobals.Global1;
       //etc
    }
}

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How to count no of lines in text file and store the value into a variable using batch script?

for /f "usebackq" %A in (`TYPE c:\temp\file.txt ^| find /v /c "" `) do set numlines=%A

in a batch file, use %%A instead of %A

How do you return a JSON object from a Java Servlet

By Using Gson you can send json response see below code

You can see this code

@WebServlet(urlPatterns = {"/jsonResponse"})
public class JsonResponse extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    Student student = new Student(12, "Ram Kumar", "Male", "1234565678");
    Subject subject1 = new Subject(1, "Computer Fundamentals");
    Subject subject2 = new Subject(2, "Computer Graphics");
    Subject subject3 = new Subject(3, "Data Structures");
    Set subjects = new HashSet();
    subjects.add(subject1);
    subjects.add(subject2);
    subjects.add(subject3);
    student.setSubjects(subjects);
    Address address = new Address(1, "Street 23 NN West ", "Bhilai", "Chhattisgarh", "India");
    student.setAddress(address);
    Gson gson = new Gson();
    String jsonData = gson.toJson(student);
    PrintWriter out = response.getWriter();
    try {
        out.println(jsonData);
    } finally {
        out.close();
    }

  }
}

helpful from json response from servlet in java

What does Maven do, in theory and in practice? When is it worth to use it?

Maven is a build tool. Along with Ant or Gradle are Javas tools for building.
If you are a newbie in Java though just build using your IDE since Maven has a steep learning curve.

Calculating difference between two timestamps in Oracle in milliseconds

Above one has some syntax error, Please use following on oracle:

SELECT ROUND (totalSeconds / (24 * 60 * 60), 1) TotalTimeSpendIn_DAYS,
  ROUND (totalSeconds      / (60 * 60), 0) TotalTimeSpendIn_HOURS,
  ROUND (totalSeconds      / 60) TotalTimeSpendIn_MINUTES,
  ROUND (totalSeconds) TotalTimeSpendIn_SECONDS
FROM
  (SELECT ROUND ( EXTRACT (DAY FROM timeDiff) * 24 * 60 * 60 + EXTRACT (HOUR FROM timeDiff) * 60 * 60 + EXTRACT (MINUTE FROM timeDiff) * 60 + EXTRACT (SECOND FROM timeDiff)) totalSeconds
  FROM
    (SELECT TO_TIMESTAMP(TO_CHAR( date2 , 'yyyy-mm-dd HH24:mi:ss'), 'yyyy-mm-dd HH24:mi:ss') - TO_TIMESTAMP(TO_CHAR(date1, 'yyyy-mm-dd HH24:mi:ss'),'yyyy-mm-dd HH24:mi:ss') timeDiff
    FROM TABLENAME
    )
);

How to force view controller orientation in iOS 8?

Use this to lock view controller orientation, tested on IOS 9:

// Lock orientation to landscape right

-(UIInterfaceOrientationMask)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscapeRight;
}

-(NSUInteger)navigationControllerSupportedInterfaceOrientations:(UINavigationController *)navigationController {
    return UIInterfaceOrientationMaskLandscapeRight;
}

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

How to manually send HTTP POST requests from Firefox or Chrome browser?

Try Runscope. A free tool sampling their service is provided at https://www.hurl.it/ . You can set the method, authentication, headers, parameters, and body. Response shows status code, headers, and body. The response body can be formatted from JSON with a collapsable heirarchy. Paid accounts can automate test API calls and use return data to build new test calls. COI disclosure: I have no relationship to Runscope.

"No cached version... available for offline mode."

Just happened to me after upgrading to Android Studio 3.1. The Offline Work checkbox was unchecked, so no luck there.

I went to Settings > Build, Execution, Deployment > Compiler and the Command-line Options textfield contained --offline, so I just deleted that and everything worked.

setting screenshot

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

This usually happens when the version of one of the DLLs of the testing environment does not match the development environment.

Clean and Build your solution and take all your DLLs to the environment where the error is happening that should fix it

Try-Catch-End Try in VBScript doesn't seem to work

Sometimes, especially when you work with VB, you can miss obvious solutions. Like I was doing last 2 days.

the code, which generates error needs to be moved to a separate function. And in the beginning of the function you write On Error Resume Next. This is how an error can be "swallowed", without swallowing any other errors. Dividing code into small separate functions also improves readability, refactoring & makes it easier to add some new functionality.

Count the number of items in my array list

Using Java 8 stream API:

 String[] keys = new String[0];

// A map for keys and their count
Map<String, Long> keyCountMap = Arrays.stream(keys).
collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int uniqueItemIdCount= keyCountMap.size();

What is the current choice for doing RPC in Python?

You could try Ladon. It serves up multiple web server protocols at once so you can offer more flexibility at the client side.

http://pypi.python.org/pypi/ladon

@Autowired - No qualifying bean of type found for dependency

The thing is that both the application context and the web application context are registered in the WebApplicationContext during server startup. When you run the test you must explicitly tell which contexts to load.

Try this:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/beans.xml", "/mvc-dispatcher-servlet.xml"})

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

Clear the cache in JavaScript

Cache.delete() can be used for new chrome, firefox and opera.

How to take backup of a single table in a MySQL database?

You can use this code:

This example takes a backup of sugarcrm database and dumps the output to sugarcrm.sql

# mysqldump -u root -ptmppassword sugarcrm > sugarcrm.sql

# mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

The sugarcrm.sql will contain drop table, create table and insert command for all the tables in the sugarcrm database. Following is a partial output of sugarcrm.sql, showing the dump information of accounts_contacts table:

--

-- Table structure for table accounts_contacts

DROP TABLE IF EXISTS `accounts_contacts`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `accounts_contacts` (
`id` varchar(36) NOT NULL,
`contact_id` varchar(36) default NULL,
`account_id` varchar(36) default NULL,
`date_modified` datetime default NULL,
`deleted` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `idx_account_contact` (`account_id`,`contact_id`),
KEY `idx_contid_del_accid` (`contact_id`,`deleted`,`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

--

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

How to output a multiline string in Bash?

Here documents are often used for this purpose.

cat << EOF
usage: up [--level <n>| -n <levels>][--help][--version]

Report bugs to: 
up home page:
EOF

They are supported in all Bourne-derived shells including all versions of Bash.

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

This will get you the drives on the machine:

System.IO.DriveInfo.GetDrives()

These two methods will get you the bad characters to check:

System.IO.Path.GetInvalidFileNameChars();
System.IO.Path.GetInvalidPathChars();

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

ORA-12516, TNS:listener could not find available handler

I fixed this problem with sql command line:

connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;

Restart database.

How to put a div in center of browser using CSS?

Using this:

center-div { margin: auto; position: absolute; top: 50%; left: 50%; bottom: 0; right: 0; transform: translate(-50% -50%); }

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

Filename timestamp in Windows CMD batch script getting truncated

It wants the full time in DD-MM-YYYY_HH-MM-SS.TT where TT is the ticks. The exception says it all.

set default schema for a sql query

Try setuser. Example

declare @schema nvarchar (256)
set @schema=(
  select top 1 TABLE_SCHEMA
  from INFORMATION_SCHEMA.TABLES
  where TABLE_NAME='MyTable'
)
if @schema<>'dbo' setuser @schema

How to set the current working directory?

Perhaps this is what you are looking for:

import os
os.chdir(default_path)

Android: how to make keyboard enter button say "Search" and handle its click?

Hide keyboard when user clicks search. Addition to Robby Pond answer

private void performSearch() {
    editText.clearFocus();
    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    in.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    //...perform search
}

How should a model be structured in MVC?

In my case I have a database class that handle all the direct database interaction such as querying, fetching, and such. So if I had to change my database from MySQL to PostgreSQL there won't be any problem. So adding that extra layer can be useful.

Each table can have its own class and have its specific methods, but to actually get the data, it lets the database class handle it:

File Database.php

class Database {
    private static $connection;
    private static $current_query;
    ...

    public static function query($sql) {
        if (!self::$connection){
            self::open_connection();
        }
        self::$current_query = $sql;
        $result = mysql_query($sql,self::$connection);

        if (!$result){
            self::close_connection();
            // throw custom error
            // The query failed for some reason. here is query :: self::$current_query
            $error = new Error(2,"There is an Error in the query.\n<b>Query:</b>\n{$sql}\n");
            $error->handleError();
        }
        return $result;
    }
 ....

    public static function find_by_sql($sql){
        if (!is_string($sql))
            return false;

        $result_set = self::query($sql);
        $obj_arr = array();
        while ($row = self::fetch_array($result_set))
        {
            $obj_arr[] = self::instantiate($row);
        }
        return $obj_arr;
    }
}

Table object classL

class DomainPeer extends Database {

    public static function getDomainInfoList() {
        $sql = 'SELECT ';
        $sql .='d.`id`,';
        $sql .='d.`name`,';
        $sql .='d.`shortName`,';
        $sql .='d.`created_at`,';
        $sql .='d.`updated_at`,';
        $sql .='count(q.id) as queries ';
        $sql .='FROM `domains` d ';
        $sql .='LEFT JOIN queries q on q.domainId = d.id ';
        $sql .='GROUP BY d.id';
        return self::find_by_sql($sql);
    }

    ....
}

I hope this example helps you create a good structure.

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

For the first one: your program will go through the loop once for every row in the result set returned by the query. You can know in advance how many results there are by using mysql_num_rows().

For the second one: this time you are only using one row of the result set and you are doing something for each of the columns. That's what the foreach language construct does: it goes through the body of the loop for each entry in the array $row. The number of times the program will go through the loop is knowable in advance: it will go through once for every column in the result set (which presumably you know, but if you need to determine it you can use count($row)).

How to get all files under a specific directory in MATLAB?

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

DataRow: Select cell value by a given column name

You can get the column value in VB.net

Dim row As DataRow = fooTable.Rows(0)
Dim temp = Convert.ToString(row("ColumnName"))

And in C# you can use Jimmy's Answer, just be careful while converting it to ToString(). It can throw null exception if the data is null instead Use Convert.ToString(your_expression) to avoid null exception reference

C# - Making a Process.Start wait until the process has start-up

Do you mean wait until it's done? Then use Process.WaitForExit:

var process = new Process {
    StartInfo = new ProcessStartInfo {
        FileName = "popup.exe"
    }
};
process.Start();
process.WaitForExit();

Alternatively, if it's an application with a UI that you are waiting to enter into a message loop, you can say:

process.Start();
process.WaitForInputIdle();

Lastly, if neither of these apply, just Thread.Sleep for some reasonable amount of time:

process.Start();
Thread.Sleep(1000); // sleep for one second

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

jQuery scroll to element

This is my approach abstracting the ID's and href's, using a generic class selector

_x000D_
_x000D_
$(function() {_x000D_
  // Generic selector to be used anywhere_x000D_
  $(".js-scroll-to").click(function(e) {_x000D_
_x000D_
    // Get the href dynamically_x000D_
    var destination = $(this).attr('href');_x000D_
_x000D_
    // Prevent href=“#” link from changing the URL hash (optional)_x000D_
    e.preventDefault();_x000D_
_x000D_
    // Animate scroll to destination_x000D_
    $('html, body').animate({_x000D_
      scrollTop: $(destination).offset().top_x000D_
    }, 500);_x000D_
  });_x000D_
});
_x000D_
<!-- example of a fixed nav menu -->_x000D_
<ul class="nav">_x000D_
  <li>_x000D_
    <a href="#section-1" class="nav-item js-scroll-to">Item 1</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#section-2" class="nav-item js-scroll-to">Item 2</a>_x000D_
  </li>_x000D_
  <li>_x000D_
    <a href="#section-3" class="nav-item js-scroll-to">Item 3</a>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Create directory if it does not exist

The following code snippet helps you to create a complete path.

Function GenerateFolder($path) {
    $global:foldPath = $null
    foreach($foldername in $path.split("\")) {
        $global:foldPath += ($foldername+"\")
        if (!(Test-Path $global:foldPath)){
            New-Item -ItemType Directory -Path $global:foldPath
            # Write-Host "$global:foldPath Folder Created Successfully"
        }
    }
}

The above function split the path you passed to the function and will check each folder whether it exists or not. If it does not exist it will create the respective folder until the target/final folder created.

To call the function, use below statement:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"

How to close existing connections to a DB

This should disconnect everyone else, and leave you as the only user:

alter database YourDb set single_user with rollback immediate

Note: Don't forget

alter database YourDb set MULTI_USER

after you're done!

Visual Studio 2017: Display method references

In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:

Tools ? Options ? Text Editor ? All Languages ? CodeLens

This is not available in the Community Edition