Programs & Examples On #Development machine

Anything related to computers specifically used and/or configured for software development.

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

How to concatenate strings in a Windows batch file?

What about:

@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof

:concat
set myvar=%myvar% %1;
goto :eof

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

You are correct, @RequestBody annotated parameter is expected to hold the entire body of the request and bind to one object, so you essentially will have to go with your options.

If you absolutely want your approach, there is a custom implementation that you can do though:

Say this is your json:

{
    "str1": "test one",
    "str2": "two test"
}

and you want to bind it to the two params here:

@RequestMapping(value = "/Test", method = RequestMethod.POST)
public boolean getTest(String str1, String str2)

First define a custom annotation, say @JsonArg, with the JSON path like path to the information that you want:

public boolean getTest(@JsonArg("/str1") String str1, @JsonArg("/str2") String str2)

Now write a Custom HandlerMethodArgumentResolver which uses the JsonPath defined above to resolve the actual argument:

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.jayway.jsonpath.JsonPath;

public class JsonPathArgumentResolver implements HandlerMethodArgumentResolver{

    private static final String JSONBODYATTRIBUTE = "JSON_REQUEST_BODY";
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(JsonArg.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String body = getRequestBody(webRequest);
        String val = JsonPath.read(body, parameter.getMethodAnnotation(JsonArg.class).value());
        return val;
    }

    private String getRequestBody(NativeWebRequest webRequest){
        HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);
        String jsonBody = (String) servletRequest.getAttribute(JSONBODYATTRIBUTE);
        if (jsonBody==null){
            try {
                String body = IOUtils.toString(servletRequest.getInputStream());
                servletRequest.setAttribute(JSONBODYATTRIBUTE, body);
                return body;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return "";

    }
}

Now just register this with Spring MVC. A bit involved, but this should work cleanly.

How to search by key=>value in a multidimensional array in PHP

If you want to search for array of keys this is good

function searchKeysInMultiDimensionalArray($array, $keys)
{
    $results = array();

    if (is_array($array)) {
        $resultArray = array_intersect_key($array, array_flip($keys));
        if (!empty($resultArray)) {
            $results[] = $resultArray;
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, searchKeysInMultiDimensionalArray($subarray, $keys));
        }
    }

    return $results;
}

Keys will not overwrite because each set of key => values will be in separate array in resulting array.
If you don't want duplicate keys then use this one

function searchKeysInMultiDimensionalArray($array, $keys)
{
    $results = array();

    if (is_array($array)) {
        $resultArray = array_intersect_key($array, array_flip($keys));
        if (!empty($resultArray)) {
            foreach($resultArray as $key => $single) {

                $results[$key] = $single;
            }
        }

        foreach ($array as $subarray) {
            $results = array_merge($results, searchKeysInMultiDimensionalArray($subarray, $keys));
        }
    }

    return $results;
}

How do I kill the process currently using a port on localhost in Windows?

We can avoid this by simple restarting IIS, using the below command:

IISRESET

Copying PostgreSQL database to another server


Dump your database : pg_dump database_name_name > backup.sql


Import your database back: psql db_name < backup.sql

Convert double/float to string

The only exact solution is to perform arbitrary-precision decimal arithmetic for the base conversion, since the exact value can be very long - for 80-bit long double, up to about 10000 decimal places. Fortunately it's "only" up to about 700 places or so for IEEE double.

Rather than working with individual decimal digits, it's helpful to instead work base-1-billion (the highest power of 10 that fits in a 32-bit integer) and then convert these "base-1-billion digits" to 9 decimal digits each at the end of your computation.

I have a very dense (rather hard to read) but efficient implementation here, under LGPL MIT license:

http://git.musl-libc.org/cgit/musl/blob/src/stdio/vfprintf.c?h=v1.1.6

If you strip out all the hex float support, infinity/nan support, %g/%f/%e variation support, rounding (which will never be needed if you only want exact answers), and other things you might not need, the remaining code is rather simple.

What are these ^M's that keep showing up in my files in emacs?

One of the most straightforward ways of gettings rid of ^Ms with just an emacs command one-liner:

    C-x h C-u M-| dos2unix    

Analysis:

    C-x h: select current buffer
    C-u: apply following command as a filter, redirecting its output to replace current buffer
    M-| dos2unix: performs `dos2unix` [current buffer]

*nix platforms have the dos2unix utility out-of-the-box, including Mac (with brew). Under Windows, it is widely available too (MSYS2, Cygwin, user-contributed, among others).

Animation CSS3: display + opacity

I had the same problem. I tried using animations instead of transitions - as suggested by @MichaelMullany and @Chris - but it only worked for webkit browsers even if I copy-pasted with "-moz" and "-o" prefixes.

I was able to get around the problem by using visibility instead of display. This works for me because my child element is position: absolute, so document flow isn't being affected. It might work for others too.

This is what the original code would look like using my solution:

.child {
    position: absolute;
    opacity: 0;
    visibility: hidden;

    -webkit-transition: opacity 0.5s ease-in-out;
    -moz-transition: opacity 0.5s ease-in-out;
    transition: opacity 0.5s ease-in-out;
}

.parent:hover .child {
    position: relative;
    opacity: 0.9;
    visibility: visible;
}

Objective-C : BOOL vs bool

I go against convention here. I don't like typedef's to base types. I think it's a useless indirection that removes value.

  1. When I see the base type in your source I will instantly understand it. If it's a typedef I have to look it up to see what I'm really dealing with.
  2. When porting to another compiler or adding another library their set of typedefs may conflict and cause issues that are difficult to debug. I just got done dealing with this in fact. In one library boolean was typedef'ed to int, and in mingw/gcc it's typedef'ed to a char.

Error: Local workspace file ('angular.json') could not be found

Well, I faced the same issue as soon as I updated my angular cli version.

Earlier I was using 1.7.4 and just now I upgraded it to angular cli 6.0.8.

To update Angular Cli global:

npm uninstall -g angular-cli
npm cache clean 
npm install -g @angular/cli@latest

To update Angular Cli dev:

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install

To fix audit issues after npm install:

npm audit fix

To fix the issue related to "angular.json":

ng update @angular/cli --migrate-only --from=1.7.4

What is the correct way to free memory in C#

1.If I have something like Foo o = new Foo(); inside the method, does that mean that each time the timer ticks, I'm creating a new object and a new reference to that object?

Yes.

2.If I have string foo = null and then I just put something temporal in foo, is it the same as above?

If you are asking if the behavior is the same then yes.

3.Does the garbage collector ever delete the object and the reference or objects are continually created and stay in memory?

The memory used by those objects is most certainly collected after the references are deemed to be unused.

4.If I just declare Foo o; and not point it to any instance, isn't that disposed when the method ends?

No, since no object was created then there is no object to collect (dispose is not the right word).

5.If I want to ensure that everything is deleted, what is the best way of doing it

If the object's class implements IDisposable then you certainly want to greedily call Dispose as soon as possible. The using keyword makes this easier because it calls Dispose automatically in an exception-safe way.

Other than that there really is nothing else you need to do except to stop using the object. If the reference is a local variable then when it goes out of scope it will be eligible for collection.1 If it is a class level variable then you may need to assign null to it to make it eligible before the containing class is eligible.


1This is technically incorrect (or at least a little misleading). An object can be eligible for collection long before it goes out of scope. The CLR is optimized to collect memory when it detects that a reference is no longer used. In extreme cases the CLR can collect an object even while one of its methods is still executing!

Update:

Here is an example that demonstrates that the GC will collect objects even though they may still be in-scope. You have to compile a Release build and run this outside of the debugger.

static void Main(string[] args)
{
    Console.WriteLine("Before allocation");
    var bo = new BigObject();
    Console.WriteLine("After allocation");
    bo.SomeMethod();
    Console.ReadLine();
    // The object is technically in-scope here which means it must still be rooted.
}

private class BigObject
{
    private byte[] LotsOfMemory = new byte[Int32.MaxValue / 4];

    public BigObject()
    {
        Console.WriteLine("BigObject()");
    }

    ~BigObject()
    {
        Console.WriteLine("~BigObject()");
    }

    public void SomeMethod()
    {
        Console.WriteLine("Begin SomeMethod");
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("End SomeMethod");
    }
}

On my machine the finalizer is run while SomeMethod is still executing!

How to use z-index in svg elements?

We have already 2019 and z-index is still not supported in SVG.

You can see on the site SVG2 support in Mozilla that the state for z-indexNot implemented.

You can also see on the site Bug 360148 "Support the 'z-index' property on SVG elements" (Reported: 12 years ago).

But you have 3 possibilities in SVG to set it:

  1. With element.appendChild(aChild);
  2. With parentNode.insertBefore(newNode, referenceNode);
  3. With targetElement.insertAdjacentElement(positionStr, newElement); (No support in IE for SVG)

Interactive demo example

With all this 3 functions.

_x000D_
_x000D_
var state = 0,_x000D_
    index = 100;_x000D_
_x000D_
document.onclick = function(e)_x000D_
{_x000D_
    if(e.target.getAttribute('class') == 'clickable')_x000D_
    {_x000D_
        var parent = e.target.parentNode;_x000D_
_x000D_
        if(state == 0)_x000D_
            parent.appendChild(e.target);_x000D_
        else if(state == 1)_x000D_
            parent.insertBefore(e.target, null); //null - adds it on the end_x000D_
        else if(state == 2)_x000D_
            parent.insertAdjacentElement('beforeend', e.target);_x000D_
        else_x000D_
            e.target.style.zIndex = index++;_x000D_
    }_x000D_
};_x000D_
_x000D_
if(!document.querySelector('svg').insertAdjacentElement)_x000D_
{_x000D_
    var label = document.querySelectorAll('label')[2];_x000D_
    label.setAttribute('disabled','disabled');_x000D_
    label.style.color = '#aaa';_x000D_
    label.style.background = '#eee';_x000D_
    label.style.cursor = 'not-allowed';_x000D_
    label.title = 'This function is not supported in SVG for your browser.';_x000D_
}
_x000D_
label{background:#cef;padding:5px;cursor:pointer}_x000D_
.clickable{cursor:pointer}
_x000D_
With: _x000D_
<label><input type="radio" name="check" onclick="state=0" checked/>appendChild()</label>_x000D_
<label><input type="radio" name="check" onclick="state=1"/>insertBefore()</label><br><br>_x000D_
<label><input type="radio" name="check" onclick="state=2"/>insertAdjacentElement()</label>_x000D_
<label><input type="radio" name="check" onclick="state=3"/>Try it with z-index</label>_x000D_
<br>_x000D_
<svg width="150" height="150" viewBox="0 0 150 150">_x000D_
    <g stroke="none">_x000D_
        <rect id="i1" class="clickable" x="10" y="10" width="50" height="50" fill="#80f"/>_x000D_
        <rect id="i2" class="clickable" x="40" y="40" width="50" height="50" fill="#8f0"/>_x000D_
        <rect id="i3" class="clickable" x="70" y="70" width="50" height="50" fill="#08f"/>_x000D_
    </g>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

This application has no explicit mapping for /error

Try adding the dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Android add placeholder text to EditText

If you mean the location where you will add it in the layout. You can define a container like a FrameLayout and add this EditText to it when it is created.

<LinearLayout xmlns=".."/>
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

FrameLayout layout = (FrameLayout) findViewById(R.id.container);
layout.addView(name);

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

Where do I find the line number in the Xcode editor?

If you don't want line numbers shown all the time another way to find the line number of a piece of code is to just click in the left-most margin and create a breakpoint (a small blue arrow appears) then go to the breakpoint navigator (?7) where it will list the breakpoint with its line number. You can delete the breakpoint by right clicking on it.

Jackson: how to prevent field serialization

Jackson has a class named SimpleBeanPropertyFilter that helps to filter fields during serialization and deserialization; not globally. I think that's what you wanted.

@JsonFilter("custom_serializer")
class User {
    private String password;

    //setter, getter..
}

Then in your code:

String[] fieldsToSkip = new String[] { "password" };

ObjectMapper mapper = new ObjectMapper();

final SimpleFilterProvider filter = new SimpleFilterProvider();
filter.addFilter("custom_serializer",
            SimpleBeanPropertyFilter.serializeAllExcept(fieldsToSkip));

mapper.setFilters(filter);

String jsonStr = mapper.writeValueAsString(currentUser);

This will prevent password field to get serialized. Also you will be able to deserialize password fields as it is. Just make sure no filters are applied on the ObjectMapper object.

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(yourJsonStr, User.class);    // user object does have non-null password field

Why are #ifndef and #define used in C++ header files?

This prevent from the multiple inclusion of same header file multiple time.

#ifndef __COMMON_H__
#define __COMMON_H__
//header file content
#endif

Suppose you have included this header file in multiple files. So first time __COMMON_H__ is not defined, it will get defined and header file included.

Next time __COMMON_H__ is defined, so it will not include again.

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Lazy Set

VARIABLE = value

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

VARIABLE := value

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

VARIABLE ?= value

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

ifeq ($(origin FOO), undefined)
  FOO = bar
endif

See the documentation for more details.

Append

VARIABLE += value

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

Way to go from recursion to iteration

Usually, I replace a recursive algorithm by an iterative algorithm by pushing the parameters that would normally be passed to the recursive function onto a stack. In fact, you are replacing the program stack by one of your own.

var stack = [];
stack.push(firstObject);

// while not empty
while (stack.length) {

    // Pop off end of stack.
    obj = stack.pop();

    // Do stuff.
    // Push other objects on the stack as needed.
    ...

}

Note: if you have more than one recursive call inside and you want to preserve the order of the calls, you have to add them in the reverse order to the stack:

foo(first);
foo(second);

has to be replaced by

stack.push(second);
stack.push(first);

Edit: The article Stacks and Recursion Elimination (or Article Backup link) goes into more details on this subject.

Authenticating in PHP using LDAP through Active Directory

I like the Zend_Ldap Class, you can use only this class in your project, without the Zend Framework.

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

Change Row background color based on cell value DataTable

I used createdRow Function and solved my problem

    $('#result1').DataTable( {
        data: data['firstQuery'],
        columns: [
                        { title: 'Shipping Agent Code' },
                        { title: 'City' },
                        { title: 'Delivery Zone' },
                        { title: 'Total Slots Open ' },
                        { title: 'Slots Utilized' },
                        { title: 'Utilization %' },

                    ],
                    "columnDefs": [
                        {"className": "dt-center", "targets": "_all"}
                      ],
                      "createdRow": function( row, data, dataIndex){
                            if( data[5] >= 90  ){
                                $(row).css('background-color', '#F39B9B');
                            }
                            else if( data[5] <= 70  ){
                                $(row).css('background-color', '#A497E5');
                            }
                            else{
                                $(row).css('background-color', '#9EF395');
                            }

                        }
                } );

Simple way to count character occurrences in a string

I believe the "one liner" that you expected to get is this:

"abdsd3$asda$asasdd$sadas".replaceAll( "[^$]*($)?", "$1" ).length();

Remember that the requirements are:

(instead of traversing manually all the string, or loop for indexOf)

and let me add: that at the heart of this question it sounds like "any loop" is not wanted and there is no requirement for speed. I believe the subtext of this question is coolness factor.

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with

$my_url = urlencode("my url");

and then calling

file_get_contents($my_url);

and see if you have better luck.

Multiple modals overlay

The solution to this for me was to NOT use the "fade" class on my modal divs.

XPath using starts-with function

Use:

//REVENUE_YEAR[starts-with(.,'2552')]/../REGION/text() 

How to get first character of string?

In JavaScript you can do this:

_x000D_
_x000D_
const x = 'some string';_x000D_
console.log(x.substring(0, 1));
_x000D_
_x000D_
_x000D_

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

I would do something like this:

;WITH x 
 AS (SELECT *, 
            Row_number() 
              OVER( 
                partition BY employeeid 
                ORDER BY datestart) rn 
     FROM   employeehistory) 
SELECT * 
FROM   x x1 
   LEFT OUTER JOIN x x2 
                ON x1.rn = x2.rn + 1 

Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

execute shell command from android

Process p;
StringBuffer output = new StringBuffer();
try {
    p = Runtime.getRuntime().exec(params[0]);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(p.getInputStream()));
    String line = "";
    while ((line = reader.readLine()) != null) {
        output.append(line + "\n");
        p.waitFor();
    }
} 
catch (IOException e) {
    e.printStackTrace();
} catch (InterruptedException e) {
    e.printStackTrace();
}
String response = output.toString();
return response;

Convert base class to derived class

No, there is no built in conversion for this. You'll need to create a constructor, like you mentioned, or some other conversion method.

Also, since BaseClass is not a DerivedClass, myDerivedObject will be null, andd the last line above will throw a null ref exception.

How do I generate random number for each row in a TSQL Select?

Random number generation between 1000 and 9999 inclusive:

FLOOR(RAND(CHECKSUM(NEWID()))*(9999-1000+1)+1000)

"+1" - to include upper bound values(9999 for previous example)

SQL Server table creation date query

SELECT create_date
FROM sys.tables
WHERE name='YourTableName'

How do I add a newline to a windows-forms TextBox?

Try using Environment.NewLine:

Gets the newline string defined for this environment.

Something like this ought to work:

textBox.AppendText("your new text" & Environment.NewLine)

Java word count program

public class wordCOunt
{
public static void main(String ar[])
{
System.out.println("Simple Java Word Count Program");

    String str1 = "Today is Holdiay Day";

    int wordCount = 1;

    for (int i = 0; i < str1.length(); i++) 
    {
        if (str1.charAt(i) == ' '&& str1.charAt(i+1)!=' ') 
        {
            wordCount++;
        } 
    }

    System.out.println("Word count is = " +(str1.length()- wordCount));
}

}

Checkboxes in web pages – how to make them bigger?

Actually there is a way to make them bigger, checkboxes just like anything else (even an iframe like a facebook button).

Wrap them in a "zoomed" element:

_x000D_
_x000D_
.double {_x000D_
  zoom: 2;_x000D_
  transform: scale(2);_x000D_
  -ms-transform: scale(2);_x000D_
  -webkit-transform: scale(2);_x000D_
  -o-transform: scale(2);_x000D_
  -moz-transform: scale(2);_x000D_
  transform-origin: 0 0;_x000D_
  -ms-transform-origin: 0 0;_x000D_
  -webkit-transform-origin: 0 0;_x000D_
  -o-transform-origin: 0 0;_x000D_
  -moz-transform-origin: 0 0;_x000D_
}
_x000D_
<div class="double">_x000D_
  <input type="checkbox" name="hello" value="1">_x000D_
</div>
_x000D_
_x000D_
_x000D_

It might look a little bit "rescaled" but it works.

Of course you can make that div float:left and put your label besides it, float:left too.

Can I make a phone call from HTML on Android?

Yes you can; it works on Android too:

tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:

* tel:2125551212
* tel: (212) 555 1212

The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:

<a href="tel:2125551212">2125551212</a>

on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.

Have a look to RFC3966

Pip freeze vs. pip list

To answer the second part of this question, the two packages shown in pip list but not pip freeze are setuptools (which is easy_install) and pip itself.

It looks like pip freeze just doesn't list packages that pip itself depends on. You may use the --all flag to show also those packages.

From the documentation:

--all

Do not skip these packages in the output: pip, setuptools, distribute, wheel

C: socket connection timeout

Here is a modern connect_with_timeout implementation, using poll, with proper error and signal handling:

#include <sys/socket.h>
#include <fcntl.h>
#include <poll.h>
#include <time.h>

int connect_with_timeout(int sockfd, const struct sockaddr *addr, socklen_t addrlen, unsigned int timeout_ms) {
    int rc = 0;
    // Set O_NONBLOCK
    int sockfd_flags_before;
    if((sockfd_flags_before=fcntl(sockfd,F_GETFL,0)<0)) return -1;
    if(fcntl(sockfd,F_SETFL,sockfd_flags_before | O_NONBLOCK)<0) return -1;
    // Start connecting (asynchronously)
    do {
        if (connect(sockfd, addr, addrlen)<0) {
            // Did connect return an error? If so, we'll fail.
            if ((errno != EWOULDBLOCK) && (errno != EINPROGRESS)) {
                rc = -1;
            }
            // Otherwise, we'll wait for it to complete.
            else {
                // Set a deadline timestamp 'timeout' ms from now (needed b/c poll can be interrupted)
                struct timespec now;
                if(clock_gettime(CLOCK_MONOTONIC, &now)<0) { rc=-1; break; }
                struct timespec deadline = { .tv_sec = now.tv_sec,
                                             .tv_nsec = now.tv_nsec + timeout_ms*1000000l};
                // Wait for the connection to complete.
                do {
                    // Calculate how long until the deadline
                    if(clock_gettime(CLOCK_MONOTONIC, &now)<0) { rc=-1; break; }
                    int ms_until_deadline = (int)(  (deadline.tv_sec  - now.tv_sec)*1000l
                                                  + (deadline.tv_nsec - now.tv_nsec)/1000000l);
                    if(ms_until_deadline<0) { rc=0; break; }
                    // Wait for connect to complete (or for the timeout deadline)
                    struct pollfd pfds[] = { { .fd = sockfd, .events = POLLOUT } };
                    rc = poll(pfds, 1, ms_until_deadline);
                    // If poll 'succeeded', make sure it *really* succeeded
                    if(rc>0) {
                        int error = 0; socklen_t len = sizeof(error);
                        int retval = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len);
                        if(retval==0) errno = error;
                        if(error!=0) rc=-1;
                    }
                }
                // If poll was interrupted, try again.
                while(rc==-1 && errno==EINTR);
                // Did poll timeout? If so, fail.
                if(rc==0) {
                    errno = ETIMEDOUT;
                    rc=-1;
                }
            }
        }
    } while(0);
    // Restore original O_NONBLOCK state
    if(fcntl(sockfd,F_SETFL,sockfd_flags_before)<0) return -1;
    // Success
    return rc;
}

How to use "Share image using" sharing Intent to share images in android?

I just had the same problem.
Here is an answer that doesn't use any explicit file writing in your main code (letting the api taking care of it for you).

Drawable mDrawable = myImageView1.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();
String path = MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "Image I want to share", null);
Uri uri = Uri.parse(path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.setType("image/*");
startActivity(Intent.createChooser(shareIntent, "Share Image"));

This is the path... you just need to add your image IDs in a Drawable object. In my case (code above), the drawable was extracted from an ImageView.

What does the "undefined reference to varName" in C mean?

You need to compile and then link the object files like this:

gcc -c a.c  
gcc -c b.c  
gcc a.o b.o -o prog  

How do you check if a selector matches something in jQuery?

no, jquery always returns a jquery object regardless if a selector was matched or not. You need to use .length

if ( $('#someDiv').length ){

}

android.content.Context.getPackageName()' on a null object reference

You solve the issue with a try/ catch. This crash happens when user close the app before the start intent.

try
{
    Intent mIntent = new Intent(getActivity(),MusicHome.class);
    mIntent.putExtra("SigninFragment.user_details", bundle);
    startActivity(mIntent);
}
catch (Exception e) {
    e.printStackTrace();
}

How to create a batch file to run cmd as administrator

Make a text using notepad or any text editor of you choice. Open notepad, write this short command "cmd.exe" without the quote aand save it as cmd.bat.

Click cmd.bat and choose "run as administrator".

Printing *s as triangles in Java?

This will print stars in triangle:

`   
public class printstar{
public static void main (String args[]){
int m = 0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4-i;j++){
System.out.print("");}

for (int n=0;n<=i+m;n++){
if (n%2==0){
System.out.print("*");}
else {System.out.print(" ");}
}
m = m+1;
System.out.println("");
}
}
}'

Reading and understanding this should help you with designing the logic next time..

Network usage top/htop on Linux

Also iftop:

display bandwidth usage on an interface

iftop does for network usage what top(1) does for CPU usage. It listens to network traffic on a named interface and displays a table of current bandwidth usage by pairs of hosts. Handy for answering the question "why is our ADSL link so slow?"...

How to stop mongo DB in one command

From the given commands I think you're on Linux.

Start MongoDB:

$ sudo service mongod start
mongod start/running, process XXXXX 

Check the Status:

$ sudo service mongod status
mongod start/running, process XXXXX 

Stop MongoDB:

$ sudo service mongod stop
mongod stop/waiting 

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

I'm pretty certain that you can't change the datetime format in mysql. The phpmyadmin setting is probably applying a custom format as it reads the datetime (using DATE_FORMAT or something from php). It shouldn't matter what format the database uses, format in the application to display it as you wish.

Date formatting is a pretty common task. I typically like to abstract it out into internationalization code or, if you don't need to deal with i18n, into a common date utility library. It helps keep things consistent and makes it easier to change later (or add i18n support).

Remove special symbols and extra spaces and replace with underscore using the replace method

var str = "hello world & hello universe"

In order to replace both Spaces and Symbols in one shot, we can use the below regex code.

str.replaceAll("\\W+","")

Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches

Try it!

Streaming video from Android camera to server

This is hardly a full answer, but webRTC may be what you're looking for. Here's some quick examples of webRTC in action: http://www.webrtc.org/reference-apps

If you want Android specific code, it exists! http://www.webrtc.org/native-code/android

urllib2 and json

Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself.

import json
import urllib2
data = json.dumps([1, 2, 3])
clen = len(data)
req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
response = f.read()
f.close()

Took me for ever to figure this out, so I hope it helps someone else.

How can I center an image in Bootstrap?

Image by default is displayed as inline-block, you need to display it as block in order to center it with .mx-auto. This can be done with built-in .d-block:

<div class="container">
    <div class="row">
        <div class="col-4">
            <img class="mx-auto d-block" src="...">  
        </div>
    </div>
</div>

Or leave it as inline-block and wrapped it in a div with .text-center:

<div class="container">
    <div class="row">
        <div class="col-4">
          <div class="text-center">
            <img src="..."> 
          </div>     
        </div>
    </div>
</div>

I made a fiddle showing both ways. They are documented here as well.

How to get the entire document HTML as a string?

You can also do:

document.getElementsByTagName('html')[0].innerHTML

You will not get the Doctype or html tag, but everything else...

Disable and enable buttons in C#

button2.Enabled == true ;

thats the problem - it should be:

button2.Enabled = true ;

Git On Custom SSH Port

git clone ssh://[email protected]:[port]/gitolite-admin

Note that the port number should be there without the square brackets: []

FTP/SFTP access to an Amazon S3 Bucket

As other posters have pointed out, there are some limitations with the AWS Transfer for SFTP service. You need to closely align requirements. For example, there are no quotas, whitelists/blacklists, file type limits, and non key based access requires external services. There is also a certain overhead relating to user management and IAM, which can get to be a pain at scale.

We have been running an SFTP S3 Proxy Gateway for about 5 years now for our customers. The core solution is wrapped in a collection of Docker services and deployed in whatever context is needed, even on-premise or local development servers. The use case for us is a little different as our solution is focused data processing and pipelines vs a file share. In a Salesforce example, a customer will use SFTP as the transport method sending email, purchase...data to an SFTP/S3 enpoint. This is mapped an object key on S3. Upon arrival, the data is picked up, processed, routed and loaded to a warehouse. We also have fairly significant auditing requirements for each transfer, something the Cloudwatch logs for AWS do not directly provide.

As other have mentioned, rolling your own is an option too. Using AWS Lightsail you can setup a cluster, say 4, of $10 2GB instances using either Route 53 or an ELB.

In general, it is great to see AWS offer this service and I expect it to mature over time. However, depending on your use case, alternative solutions may be a better fit.

CSS Cell Margin

margin does not work unfortunately on individual cells, however you could add extra columns between the two cells you want to put a space between... another option is to use a border with the same colour as the background...

What is the difference between Builder Design pattern and Factory Design pattern?

Builder and Abstract Factory

The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That's why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory's methods to create its own objects. In the Builder's case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.

Common interface for products

In practice the products created by the concrete builders have a structure significantly different, so if there is not a reason to derive different products a common parent class. This also distinguishes the Builder pattern from the Abstract Factory pattern which creates objects derived from a common type.

From: http://www.oodesign.com/builder-pattern.html

Center content in responsive bootstrap navbar

Update 2020...

Bootstrap 5 Beta

The Navbar is still flexbox based in Bootstrap 5 and centering content works the same as it did with Bootstrap 4. Examples

Bootstrap 4

Centering Navbar content is easier is Bootstrap 4, and you can see many centering scenarios explained here: https://stackoverflow.com/a/20362024/171456

Bootstrap 3

Another scenario that doesn't seem to have been answered yet is centering both the brand and navbar links. Here's a solution..

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

Also see: Bootstrap NavBar with left, center or right aligned items

How do I navigate to a parent route from a child route?

without much ado:

this.router.navigate(['..'], {relativeTo: this.activeRoute, skipLocationChange: true});

parameter '..' makes navigation one level up, i.e. parent :)

How to strip comma in Python string

You want to replace it, not strip it:

s = s.replace(',', '')

Preview an image before it is uploaded

For Multiple image upload (Modification to the @IvanBaev's Solution)

function readURL(input) {
    if (input.files && input.files[0]) {
        var i;
        for (i = 0; i < input.files.length; ++i) {
          var reader = new FileReader();
          reader.onload = function (e) {
              $('#form1').append('<img src="'+e.target.result+'">');
          }
          reader.readAsDataURL(input.files[i]);
        }
    }
}

http://jsfiddle.net/LvsYc/12330/

Hope this helps someone.

Remove style attribute from HTML tags

Something like this should work (untested code warning):

<?php

$html = '<p style="asd">qwe</p><br /><p class="qwe">qweqweqwe</p>';

$domd = new DOMDocument();
libxml_use_internal_errors(true);
$domd->loadHTML($html);
libxml_use_internal_errors(false);

$domx = new DOMXPath($domd);
$items = $domx->query("//p[@style]");

foreach($items as $item) {
  $item->removeAttribute("style");
}

echo $domd->saveHTML();

Remove Datepicker Function dynamically

Well I had the same issue and tried "destroy" but that not worked for me. Then I found following work around My HTML was:

<input placeholder="Select Date" id="MyControlId" class="form-control datepicker" type="text" />

Jquery That work for me:

$('#MyControlId').data('datepicker').remove();

Scroll Element into View with Selenium

This is a repeated solution with JavaScript, but with an added waiting for element.

Otherwise ElementNotVisibleException may appear if some action on the element is being done.

this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));

Perl - If string contains text?

For case-insensitive string search, use index (or rindex) in combination with fc. This example expands on the answer by Eugene Yarmash:

use feature qw( fc ); 
my $str = "Abc"; 
my $substr = "aB"; 

print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found

$str = "Abc";
$substr = "bA";

print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing

Both index and rindex return -1 if the substring is not found.
And fc returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc or lc. Remember to enable this function, for example with use feature qw( fc );.

Java check to see if a variable has been initialized

Instance variables or fields, along with static variables, are assigned default values based on the variable type:

  • int: 0
  • char: \u0000 or 0
  • double: 0.0
  • boolean: false
  • reference: null

Just want to clarify that local variables (ie. declared in block, eg. method, for loop, while loop, try-catch, etc.) are not initialized to default values and must be explicitly initialized.

Can I change the headers of the HTTP request sent by the browser?

I was looking to do exactly the same thing (RESTful web service), and I stumbled upon this firefox addon, which lets you modify the accept headers (actually, any request headers) for requests. It works perfectly.

https://addons.mozilla.org/en-US/firefox/addon/967/

Format Instant to String

Or if you still want to use formatter created from pattern you can just use LocalDateTime instead of Instant:

LocalDateTime datetime = LocalDateTime.now();
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(datetime)

How to search all loaded scripts in Chrome Developer Tools?

In Widows it is working for me. Control Shift F and then it opens a search window at the bottom. Make sure you expand the bottom area to see the new search window.

enter image description here

How to print table using Javascript?

My fellows,

In January 2019 I used a code made before:

 <script type="text/javascript">   
    function imprimir() {
        var divToPrint=document.getElementById("ConsutaBPM");
        newWin= window.open("");
        newWin.document.write(divToPrint.outerHTML);
        newWin.print();
        newWin.close();
    }
</script>

To undestand: ConsutaBPM is a DIV which contains inside phrases and tables. I wanted to print ALL, titles, table, and others. The problem was when TRIED to print the TABLE...

The table mas be defined with BORDER and CELLPADDING:

<table border='1' cellpadding='1' id='Tablbpm1' >

It worked fine!!!

How do I call a SQL Server stored procedure from PowerShell?

Here is a function that I use (slightly redacted). It allows input and output parameters. I only have uniqueidentifier and varchar types implemented, but any other types are easy to add. If you use parameterized stored procedures (or just parameterized sql...this code is easily adapted to that), this will make your life a lot easier.

To call the function, you need a connection to the SQL server (say $conn),

$res=exec-storedprocedure -storedProcName 'stp_myProc' -parameters @{Param1="Hello";Param2=50} -outparams @{ID="uniqueidentifier"} $conn

retrieve proc output from returned object

$res.data #dataset containing the datatables returned by selects

$res.outputparams.ID #output parameter ID (uniqueidentifier)

The function:

function exec-storedprocedure($storedProcName,  
        [hashtable] $parameters=@{},
        [hashtable] $outparams=@{},
        $conn,[switch]$help){ 

        function put-outputparameters($cmd, $outparams){
            foreach($outp in $outparams.Keys){
                $cmd.Parameters.Add("@$outp", (get-paramtype $outparams[$outp])).Direction=[System.Data.ParameterDirection]::Output
            }
        }
        function get-outputparameters($cmd,$outparams){
            foreach($p in $cmd.Parameters){
                if ($p.Direction -eq [System.Data.ParameterDirection]::Output){
                $outparams[$p.ParameterName.Replace("@","")]=$p.Value
                }
            }
        }

        function get-paramtype($typename,[switch]$help){
            switch ($typename){
                'uniqueidentifier' {[System.Data.SqlDbType]::UniqueIdentifier}
                'int' {[System.Data.SqlDbType]::Int}
                'xml' {[System.Data.SqlDbType]::Xml}
                'nvarchar' {[System.Data.SqlDbType]::NVarchar}
                default {[System.Data.SqlDbType]::Varchar}
            }
        }
        if ($help){
            $msg = @"
    Execute a sql statement.  Parameters are allowed.  
    Input parameters should be a dictionary of parameter names and values.
    Output parameters should be a dictionary of parameter names and types.
    Return value will usually be a list of datarows. 

    Usage: exec-query sql [inputparameters] [outputparameters] [conn] [-help]
    "@
            Write-Host $msg
            return
        }
        $close=($conn.State -eq [System.Data.ConnectionState]'Closed')
        if ($close) {
           $conn.Open()
        }

        $cmd=new-object system.Data.SqlClient.SqlCommand($sql,$conn)
        $cmd.CommandType=[System.Data.CommandType]'StoredProcedure'
        $cmd.CommandText=$storedProcName
        foreach($p in $parameters.Keys){
            $cmd.Parameters.AddWithValue("@$p",[string]$parameters[$p]).Direction=
                  [System.Data.ParameterDirection]::Input
        }

        put-outputparameters $cmd $outparams
        $ds=New-Object system.Data.DataSet
        $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
        [Void]$da.fill($ds)
        if ($close) {
           $conn.Close()
        }
        get-outputparameters $cmd $outparams

        return @{data=$ds;outputparams=$outparams}
    }

Get time difference between two dates in seconds

<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();

var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>

Overriding the java equals() method - not working?

In Java, the equals() method that is inherited from Object is:

public boolean equals(Object other);

In other words, the parameter must be of type Object. This is called overriding; your method public boolean equals(Book other) does what is called overloading to the equals() method.

The ArrayList uses overridden equals() methods to compare contents (e.g. for its contains() and equals() methods), not overloaded ones. In most of your code, calling the one that didn't properly override Object's equals was fine, but not compatible with ArrayList.

So, not overriding the method correctly can cause problems.

I override equals the following everytime:

@Override
public boolean equals(Object other){
    if (other == null) return false;
    if (other == this) return true;
    if (!(other instanceof MyClass)) return false;
    MyClass otherMyClass = (MyClass)other;
    ...test other properties here...
}

The use of the @Override annotation can help a ton with silly mistakes.

Use it whenever you think you are overriding a super class' or interface's method. That way, if you do it the wrong way, you will get a compile error.

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

appending array to FormData and send via AJAX

You have several options:

Convert it to a JSON string, then parse it in PHP (recommended)

JS

var json_arr = JSON.stringify(arr);

PHP

$arr = json_decode($_POST['arr']);

Or use @Curios's method

Sending an array via FormData.


Not recommended: Serialize the data with, then deserialize in PHP

JS

// Use <#> or any other delimiter you want
var serial_arr = arr.join("<#>"); 

PHP

$arr = explode("<#>", $_POST['arr']);

How to check if ZooKeeper is running or up from command prompt?

I did some test:

When it's running:

$ /usr/lib/zookeeper/bin/zkServer.sh status
JMX enabled by default
Using config: /usr/lib/zookeeper/bin/../conf/zoo.cfg
Mode: follower

When it's stopped:

$ zkServer status                                                                                                                                
JMX enabled by default
Using config: /usr/local/etc/zookeeper/zoo.cfg
Error contacting service. It is probably not running.

I'm not running on the same machine, but you get the idea.

Checking for directory and file write permissions in .NET

Try working with this C# snippet I just crafted:

using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string directory = @"C:\downloads";

            DirectoryInfo di = new DirectoryInfo(directory);

            DirectorySecurity ds = di.GetAccessControl();

            foreach (AccessRule rule in ds.GetAccessRules(true, true, typeof(NTAccount)))
            {
                Console.WriteLine("Identity = {0}; Access = {1}", 
                              rule.IdentityReference.Value, rule.AccessControlType);
            }
        }
    }
}

And here's a reference you could also look at. My code might give you an idea as to how you could check for permissions before attempting to write to a directory.

Alternate output format for psql

One interesting thing is we can view the tables horizontally, without folding. we can use PAGER environment variable. psql makes use of it. you can set

export PAGER='/usr/bin/less -S'

or just less -S if its already availble in command line, if not with the proper location. -S to view unfolded lines. you can pass in any custom viewer or other options with it.

I've written more in Psql Horizontal Display

Margin on child element moves parent element

To prevent "Div parent" use margin of "div child":
In parent use these css:

  • Float
  • Padding
  • Border
  • Overflow

Convert DateTime to long and also the other way around

Since you're using ToFileTime, you'll want to use FromFileTime to go the other way. But note:

Ordinarily, the FromFileTime method restores a DateTime value that was saved by the ToFileTime method. However, the two values may differ under the following conditions:

If the serialization and deserialization of the DateTime value occur in different time zones. For example, if a DateTime value with a time of 12:30 P.M. in the U.S. Eastern Time zone is serialized, and then deserialized in the U.S. Pacific Time zone, the original value of 12:30 P.M. is adjusted to 9:30 A.M. to reflect the difference between the two time zones.

If the DateTime value that is serialized represents an invalid time in the local time zone. In this case, the ToFileTime method adjusts the restored DateTime value so that it represents a valid time in the local time zone.

If you don't care which long representation of a DateTime is stored, you can use Ticks as others have suggested (Ticks is probably preferable, depending on your requirements, since the value returned by ToFileTime seems to be in the context of the Windows filesystem API).

Getting index value on razor foreach

 @{int i = 0;}
 @foreach(var myItem in Model.Members)
 {
     <span>@i</span>
     @{i++;
      }
 }

// Use @{i++ to increment value}

How do I create a HTTP Client Request with a cookie?

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

You can use javax.xml.bind.DatatypeConverter class

DatatypeConverter.printDateTime & DatatypeConverter.parseDateTime

Does WhatsApp offer an open API?

  1. is the correct answer. WhatsApp is intentionally a closed system without an API for external access.

There were several projects available that reverse engineered the WhatsApp webservice interfaces. However, to my knowledge all of them are now discontinued/defunct due to legal action against them from WhatsApp.

For mobile phone applications there is a limited URL-Scheme-API available on IPhone and Android (Android-intent possible as well).

How to ORDER BY a SUM() in MySQL?

This is how you do it

SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS 
FROM TABLE 
ORDER BY SUM_COUNTS LIMIT 20

The SUM function will add up all rows, so the order by clause is useless, instead you will have to use the group by clause.

How to set UICollectionViewCell Width and Height programmatically

This is my version, find your suitable ratio to get the cell size as per your requirement.

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
return CGSizeMake(CGRectGetWidth(collectionView.frame)/4, CGRectGetHeight(collectionView.frame)/4); 
} 

Escape @ character in razor view engine

use <text></text> or the easier way @:

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

C# Collection was modified; enumeration operation may not execute

The problem is where you are executing:

rankings[kvp.Key] = rankings[kvp.Key] + 4;

You cannot modify the collection you are iterating through in a foreach loop. A foreach loop requires the loop to be immutable during iteration.

Instead, use a standard 'for' loop or create a new loop that is a copy and iterate through that while updating your original.

Java - Check if JTextField is empty or not

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // Submit Button        

    String Fname = jTextField1.getText();
    String Lname = jTextField2.getText();
    String Desig = jTextField3.getText();
    String Nic = jTextField4.getText();
    String Phone = jTextField5.getText();
    String Add = jTextArea1.getText();
    String Dob = jTextField6.getText();
    // String Gender;
    // Image

    if (Fname.hashCode() == 0 || Lname.hashCode() == 0 || Desig.hashCode() == 0 || Nic.hashCode() == 0 || Phone.hashCode() == 0 || Add.hashCode() == 0)
    {
        JOptionPane.showMessageDialog(null, "Some fields are empty!");
    }
    else
    {
        JOptionPane.showMessageDialog(null, "OK");
    }
}

Representing Directory & File Structure in Markdown Syntax

If you wish to generate it dynamically I recommend using Frontend-md. It is simple to use.

How to convert list to string

By using ''.join

list1 = ['1', '2', '3']
str1 = ''.join(list1)

Or if the list is of integers, convert the elements before joining them.

list1 = [1, 2, 3]
str1 = ''.join(str(e) for e in list1)

java.math.BigInteger cannot be cast to java.lang.Long

I'm lacking context, but this is working just fine:

List<BigInteger> nums = new ArrayList<BigInteger>();
Long max = Collections.max(nums).longValue(); // from BigInteger to Long...

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

I think your code should work just remove one thing from here but it'll do redirection from current page within existing window

<asp:Button ID="btn" runat="Server" Text="SUBMIT" 

 OnClick="btnNewEntry_Click"/>    



protected void btnNewEntry_Click(object sender, EventArgs e)
 {
    Response.Redirect("CMS_1.aspx");
 }

And if u wanna do the this via client side scripting Use this way

<asp:Button ID="BTN" runat="server" Text="Submit" OnClientClick="window.open('Default2.aspx')" />

According to me you should prefer the Client Side Scripting because just to open a new window server side will take a post back and that will be useless..

How can I switch views programmatically in a view controller? (Xcode, iPhone)

If you're in a Navigation Controller:

ViewController *viewController = [[ViewController alloc] init];
[self.navigationController pushViewController:viewController animated:YES];

or if you just want to present a new view:

ViewController *viewController = [[ViewController alloc] init];    
[self presentViewController:viewController animated:YES completion:nil];

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

For me,

  1. I ended the process in Windows Task Manager: VsHub.exe.
  2. Restarted Visual Studio.

After that, everything works like a charm again!

no such file to load -- rubygems (LoadError)

gem install bundler

fixed the issue for me.

Get just the filename from a path in a Bash script

$ source_file_filename_no_ext=${source_file%.*}
$ echo ${source_file_filename_no_ext##*/}

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

How to find duplicate records in PostgreSQL

The basic idea will be using a nested query with count aggregation:

select * from yourTable ou
where (select count(*) from yourTable inr
where inr.sid = ou.sid) > 1

You can adjust the where clause in the inner query to narrow the search.


There is another good solution for that mentioned in the comments, (but not everyone reads them):

select Column1, Column2, count(*)
from yourTable
group by Column1, Column2
HAVING count(*) > 1

Or shorter:

SELECT (yourTable.*)::text, count(*)
FROM yourTable
GROUP BY yourTable.*
HAVING count(*) > 1

HTML5 canvas ctx.fillText won't do line breaks?

Maybe coming to this party a bit late, but I found the following tutorial for wrapping text on a canvas perfect.

http://www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/

From that I was able to think get multi lines working (sorry Ramirez, yours didn't work for me!). My complete code to wrap text in a canvas is as follows:

<script type="text/javascript">

     // http: //www.html5canvastutorials.com/tutorials/html5-canvas-wrap-text-tutorial/
     function wrapText(context, text, x, y, maxWidth, lineHeight) {
        var cars = text.split("\n");

        for (var ii = 0; ii < cars.length; ii++) {

            var line = "";
            var words = cars[ii].split(" ");

            for (var n = 0; n < words.length; n++) {
                var testLine = line + words[n] + " ";
                var metrics = context.measureText(testLine);
                var testWidth = metrics.width;

                if (testWidth > maxWidth) {
                    context.fillText(line, x, y);
                    line = words[n] + " ";
                    y += lineHeight;
                }
                else {
                    line = testLine;
                }
            }

            context.fillText(line, x, y);
            y += lineHeight;
        }
     }

     function DrawText() {

         var canvas = document.getElementById("c");
         var context = canvas.getContext("2d");

         context.clearRect(0, 0, 500, 600);

         var maxWidth = 400;
         var lineHeight = 60;
         var x = 20; // (canvas.width - maxWidth) / 2;
         var y = 58;


         var text = document.getElementById("text").value.toUpperCase();                

         context.fillStyle = "rgba(255, 0, 0, 1)";
         context.fillRect(0, 0, 600, 500);

         context.font = "51px 'LeagueGothicRegular'";
         context.fillStyle = "#333";

         wrapText(context, text, x, y, maxWidth, lineHeight);
     }

     $(document).ready(function () {

         $("#text").keyup(function () {
             DrawText();
         });

     });

    </script>

Where c is the ID of my canvas and text is the ID of my textbox.

As you can probably see am using a non-standard font. You can use @font-face as long as you have used the font on some text PRIOR to manipulating the canvas - otherwise the canvas won't pick up the font.

Hope this helps someone.

Compiling problems: cannot find crt1.o

I had the same problem today, I solved it by installing recommended packages: libc6-dev-mipsel-cross libc6-dev-mipsel-cross, libc-dev-mipsel-cross

This worked:

sudo apt-get install libc6-dev-mipsel-cross

In PHP, what is a closure and why does it use the "use" identifier?

Until very recent years, PHP has defined its AST and PHP interpreter has isolated the parser from the evaluation part. During the time when the closure is introduced, PHP's parser is highly coupled with the evaluation.

Therefore when the closure was firstly introduced to PHP, the interpreter has no method to know which which variables will be used in the closure, because it is not parsed yet. So user has to pleased the zend engine by explicit import, doing the homework that zend should do.

This is the so-called simple way in PHP.

Regular expression for matching latitude/longitude coordinates?

PHP

Here is the PHP's version (input values are: $latitude and $longitude):

$latitude_pattern  = '/\A[+-]?(?:90(?:\.0{1,18})?|\d(?(?<=9)|\d?)\.\d{1,18})\z/x';
$longitude_pattern = '/\A[+-]?(?:180(?:\.0{1,18})?|(?:1[0-7]\d|\d{1,2})\.\d{1,18})\z/x';
if (preg_match($latitude_pattern, $latitude) && preg_match($longitude_pattern, $longitude)) {
  // Valid coordinates.
}

How do you import a large MS SQL .sql file?

The file basically contain data for two new tables.

Then you may find it simpler to just DTS (or SSIS, if this is SQL Server 2005+) the data over, if the two servers are on the same network.

If the two servers are not on the same network, you can backup the source database and restore it to a new database on the destination server. Then you can use DTS/SSIS, or even a simple INSERT INTO SELECT, to transfer the two tables to the destination database.

Struct with template variables in C++

Looks like @monkeyking is trying it to make it more obvious code as shown below

template <typename T> 
struct Array { 
  size_t x; 
  T *ary; 
};

typedef Array<int> iArray;
typedef Array<float> fArray;

Google MAP API v3: Center & Zoom on displayed markers

I've also find this fix that zooms to fit all markers

LatLngList: an array of instances of latLng, for example:

// "map" is an instance of GMap3

var LatLngList = [
                     new google.maps.LatLng (52.537,-2.061), 
                     new google.maps.LatLng (52.564,-2.017)
                 ],
    latlngbounds = new google.maps.LatLngBounds();

LatLngList.forEach(function(latLng){
   latlngbounds.extend(latLng);
});

// or with ES6:
// for( var latLng of LatLngList)
//    latlngbounds.extend(latLng);

map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds); 

jQuery - Dynamically Create Button and Attach Event Handler

You were just adding the html string. Not the element you created with a click event listener.

Try This:

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
</head>
<body>
    <table id="addNodeTable">
        <tr>
            <td>
                Row 1
            </td>
        </tr>
        <tr >
            <td>
                Row 2
            </td>
        </tr>
    </table>
</body>
</html>
<script type="text/javascript">
    $(document).ready(function() {
        var test = $('<button>Test</button>').click(function () {
            alert('hi');
        });
        $("#addNodeTable tr:last").append('<tr><td></td></tr>').find("td:last").append(test);

    });
</script>

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

-Wall and -Wextra sets the stage in GCC and the subsequent -Wno-unused-variable may not take effect. For example, if you have:

CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \ -fno-strict-overflow -fno-strict-aliasing \ -Wall -Wextra \ -pthread \ -Wno-unused-label \ -Wno-unused-function \ -Wno-unused-parameter \ -Wno-unused-variable \ $(INC)

then GCC sees the instruction -Wall -Wextra and seems to ignore -Wno-unused-variable

This can instead look like this below and you get the desired effect of not being stopped in your compile on the unused variable:

CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \ -fno-strict-overflow -fno-strict-aliasing \ -pthread \ -Wno-unused-label \ -Wno-unused-function \ $(INC)

There is a good reason it is called a "warning" vs an "error". Failing the compile just because you code is not complete (say you are stubbing the algorithm out) can be defeating.

getting the screen density programmatically in android?

If you want to retrieve the density from a Service it works like this:

WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics metrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(metrics);

Run multiple python scripts concurrently

With Bash:

python script1.py &
python script2.py &

That's the entire script. It will run the two Python scripts at the same time.

Python could do the same thing itself but it would take a lot more typing and is a bad choice for the problem at hand.

I think it's possible though that you are taking the wrong approach to solving your problem, and I'd like to hear what you're getting at.

javascript /jQuery - For Loop

What about something like this?

var arr = [];

$('[id^=event]', response).each(function(){
    arr.push($(this).html());
});

The [attr^=selector] selector matches elements on which the attr attribute starts with the given string, that way you don't care about the numbers after "event".

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

To Install

adb install -r exampleApp.apk

(The -r makes it replace the existing copy, add an -s if installing on an emulator)

Make sure the app is signed the same and is the same debug/release variant

Bonus

I set up an alias in my ~/.bash_profile, to make it a 2char command.

alias bi="gradlew && adb install -r exampleApp.apk"

(Short for Build and Install)

How to make remote REST call inside Node.js? any CURL?

If you have Node.js 4.4+, take a look at reqclient, it allows you to make calls and log the requests in cURL style, so you can easily check and reproduce the calls outside the application.

Returns Promise objects instead of pass simple callbacks, so you can handle the result in a more "fashion" way, chain the result easily, and handle errors in a standard way. Also removes a lot of boilerplate configurations on each request: base URL, time out, content type format, default headers, parameters and query binding in the URL, and basic cache features.

This is an example of how to initialize it, make a call and log the operation with curl style:

var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
    baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});

This will log in the console...

[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json

And when the response is returned ...

[Response   client/orders]<- Status 200 - {"orderId": 1320934}

This is an example of how to handle the response with the promise object:

client.get("reports/clients")
  .then(function(response) {
    // Do something with the result
  }).catch(console.error);  // In case of error ...

Of course, it can be installed with: npm install reqclient.

Rails 4: assets not loading in production

location ~ ^/assets/ {
  expires 1y;
  add_header Cache-Control public;
  add_header ETag "";
}

This fixed the problem for me in production. Put it into the nginx config.

Making an image act like a button

It sounds like you want an image button:

<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />

Alternatively, you can use CSS to make the existing submit button use your image as its background.

In any case, you don't want a separate <img /> element on the page.

Get the last three chars from any string - Java

public String getLastThree(String myString) {
    if(myString.length() > 3)
        return myString.substring(myString.length()-3);
    else
        return myString;
}

Deleting an element from an array in PHP

To avoid doing a search one can play around with array_diff:

$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11

In this case one doesn't have to search/use the key.

Check if date is a valid one

Was able to find the solution. Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

How do I add a linker or compile flag in a CMake file?

Suppose you want to add those flags (better to declare them in a constant):

SET(GCC_COVERAGE_COMPILE_FLAGS "-fprofile-arcs -ftest-coverage")
SET(GCC_COVERAGE_LINK_FLAGS    "-lgcov")

There are several ways to add them:

  1. The easiest one (not clean, but easy and convenient, and works only for compile flags, C & C++ at once):

    add_definitions(${GCC_COVERAGE_COMPILE_FLAGS})
    
  2. Appending to corresponding CMake variables:

    SET(CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}")
    SET(CMAKE_EXE_LINKER_FLAGS  "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}")
    
  3. Using target properties, cf. doc CMake compile flag target property and need to know the target name.

    get_target_property(TEMP ${THE_TARGET} COMPILE_FLAGS)
    if(TEMP STREQUAL "TEMP-NOTFOUND")
      SET(TEMP "") # Set to empty string
    else()
      SET(TEMP "${TEMP} ") # A space to cleanly separate from existing content
    endif()
    # Append our values
    SET(TEMP "${TEMP}${GCC_COVERAGE_COMPILE_FLAGS}" )
    set_target_properties(${THE_TARGET} PROPERTIES COMPILE_FLAGS ${TEMP} )
    

Right now I use method 2.

How can I get date in application run by node.js?

NodeJS (and newer browsers) have a nice shortcut to get the current time in milliseconds.

var timeInMss = Date.now()

Which has a performance boost compared with

var timeInMss = new Date().getTime()

Because you do not need to create a new object.

The openssl extension is required for SSL/TLS protection

according to the composer reference there are two relevant options: disable-tls and secure-http.

nano ~/.composer/config.json (If the file does not exist or is empty, then just create it with the following content)

{
    "config": {
        "disable-tls": true,
        "secure-http": false
    }
}

then it complains much:

You are running Composer with SSL/TLS protection disabled.
Warning: Accessing getcomposer.org over http which is an insecure protocol.

but it performs the composer selfupdate (or whatever).

while one cannot simply "enable SSL in the php.ini" on Linux; PHP needs to be compiled with openSSL configured as shared library - in order to be able to access it from the PHP CLI SAPI.

How to style a div to be a responsive square?

HTML

<div class='square-box'>
    <div class='square-content'>
        <h3>test</h3>
    </div>
</div>

CSS

.square-box{
    position: relative;
    width: 50%;
    overflow: hidden;
    background: #4679BD;
}
.square-box:before{
    content: "";
    display: block;
    padding-top: 100%;
}
.square-content{
    position:  absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    color: white;
    text-align: center;
}

http://jsfiddle.net/38Tnx/1425/

Oracle date difference to get number of years

For Oracle SQL Developer I was able to calculate the difference in years using the below line of SQL. This was to get Years that were within 0 to 10 years difference. You can do a case like shown in some of the other responses to handle your ifs as well. Happy Coding!

TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) > 0 and TRUNC((MONTHS_BETWEEN(<DATE_ONE>, <DATE_TWO>) * 31) / 365) < 10

Is it possible to use pip to install a package from a private GitHub repository?

oxyum's solution is OK for this answer. I just want to point out that you need to be careful if you are installing using sudo as the keys must be stored for root too (for example, /root/.ssh).

Then you can type

sudo pip install git+ssh://[email protected]/echweb/echweb-utils.git

Convert Json string to Json object in Swift 4

I used below code and it's working fine for me. :

let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
    
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
        
     do {
            dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
        
            if let myDictionary = dictonary
              {
                  print(" User name is: \(myDictionary["userName"]!)")
              }
            } catch let error as NSError {
            
            print(error)
         }
}

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

In case someone lands here after making the same mistake I did:

  1. Switched to plugin="mysql_native_password" temporarily. Performed my tasks.
  2. Attempted to switch back to the "auth_socket" plugin, but incorrectly referenced it as plugin="auth_socket" which resulted in mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"
  3. Lacking a way to login to fix this mistake, I was forced to have to stop mysql and use mysql_safe to bypass authentication in order to switch to the appropriate plugin plugin="unix_socket"

Hopefully this saves someone some time if they receive the original poster's error message, but the true cause was flubbing the plugin name, not actually lacking the existence of the "auth_socket" plugin itself, which according to the MariaDB documentation:

In MariaDB 10.4.3 and later, the unix_socket authentication plugin is installed by default, and it is used by the 'root'@'localhost' user account by default.

change PATH permanently on Ubuntu

Add the following line in your .profile file in your home directory (using vi ~/.profile):

PATH=$PATH:/home/me/play
export PATH

Then, for the change to take effect, simply type in your terminal:

$ . ~/.profile

How to get jQuery to wait until an effect is finished?

You can as well use $.when() to wait until the promise finished:

var myEvent = function() {
    $( selector ).fadeOut( 'fast' );
};
$.when( myEvent() ).done( function() {
    console.log( 'Task finished.' );
} );

In case you're doing a request that could as well fail, then you can even go one step further:

$.when( myEvent() )
    .done( function( d ) {
        console.log( d, 'Task done.' );
    } )
    .fail( function( err ) {
        console.log( err, 'Task failed.' );
    } )
    // Runs always
    .then( function( data, textStatus, jqXHR ) {
        console.log( jqXHR.status, textStatus, 'Status 200/"OK"?' );
    } );

How do I uninstall a package installed using npm link?

you can use unlink to remove the symlink.

For Example:

cd ~/projects/node-redis 
npm link                 
cd ~/projects/node-bloggy
npm link redis             # links to your local redis

To reinstall from your package.json:

npm unlink redis
npm install

https://www.tachyonstemplates.com/npm-cheat-sheet/#unlinking-a-npm-package-from-an-application

jQuery Datepicker onchange event issue

I wrote this because I needed a solution to trigger an event only if the date changed.

It is a simple solution. Each time the dialog box closes we test to see if the data has changed. If it has, we trigger a custom event and reset the stored value.

$('.datetime').datepicker({
    onClose: function(dateText,datePickerInstance) {
        var oldValue = $(this).data('oldValue') || "";
        if (dateText !== oldValue) {
            $(this).data('oldValue',dateText);
            $(this).trigger('dateupdated');
        }
    }
});

Now we can hook up handlers for that custom event...

$('body').on('dateupdated','.datetime', function(e) {
    // do something
});

How a thread should close itself in Java?

If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt() (it will not do anything bad though. It's just that you don't need to.) This is because interrupt() is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.

By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?

Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.

If you are NOT the owner of the thread (e.g. if you have not extended Thread and coded a Runnable etc.) you should do

Thread.currentThread().interrupt();
return;

This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.

For the same reason, you should never do

Catch(InterruptedException ie){
     //ignore
}

Because if you do, you are stopping the message there. Instead one should do

Catch(InterruptedException ie){
    Thread.currentThread().interrupt();//preserve the message
    return;//Stop doing whatever I am doing and terminate
}

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

How to update a record using sequelize for node?

This solution is deprecated

failure|fail|error() is deprecated and will be removed in 2.1, please use promise-style instead.

so you have to use

Project.update(

    // Set Attribute values 
    {
        title: 'a very different title now'
    },

    // Where clause / criteria 
    {
        _id: 1
    }

).then(function() {

    console.log("Project with id =1 updated successfully!");

}).catch(function(e) {
    console.log("Project update failed !");
})

And you can use .complete() as well

Regards

Change font color and background in html on mouseover

You'd better use CSS for this:

td{
    background-color:black;
    color:white;
}
td:hover{
    background-color:white;
    color:black;
}

If you want to use these styles for only a specific set of elements, you should give your td a class (or an ID, if it's the only element which'll have that style).

Example :

HTML

<td class="whiteHover"></td>

CSS

.whiteHover{
    /* Same style as above */
}

Here's a reference on MDN for :hover pseudo class.

c++ custom compare function for std::sort()

Look here: http://en.cppreference.com/w/cpp/algorithm/sort.

It says:

template< class RandomIt, class Compare >
void sort( RandomIt first, RandomIt last, Compare comp );
  • comp - comparison function which returns ?true if the first argument is less than the second. The signature of the comparison function should be equivalent to the following: bool cmp(const Type1 &a, const Type2 &b);

Also, here's an example of how you can use std::sort using a custom C++14 polymorphic lambda:

std::sort(std::begin(container), std::end(container),
          [] (const auto& lhs, const auto& rhs) {
    return lhs.first < rhs.first;
});

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

How to create a Java cron job

If you are using unix, you need to write a shellscript to run you java batch first.

After that, in unix, you run this command "crontab -e" to edit crontab script. In order to configure crontab, please refer to this article http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/

Save your crontab setting. Then wait for the time to come, program will run automatically.

jquery find class and get the value

You can also get the value by the following way

$(document).ready(function(){
  $("#start").click(function(){
    alert($(this).find("input[class='myClass']").val());
  });
});

How to use npm with ASP.NET Core

I've found a better way how to manage JS packages in my project with NPM Gulp/Grunt task runners. I don't like the idea to have a NPM with another layer of javascript library to handle the "automation", and my number one requirement is to simple run the npm update without any other worries about to if I need to run gulp stuff, if it successfully copied everything and vice versa.

The NPM way:

  • The JS minifier is already bundled in the ASP.net core, look for bundleconfig.json so this is not an issue for me (not compiling something custom)
  • The good thing about NPM is that is have a good file structure so I can always find the pre-compiled/minified versions of the dependencies under the node_modules/module/dist
  • I'm using an NPM node_modules/.hooks/{eventname} script which is handling the copy/update/delete of the Project/wwwroot/lib/module/dist/.js files, you can find the documentation here https://docs.npmjs.com/misc/scripts (I'll update the script that I'm using to git once it'll be more polished) I don't need additional task runners (.js tools which I don't like) what keeps my project clean and simple.

The python way:

https://pypi.python.org/pyp... but in this case you need to maintain the sources manually

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

var myModule = angular.module('myModule', []);

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

Log4j2 configuration - No log4j2 configuration file found

Was following the documentations - Apache Log4j2 Configuratoin and Apache Log4j2 Maven in configuring log4j2 with yaml. As per the documentation, the following maven dependencies are required:

  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.8.1</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.8.1</version>
  </dependency>

and

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-yaml</artifactId>
    <version>2.8.6</version>
</dependency>

Just adding these didn't pick the configuration and always gave error. The way of debugging configuration by adding -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE helped in seeing the logs. Later had to download the source using Maven and debugging helped in understanding the depended classes of log4j2. They are listed in org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory:

com.fasterxml.jackson.databind.ObjectMapper
com.fasterxml.jackson.databind.JsonNode
com.fasterxml.jackson.core.JsonParser
com.fasterxml.jackson.dataformat.yaml.YAMLFactory

Adding dependency mapping for jackson-dataformat-yaml will not have the first two classes. Hence, add the jackson-databind dependency to get yaml configuration working:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
</dependency>

You may add the version by referring to the Test Dependencies section of log4j-api version item from MVN Repository. E.g. for 2.8.1 version of log4j-api, refer this link and locate the jackson-databind version.

Moreover, you can use the below Java code to check if the classes are available in the classpath:

System.out.println(ClassLoader.getSystemResource("log4j2.yml")); //Check if file is available in CP
ClassLoader cl = Thread.currentThread().getContextClassLoader(); //Code as in log4j2 API. Version: 2.8.1
 String [] classes = {"com.fasterxml.jackson.databind.ObjectMapper",
 "com.fasterxml.jackson.databind.JsonNode",
 "com.fasterxml.jackson.core.JsonParser",
 "com.fasterxml.jackson.dataformat.yaml.YAMLFactory"};

 for(String className : classes) {
     cl.loadClass(className);
 }

Java equivalent to #region in C#

The best way

//region DESCRIPTION_REGION
int x = 22;
// Comments
String s = "SomeString";
//endregion;

Tip: Put ";" at the end of the "endregion"

python-pandas and databases like mysql

And this is how you connect to PostgreSQL using psycopg2 driver (install with "apt-get install python-psycopg2" if you're on Debian Linux derivative OS).

import pandas.io.sql as psql
import psycopg2

conn = psycopg2.connect("dbname='datawarehouse' user='user1' host='localhost' password='uberdba'")

q = """select month_idx, sum(payment) from bi_some_table"""

df3 = psql.frame_query(q, conn)

JNI and Gradle in Android Studio

Gradle Build Tools 2.2.0+ - The closest the NDK has ever come to being called 'magic'

In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild and pointing ndkBuild path argument at an Android.mk or change ndkBuild to cmake and point the path argument at a CMakeLists.txt build script.

android {
    compileSdkVersion 19
    buildToolsVersion "25.0.2"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 19

        ndk {
            abiFilters 'armeabi', 'armeabi-v7a', 'x86'
        }

        externalNativeBuild {
            cmake {
                cppFlags '-std=c++11'
                arguments '-DANDROID_TOOLCHAIN=clang',
                        '-DANDROID_PLATFORM=android-19',
                        '-DANDROID_STL=gnustl_static',
                        '-DANDROID_ARM_NEON=TRUE',
                        '-DANDROID_CPP_FEATURES=exceptions rtti'
            }
        }
    }

    externalNativeBuild {
        cmake {
             path 'src/main/jni/CMakeLists.txt'
        }
        //ndkBuild {
        //   path 'src/main/jni/Android.mk'
        //}
    }
}

For much more detail check Google's page on adding native code.

After this is setup correctly you can ./gradlew installDebug and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.

Android Studio Clean and Build Integration - DEPRECATED

The other answers do point out the correct way to prevent the automatic creation of Android.mk files, but they fail to go the extra step of integrating better with Android Studio. I have added the ability to actually clean and build from source without needing to go to the command-line. Your local.properties file will need to have ndk.dir=/path/to/ndk

apply plugin: 'com.android.application'

android {
    compileSdkVersion 14
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.example.application"
        minSdkVersion 14
        targetSdkVersion 14

        ndk {
            moduleName "YourModuleName"
        }
    }

    sourceSets.main {
        jni.srcDirs = [] // This prevents the auto generation of Android.mk
        jniLibs.srcDir 'src/main/libs' // This is not necessary unless you have precompiled libraries in your project.
    }

    task buildNative(type: Exec, description: 'Compile JNI source via NDK') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                '-j', Runtime.runtime.availableProcessors(),
                'all',
                'NDK_DEBUG=1'
    }

    task cleanNative(type: Exec, description: 'Clean JNI object files') {
        def ndkDir = android.ndkDirectory
        commandLine "$ndkDir/ndk-build",
                '-C', file('src/main/jni').absolutePath, // Change src/main/jni the relative path to your jni source
                'clean'
    }

    clean.dependsOn 'cleanNative'

    tasks.withType(JavaCompile) {
        compileTask -> compileTask.dependsOn buildNative
    }
}

dependencies {
    compile 'com.android.support:support-v4:20.0.0'
}

The src/main/jni directory assumes a standard layout of the project. It should be the relative from this build.gradle file location to the jni directory.

Gradle - for those having issues

Also check this Stack Overflow answer.

It is really important that your gradle version and general setup are correct. If you have an older project I highly recommend creating a new one with the latest Android Studio and see what Google considers the standard project. Also, use gradlew. This protects the developer from a gradle version mismatch. Finally, the gradle plugin must be configured correctly.

And you ask what is the latest version of the gradle plugin? Check the tools page and edit the version accordingly.

Final product - /build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

// Running 'gradle wrapper' will generate gradlew - Getting gradle wrapper working and using it will save you a lot of pain.
task wrapper(type: Wrapper) {
    gradleVersion = '2.2'
}

// Look Google doesn't use Maven Central, they use jcenter now.
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Make sure gradle wrapper generates the gradlew file and gradle/wrapper subdirectory. This is a big gotcha.

ndkDirectory

This has come up a number of times, but android.ndkDirectory is the correct way to get the folder after 1.1. Migrating Gradle Projects to version 1.0.0. If you're using an experimental or ancient version of the plugin your mileage may vary.

The declared package does not match the expected package ""

Try closing and re-opening the file.

It is possible to get this error in eclipse when there is absolutely nothing wrong with the file location or package declaration. Try that before spending a lot of time trying these other solutions. Sometimes eclipse just gets confused. It's worked for me on a number of occasions. I credit the idea to Joshua Goldberg.

When creating a service with sc.exe how to pass in context parameters?

Parameters for created services have some peculiar formating issues, in particular if the command includes spaces or quotes:

If you want to enter command line parameters for the service, you have to enclose the whole command line in quotes. (And always leave a space after binPath= and before the first quote, as mrswadge pointed out)

So, to create a service for the command PATH\COMMAND.EXE --param1=xyz you would use the following binPath parameter:

binPath= "PATH\COMMAND.EXE --param1=xyz"
        ^^                             ^
        ||                             |
  space    quote                     quote

If the path to the executable contains spaces, you have to enclose the path in quotes.

So for a command that has both parameters and a path with spaces, you need nested quotes. You have to escape the inner quotes with backslashes \". The same holds if the parameters themselves contain quotes, you will need to escape those too.

Despite using backslashes as escape characters, you do not have to escape the regular backslashes contained in the path. This is contrary to how you normally use backslashes as escape characters.

So for a command like
"PATH WITH SPACES \COMMAND.EXE" --param-with-quotes="a b c" --param2:

binPath= "\"PATH WITH SPACES \COMMAND.EXE\" --param-with-quotes=\"a b c\" --param2"
         ^ ^                 ^           ^                      ^       ^         ^
         | |                 |           |                      |       |         | 
 opening     escaped      regular     escaped                    escaped       closing
   quote     quote       backslash    closing                    quotes          quote
     for     for            in         quote                      for              for
   whole     path          path       for path                  parameter        whole
 command                                                                       command

Here is a concrete example from the SVNserve documentation, which shows all special cases:

sc create svnserve 
   binpath= "\"C:\Program Files\CollabNet Subversion Server\svnserve.exe\" --service -r \"C:\my repositories\"  "
   displayname= "Subversion Server" depend= Tcpip start= auto 

(linebreaks are added for readability, do not include them)

This would add a new service with the command line "C:\Program Files\CollabNet Subversion Server\svnserve.exe" --service -r "C:\my repositories".

So in summary

  • space after each sc parameter: binpath=_, displayname=_ and depend=_
  • each sc parameter that contains spaces must be enclosed in quotes
  • all additional quotes inside the binpath are escaped with backslashes: \"
  • all backslashes inside the binpath are not escaped

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Different connections pools have different configs.

For example Tomcat (default) expects:

spring.datasource.ourdb.url=...

and HikariCP will be happy with:

spring.datasource.ourdb.jdbc-url=...

We can satisfy both without boilerplate configuration:

spring.datasource.ourdb.jdbc-url=${spring.datasource.ourdb.url}

There is no property to define connection pool provider.

Take a look at source DataSourceBuilder.java

If Tomcat, HikariCP or Commons DBCP are on the classpath one of them will be selected (in that order with Tomcat first).

... so, we can easily replace connection pool provider using this maven configuration (pom.xml):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>       

    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
    </dependency>

Data structure for maintaining tabular data in memory?

Have a Table class whose rows is a list of dict or better row objects

In table do not directly add rows but have a method which update few lookup maps e.g. for name if you are not adding rows in order or id are not consecutive you can have idMap too e.g.

class Table(object):
    def __init__(self):
        self.rows =  []# list of row objects, we assume if order of id
        self.nameMap = {} # for faster direct lookup for row by name

    def addRow(self, row):
        self.rows.append(row)
        self.nameMap[row['name']] = row

    def getRow(self, name):
        return self.nameMap[name]


table = Table()
table.addRow({'ID':1,'name':'a'})

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Importing text file into excel sheet

There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)

  1. Using a QueryTable
  2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
  3. If you want to use the method that you are currently using then after you open the text file in a new workbook, simply copy it over to the current sheet using Cells.Copy

Using a QueryTable

Here is a simple macro that I recorded. Please amend it to suit your needs.

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

Open the text file in memory

Sub Sample()
    Dim MyData As String, strData() As String

    Open "C:\Sample.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub

Once you have the data in the array you can export it to the current sheet.

Using the method that you are already using

Sub Sample()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("C:\Sample.txt")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

FOLLOWUP

You can use the Application.GetOpenFilename to choose the relevant file. For example...

Sub Sample()
    Dim Ret

    Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")

    If Ret <> False Then
        With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Ret, Destination:=Range("$A$1"))

            '~~> Rest of the code

        End With
    End If
End Sub

Best way to define private methods for a class in Objective-C

If you wanted to avoid the @interface block at the top you could always put the private declarations in another file MyClassPrivate.h not ideal but its not cluttering up the implementation.

MyClass.h

interface MyClass : NSObject {
 @private
  BOOL publicIvar_;
  BOOL privateIvar_;
}

@property (nonatomic, assign) BOOL publicIvar;
//any other public methods. etc
@end

MyClassPrivate.h

@interface MyClass ()

@property (nonatomic, assign) BOOL privateIvar;
//any other private methods etc.
@end

MyClass.m

#import "MyClass.h"
#import "MyClassPrivate.h"
@implementation MyClass

@synthesize privateIvar = privateIvar_;
@synthesize publicIvar = publicIvar_;

@end

Reset AutoIncrement in SQL Server after Delete

semi idiot-proof:

declare @max int;  
select @max = max(key) from table;  
dbcc checkident(table,reseed,@max)

http://sqlserverplanet.com/tsql/using-dbcc-checkident-to-reseed-a-table-after-delete

What characters are forbidden in Windows and Linux directory names?

For anyone looking for a regex:

const BLACKLIST = /[<>:"\/\\|?*]/g;

jQuery get textarea text

the best way: $('#myTextBox').val('new value').trim();

What is the $$hashKey added to my JSON.stringify result

It comes with the ng-repeat directive usually. To do dom manipulation AngularJS flags objects with special id.

This is common with Angular. For example if u get object with ngResource your object will embed all the resource API and you'll see methods like $save, etc. With cookies too AngularJS will add a property __ngDebug.

What is Turing Complete?

A Turing Machine requires that any program can perform condition testing. That is fundamental.

Consider a player piano roll. The player piano can play a highly complicated piece of music, but there is never any conditional logic in the music. It is not Turing Complete.

Conditional logic is both the power and the danger of a machine that is Turing Complete.

The piano roll is guaranteed to halt every time. There is no such guarantee for a TM. This is called the “halting problem.”

How can I add comments in MySQL?

"A comment for a column can be specified with the COMMENT option. The comment is displayed by the SHOW CREATE TABLE and SHOW FULL COLUMNS statements. This option is operational as of MySQL 4.1. (It is allowed but ignored in earlier versions.)"

As an example

--
-- Table structure for table 'accesslog'
--

CREATE TABLE accesslog (
aid int(10) NOT NULL auto_increment COMMENT 'unique ID for each access entry', 
title varchar(255) default NULL COMMENT 'the title of the page being accessed',
path varchar(255) default NULL COMMENT 'the local path of teh page being accessed',
....
) TYPE=MyISAM;

How to generate .json file with PHP?

You can simply use json_encode function of php and save file with file handling functions such as fopen and fwrite.

How to normalize a NumPy array to within a certain range?

A simple solution is using the scalers offered by the sklearn.preprocessing library.

scaler = sk.MinMaxScaler(feature_range=(0, 250))
scaler = scaler.fit(X)
X_scaled = scaler.transform(X)
# Checking reconstruction
X_rec = scaler.inverse_transform(X_scaled)

The error X_rec-X will be zero. You can adjust the feature_range for your needs, or even use a standart scaler sk.StandardScaler()

How do I multiply each element in a list by a number?

I found it interesting to use list comprehension or map with just one object name x. Note that whenever x is reassigned, its id(x) changes, i.e. points to a different object.

x = [1, 2, 3]
id(x)
2707834975552
x = [1.5 * x for x in x]
id(x)
2707834976576
x
[1.5, 3.0, 4.5]
list(map(lambda x : 2 * x / 3, x))
[1.0, 2.0, 3.0]
id(x) # not reassigned
2707834976576
x = list(map(lambda x : 2 * x / 3, x))
x
[1.0, 2.0, 3.0]
id(x)
2707834980928

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

codeigniter needs to load the url helper to call the base_url() function.

use application->config->autoload.php

edit autoload helper array and add url helper..

base_url() function is working now..

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

Answer for MYSQL USERS:

ALTER TABLE ChildTableName 
DROP FOREIGN KEY `fk_table`;
ALTER TABLE ChildTableName 
ADD CONSTRAINT `fk_t1_t2_tt`
  FOREIGN KEY (`parentTable`)
  REFERENCES parentTable (`columnName`)
  ON DELETE CASCADE
  ON UPDATE CASCADE;

Tree view of a directory/folder in Windows?

TreeSize professional has what you want. but it focus on the sizes of folders and files.

Wildcards in a Windows hosts file

To answer your question, you cannot use wildcards in the hosts file under Windows.

However, if you want to only change the hosts file to make new sites work.... you can configure your Apache like this and you don't have to keep editing it's config:

http://postpostmodern.com/instructional/a-smarter-mamp/

Basically a quick summary based on my setup, add the following to your apache.conf file:

 LoadModule vhost_alias_module modules/mod_vhost_alias.so

 NameVirtualHost *:80

  <Directory "/xampp/sites">
      Options Indexes FollowSymLinks Includes ExecCGI
      AllowOverride All
      Order allow,deny
      Allow from all 
  </Directory>

  <VirtualHost *:80>
      VirtualDocumentRoot c:/xampp/sites/%-1/%-2+/
  </VirtualHost>

This allows me to add an entry like:

127.0.0.1       test.dev

and then make the directory, c:\xampp\sites\dev\test and place the necessary files in there and it just works.

The other option is to use <Directory> tags in apache.conf and reference the pages from http://localhost/project/.

Removing multiple keys from a dictionary safely

Why not:

entriestoremove = (2,5,1)
for e in entriestoremove:
    if d.has_key(e):
        del d[e]

I don't know what you mean by "smarter way". Surely there are other ways, maybe with dictionary comprehensions:

entriestoremove = (2,5,1)
newdict = {x for x in d if x not in entriestoremove}

How to make an autocomplete TextBox in ASP.NET?

1-Install AjaxControl Toolkit easily by Nugget

PM> Install-Package AjaxControlToolkit

2-then in markup

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">  
</asp:ToolkitScriptManager>  

<asp:TextBox ID="txtMovie" runat="server"></asp:TextBox>  

<asp:AutoCompleteExtender  ID="AutoCompleteExtender1"  TargetControlID="txtMovie"   
    runat="server" />  

3- in code-behind : to get the suggestions

[System.Web.Services.WebMethodAttribute(),System.Web.Script.Services.ScriptMethodAttribute()]  
    public static string[] GetCompletionList(string prefixText, int count, string contextKey) {  
        // Create array of movies  
        string[] movies = {"Star Wars", "Star Trek", "Superman", "Memento", "Shrek", "Shrek II"};  

        // Return matching movies  
        return (from m in movies where m.StartsWith(prefixText,StringComparison.CurrentCultureIgnoreCase) select m).Take(count).ToArray();  
    }

source: http://www.asp.net/ajaxlibrary/act_autocomplete_simple.ashx

How to merge remote master to local branch

Switch to your local branch

> git checkout configUpdate

Merge remote master to your branch

> git rebase master configUpdate

In case you have any conflicts, correct them and for each conflicted file do the command

> git add [path_to_file/conflicted_file] (e.g. git add app/assets/javascripts/test.js)

Continue rebase

> git rebase --continue

Add new element to an existing object

Use this:

myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';

Or, if you are using jQuery:

$(myFunction).extend({
    bookName:'mybook',
    bookdesc: 'new'
});

The push method is wrong because it belongs to the Array.prototype object.

To create a named object, try this:

var myObj = function(){
    this.property = 'foo';
    this.bar = function(){
    }
}
myObj.prototype.objProp = true;
var newObj = new myObj();

Copying one structure to another

You can memcpy structs, or you can just assign them like any other value.

struct {int a, b;} c, d;
c.a = c.b = 10;
d = c;

Abstract Class vs Interface in C++

Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.

class IInterface() 
{ 
   Public: 
   Virtual ~IInterface(){}; 
   … 
} 

Class ClassImpl : public IInterface 
{ 
    … 
} 

Int main() 
{ 

  IInterface* pInterface = new ClassImpl(); 
  … 
  delete pInterface; // Wrong in OO Programming, correct in C++.
}

Change Placeholder Text using jQuery

If the input is inside the div than you can try this:

$('#div_id input').attr("placeholder", "placeholder text");

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

Creating a folder if it does not exists - "Item already exists"

With New-Item you can add the Force parameter

New-Item -Force -ItemType directory -Path foo

Or the ErrorAction parameter

New-Item -ErrorAction Ignore -ItemType directory -Path foo

How to rename a pane in tmux?

For those who want to easily rename their panes, this is what I have in my .tmux.conf

set -g default-command '                      \
function renamePane () {                      \
  read -p "Enter Pane Name: " pane_name;      \
  printf "\033]2;%s\033\\r:r" "${pane_name}"; \
};                                            \
export -f renamePane;                         \
bash -i'
set -g pane-border-status top
set -g pane-border-format "#{pane_index} #T #{pane_current_command}"
bind-key -T prefix R send-keys "renamePane" C-m

Panes are automatically named with their index, machine name and current command. To change the machine name you can run <C-b>R which will prompt you to enter a new name.

*Pane renaming only works when you are in a shell.

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

Redis: Show database size/size for keys

The solution from the comments deserves it's own answer:

redis-cli --bigkeys

Move UIView up when the keyboard appears in iOS

Based on theDunc's answer but written in Swift with Autolayout.

@IBOutlet weak var bottomConstraint: NSLayoutConstraint! // connect the bottom of the view you want to move to the bottom layout guide

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(ConversationViewController.keyboardWillShow(_:)),
                                                     name: UIKeyboardWillShowNotification,
                                                     object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self,
                                                     selector: #selector(ConversationViewController.keyboardWillHide(_:)),
                                                     name: UIKeyboardWillHideNotification,
                                                     object: nil)
}

override func viewWillDisappear(animated: Bool) {
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
    super.viewWillDisappear(animated)
}

// MARK: - Keyboard events

func keyboardWillShow(notification: NSNotification) {
    if let userInfo = notification.userInfo,
        keyboardFrame = userInfo[UIKeyboardFrameBeginUserInfoKey]
    {
        let keyboardSize = keyboardFrame.CGRectValue().size
        self.bottomConstraint.constant = keyboardSize.height
        UIView.animateWithDuration(0.3) {
            self.view.layoutIfNeeded()
        }
    }
}

func keyboardWillHide(notification: NSNotification) {
    self.bottomConstraint.constant = 0
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

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

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

Get program execution time in the shell

For a line-by-line delta measurement, try gnomon.

A command line utility, a bit like moreutils's ts, to prepend timestamp information to the standard output of another command. Useful for long-running processes where you'd like a historical record of what's taking so long.

You can also use the --high and/or --medium options to specify a length threshold in seconds, over which gnomon will highlight the timestamp in red or yellow. And you can do a few other things, too.

example

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

The solution was to add these flags to JVM command line when Tomcat is started:

-XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled

You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service.

If you get an error the specified service does not exist as an installed service you should run:

tomcat6w //ES//servicename

where servicename is the name of the server as viewed in services.msc

Source: orx's comment on Eric's Agile Answers.

Difference between EXISTS and IN in SQL?

I think,

  • EXISTS is when you need to match the results of query with another subquery. Query#1 results need to be retrieved where SubQuery results match. Kind of a Join.. E.g. select customers table#1 who have placed orders table#2 too

  • IN is to retrieve if the value of a specific column lies IN a list (1,2,3,4,5) E.g. Select customers who lie in the following zipcodes i.e. zip_code values lies in (....) list.

When to use one over the other... when you feel it reads appropriately (Communicates intent better).

Why does z-index not work?

In many cases an element must be positioned for z-index to work.

Indeed, applying position: relative to the elements in the question would likely solve the problem (but there's not enough code provided to know for sure).

Actually, position: fixed, position: absolute and position: sticky will also enable z-index, but those values also change the layout. With position: relative the layout isn't disturbed.

Essentially, as long as the element isn't position: static (the default setting) it is considered positioned and z-index will work.


Many answers to "Why isn't z-index working?" questions assert that z-index only works on positioned elements. As of CSS3, this is no longer true.

Elements that are flex items or grid items can use z-index even when position is static.

From the specs:

4.3. Flex Item Z-Ordering

Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

5.4. Z-axis Ordering: the z-index property

The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is used in place of raw document order, and z-index values other than auto create a stacking context even if position is static.

Here's a demonstration of z-index working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/

What does it mean to bind a multicast (UDP) socket?

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application. (Same holds true for TCP sockets).

When you bind to "0.0.0.0" (INADDR_ANY), you are basically telling the TCP/IP layer to use all available adapters for listening and to choose the best adapter for sending. This is standard practice for most socket code. The only time you wouldn't specify 0 for the IP address is when you want to send/receive on a specific network adapter.

Similarly if you specify a port value of 0 during bind, the OS will assign a randomly available port number for that socket. So I would expect for UDP multicast, you bind to INADDR_ANY on a specific port number where multicast traffic is expected to be sent to.

The "join multicast group" operation (IP_ADD_MEMBERSHIP) is needed because it basically tells your network adapter to listen not only for ethernet frames where the destination MAC address is your own, it also tells the ethernet adapter (NIC) to listen for IP multicast traffic as well for the corresponding multicast ethernet address. Each multicast IP maps to a multicast ethernet address. When you use a socket to send to a specific multicast IP, the destination MAC address on the ethernet frame is set to the corresponding multicast MAC address for the multicast IP. When you join a multicast group, you are configuring the NIC to listen for traffic sent to that same MAC address (in addition to its own).

Without the hardware support, multicast wouldn't be any more efficient than plain broadcast IP messages. The join operation also tells your router/gateway to forward multicast traffic from other networks. (Anyone remember MBONE?)

If you join a multicast group, all the multicast traffic for all ports on that IP address will be received by the NIC. Only the traffic destined for your binded listening port will get passed up the TCP/IP stack to your app. In regards to why ports are specified during a multicast subscription - it's because multicast IP is just that - IP only. "ports" are a property of the upper protocols (UDP and TCP).

You can read more about how multicast IP addresses map to multicast ethernet addresses at various sites. The Wikipedia article is about as good as it gets:

The IANA owns the OUI MAC address 01:00:5e, therefore multicast packets are delivered by using the Ethernet MAC address range 01:00:5e:00:00:00 - 01:00:5e:7f:ff:ff. This is 23 bits of available address space. The first octet (01) includes the broadcast/multicast bit. The lower 23 bits of the 28-bit multicast IP address are mapped into the 23 bits of available Ethernet address space.

Getting the length of two-dimensional array

Here's a complete solution to how to enumerate elements in a jagged two-dimensional array (with 3 rows and 3 to 5 columns):

    String row = "";
    int[][] myArray = {{11, 12, 13}, {14, 15, 16, 17}, {18, 19, 20, 21, 22}};
    for (int i=0; i<myArray.length; i++) {
        row+="\n";
        for (int j = 0; j<myArray[i].length; j++) {
            row += myArray[i][j] + "  ";
        }
    }
    JOptionPane.showMessageDialog(null, "myArray contains:" + row);

Jagged array's contents

How to hide column of DataGridView when using custom DataSource?

I have noticed that if utilised progrmmatically it renders incomplete (entire form simply doesn't "paint" anything) if used before panel1.Controls.Add(dataGridView); then dataGridView.Columns["ID"].Visible = false; will break the entire form and make it blank, so to get round that set this AFTER EG:

 panel1.Controls.Add(dataGridView);
 dataGridView.Columns["ID"].Visible = false; 
 //works

 dataGridView.Columns["ID"].Visible = false; 
 panel1.Controls.Add(dataGridView);
 //fails miserably

set the iframe height automatically

Try this coding

<div>
    <iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
        width: 100%; position: absolute;"></iframe>
</div>

Write to UTF-8 file in Python

I believe the problem is that codecs.BOM_UTF8 is a byte string, not a Unicode string. I suspect the file handler is trying to guess what you really mean based on "I'm meant to be writing Unicode as UTF-8-encoded text, but you've given me a byte string!"

Try writing the Unicode string for the byte order mark (i.e. Unicode U+FEFF) directly, so that the file just encodes that as UTF-8:

import codecs

file = codecs.open("lol", "w", "utf-8")
file.write(u'\ufeff')
file.close()

(That seems to give the right answer - a file with bytes EF BB BF.)

EDIT: S. Lott's suggestion of using "utf-8-sig" as the encoding is a better one than explicitly writing the BOM yourself, but I'll leave this answer here as it explains what was going wrong before.

Changing the action of a form with JavaScript/jQuery

Use Java script to change action url dynamically Works for me well

function chgAction( action_name )
{

 {% for data in sidebar_menu_data %}

     if( action_name== "ABC"){ document.forms.action = "/ABC/";
     }
     else if( action_name== "XYZ"){ document.forms.action = "/XYZ/";
     }

}

<form name="forms" method="post" action="<put default url>" onSubmit="return checkForm(this);">{% csrf_token %} 

Postgresql : syntax error at or near "-"

Wrap it in double quotes

alter user "dell-sys" with password 'Pass@133';

Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys" then you will have to issue exact the same whenever you refer to that user.

I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.

Copy table without copying data

Only want to clone the structure of table:

CREATE TABLE foo SELECT * FROM bar WHERE 1 = 2;

Also wants to copy the data:

CREATE TABLE foo as SELECT * FROM bar;

Using MySQL with Entity Framework

You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen. This blog talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.

How to make a gui in python

Just look at the python GUI programming options at http://wiki.python.org/moin/GuiProgramming. But, Consider Wxpython for your GUI application as it is cross platform. And,from above link you could also get some IDE to work upon.

grep using a character vector with multiple patterns

Take away the spaces. So do:

matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))