Programs & Examples On #Contact list

Change Input to Upper Case

Javascript has a toUpperCase() method. http://www.w3schools.com/jsref/jsref_toUpperCase.asp

So wherever you think best to put it in your code, you would have to do something like

$(".keywords").val().toUpperCase()

simple HTTP server in Java using only Java SE API

It's possible to create an httpserver that provides basic support for J2EE servlets with just the JDK and the servlet api in a just a few lines of code.

I've found this very useful for unit testing servlets, as it starts much faster than other lightweight containers (we use jetty for production).

Most very lightweight httpservers do not provide support for servlets, but we need them, so I thought I'd share.

The below example provides basic servlet support, or throws and UnsupportedOperationException for stuff not yet implemented. It uses the com.sun.net.httpserver.HttpServer for basic http support.

import java.io.*;
import java.lang.reflect.*;
import java.net.InetSocketAddress;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

@SuppressWarnings("deprecation")
public class VerySimpleServletHttpServer {
    HttpServer server;
    private String contextPath;
    private HttpHandler httpHandler;

    public VerySimpleServletHttpServer(String contextPath, HttpServlet servlet) {
        this.contextPath = contextPath;
        httpHandler = new HttpHandlerWithServletSupport(servlet);
    }

    public void start(int port) throws IOException {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
        server = HttpServer.create(inetSocketAddress, 0);
        server.createContext(contextPath, httpHandler);
        server.setExecutor(null);
        server.start();
    }

    public void stop(int secondsDelay) {
        server.stop(secondsDelay);
    }

    public int getServerPort() {
        return server.getAddress().getPort();
    }

}

final class HttpHandlerWithServletSupport implements HttpHandler {

    private HttpServlet servlet;

    private final class RequestWrapper extends HttpServletRequestWrapper {
        private final HttpExchange ex;
        private final Map<String, String[]> postData;
        private final ServletInputStream is;
        private final Map<String, Object> attributes = new HashMap<>();

        private RequestWrapper(HttpServletRequest request, HttpExchange ex, Map<String, String[]> postData, ServletInputStream is) {
            super(request);
            this.ex = ex;
            this.postData = postData;
            this.is = is;
        }

        @Override
        public String getHeader(String name) {
            return ex.getRequestHeaders().getFirst(name);
        }

        @Override
        public Enumeration<String> getHeaders(String name) {
            return new Vector<String>(ex.getRequestHeaders().get(name)).elements();
        }

        @Override
        public Enumeration<String> getHeaderNames() {
            return new Vector<String>(ex.getRequestHeaders().keySet()).elements();
        }

        @Override
        public Object getAttribute(String name) {
            return attributes.get(name);
        }

        @Override
        public void setAttribute(String name, Object o) {
            this.attributes.put(name, o);
        }

        @Override
        public Enumeration<String> getAttributeNames() {
            return new Vector<String>(attributes.keySet()).elements();
        }

        @Override
        public String getMethod() {
            return ex.getRequestMethod();
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            return is;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(getInputStream()));
        }

        @Override
        public String getPathInfo() {
            return ex.getRequestURI().getPath();
        }

        @Override
        public String getParameter(String name) {
            String[] arr = postData.get(name);
            return arr != null ? (arr.length > 1 ? Arrays.toString(arr) : arr[0]) : null;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            return postData;
        }

        @Override
        public Enumeration<String> getParameterNames() {
            return new Vector<String>(postData.keySet()).elements();
        }
    }

    private final class ResponseWrapper extends HttpServletResponseWrapper {
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final ServletOutputStream servletOutputStream = new ServletOutputStream() {

            @Override
            public void write(int b) throws IOException {
                outputStream.write(b);
            }
        };

        private final HttpExchange ex;
        private final PrintWriter printWriter;
        private int status = HttpServletResponse.SC_OK;

        private ResponseWrapper(HttpServletResponse response, HttpExchange ex) {
            super(response);
            this.ex = ex;
            printWriter = new PrintWriter(servletOutputStream);
        }

        @Override
        public void setContentType(String type) {
            ex.getResponseHeaders().add("Content-Type", type);
        }

        @Override
        public void setHeader(String name, String value) {
            ex.getResponseHeaders().add(name, value);
        }

        @Override
        public javax.servlet.ServletOutputStream getOutputStream() throws IOException {
            return servletOutputStream;
        }

        @Override
        public void setContentLength(int len) {
            ex.getResponseHeaders().add("Content-Length", len + "");
        }

        @Override
        public void setStatus(int status) {
            this.status = status;
        }

        @Override
        public void sendError(int sc, String msg) throws IOException {
            this.status = sc;
            if (msg != null) {
                printWriter.write(msg);
            }
        }

        @Override
        public void sendError(int sc) throws IOException {
            sendError(sc, null);
        }

        @Override
        public PrintWriter getWriter() throws IOException {
            return printWriter;
        }

        public void complete() throws IOException {
            try {
                printWriter.flush();
                ex.sendResponseHeaders(status, outputStream.size());
                if (outputStream.size() > 0) {
                    ex.getResponseBody().write(outputStream.toByteArray());
                }
                ex.getResponseBody().flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                ex.close();
            }
        }
    }

    public HttpHandlerWithServletSupport(HttpServlet servlet) {
        this.servlet = servlet;
    }

    @SuppressWarnings("deprecation")
    @Override
    public void handle(final HttpExchange ex) throws IOException {
        byte[] inBytes = getBytes(ex.getRequestBody());
        ex.getRequestBody().close();
        final ByteArrayInputStream newInput = new ByteArrayInputStream(inBytes);
        final ServletInputStream is = new ServletInputStream() {

            @Override
            public int read() throws IOException {
                return newInput.read();
            }
        };

        Map<String, String[]> parsePostData = new HashMap<>();

        try {
            parsePostData.putAll(HttpUtils.parseQueryString(ex.getRequestURI().getQuery()));

            // check if any postdata to parse
            parsePostData.putAll(HttpUtils.parsePostData(inBytes.length, is));
        } catch (IllegalArgumentException e) {
            // no postData - just reset inputstream
            newInput.reset();
        }
        final Map<String, String[]> postData = parsePostData;

        RequestWrapper req = new RequestWrapper(createUnimplementAdapter(HttpServletRequest.class), ex, postData, is);

        ResponseWrapper resp = new ResponseWrapper(createUnimplementAdapter(HttpServletResponse.class), ex);

        try {
            servlet.service(req, resp);
            resp.complete();
        } catch (ServletException e) {
            throw new IOException(e);
        }
    }

    private static byte[] getBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        while (true) {
            int r = in.read(buffer);
            if (r == -1)
                break;
            out.write(buffer, 0, r);
        }
        return out.toByteArray();
    }

    @SuppressWarnings("unchecked")
    private static <T> T createUnimplementAdapter(Class<T> httpServletApi) {
        class UnimplementedHandler implements InvocationHandler {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                throw new UnsupportedOperationException("Not implemented: " + method + ", args=" + Arrays.toString(args));
            }
        }

        return (T) Proxy.newProxyInstance(UnimplementedHandler.class.getClassLoader(),
                new Class<?>[] { httpServletApi },
                new UnimplementedHandler());
    }
}

How to create a inset box-shadow only on one side?

This is what you are looking for. It has examples for each side you want with a shadow.

.top-box
{
    box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.4);
}
.left-box
{
    box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.4);
}
.right-box
{
    box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.4);
}
.bottom-box
{
    box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.4);
}

See the snippet for more examples:

_x000D_
_x000D_
body {
    background-color:#0074D9;
}
div {
    background-color:#ffffff;
    padding:20px;
    margin-top:10px;
}
.top-box {
    box-shadow: inset 0 7px 9px -7px rgba(0,0,0,0.7);
}
.left-box {
    box-shadow: inset 7px 0 9px -7px rgba(0,0,0,0.7);
}
.right-box {
    box-shadow: inset -7px 0 9px -7px rgba(0,0,0,0.7);
}
.bottom-box {
    box-shadow: inset 0 -7px 9px -7px rgba(0,0,0,0.7);
}
.top-gradient-box {
    background: linear-gradient(to bottom, #999 0, #ffffff 7px, #ffffff 100%);
}
.left-gradient-box {
    background: linear-gradient(to right, #999 0, #ffffff 7px, #ffffff 100%);
}
.right-gradient-box {
    background: linear-gradient(to left, #999 0, #ffffff 7px, #ffffff 100%);
}
.bottom-gradient-box {
    background: linear-gradient(to top, #999 0, #ffffff 7px, #ffffff 100%);
}
_x000D_
<div class="top-box">
        This area has a top shadow using box-shadow
</div>

<div class="left-box">
        This area has a left shadow using box-shadow
</div>

<div class="right-box">
        This area has a right shadow using box-shadow
</div>

<div class="bottom-box">
        This area has a bottom shadow using box-shadow
</div>

<div class="top-gradient-box">
        This area has a top shadow using gradients
</div>
<div class="left-gradient-box">
        This area has a left shadow using gradients
</div>
<div class="right-gradient-box">
        This area has a right shadow using gradients
</div>
<div class="bottom-gradient-box">
        This area has a bottom shadow using gradients
</div>
_x000D_
_x000D_
_x000D_

What's the effect of adding 'return false' to a click event listener?

The return false prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.

onclick="return false"

Center content in responsive bootstrap navbar

There's another way to do this for layouts that doesn't have to put the navbar inside the container, and which doesn't require any CSS or Bootstrap overrides.

Simply place a div with the Bootstrap container class around the navbar. This will center the links inside the navbar:

<nav class="navbar navbar-default">
  <!-- here's where you put the container tag -->
  <div class="container">

    <div class="navbar-header">
    <!-- header and collapsed icon here -->
    </div>

    <div class="collapse navbar-collapse">
      <ul class="nav navbar-nav">
      <!-- links here -->
      </ul>
    </div>
  </div> <!-- close the container tag -->
</nav> <!-- close the nav tag -->

If you want the then align body content to the center navbar, you also put that body content in the Bootstrap container tag.

<div class="container">
  <! -- body content here -->
</div>

Not everyone can use this type of layout (some people need to nest the navbar itself inside the container). Nonetheless, if you can do it, it's an easy way to get your navbar links and body centered.

You can see the results in this fullpage JSFiddle: http://jsfiddle.net/bdd9U/231/embedded/result/

Source: http://jsfiddle.net/bdd9U/229/

Difference between Role and GrantedAuthority in Spring Security

Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

How can I set the font-family & font-size inside of a div?

Append a semicolon to the following line to fix the issue.

font-family:    Arial, Helvetica, sans-serif;

How to change the application launcher icon on Flutter?

When a new Flutter app is created, it has a default launcher icon. To customize this icon, you might want to check out the flutter_launcher_icons package.

Alternatively, you can do it manually using the following steps. This step covers replacing these placeholder icons with your app’s icons:

Android

  1. Review the Material Design product icons guidelines for icon design.

  2. In the <app dir>/android/app/src/main/res/ directory, place your icon files in folders named using configuration qualifiers. The default mipmap- folders demonstrate the correct naming convention.

  3. In AndroidManifest.xml, update the application tag’s android:icon attribute to reference icons from the previous step (for example, <application android:icon="@mipmap/ic_launcher" ...).

  4. To verify that the icon has been replaced, run your app and inspect the app icon in the Launcher.

iOS

  1. Review the iOS App Icon guidelines.
  2. In the Xcode project navigator, select Assets.xcassets in the Runner folder. Update the placeholder icons with your own app icons.
  3. Verify the icon has been replaced by running your app using a flutter run.

Binary numbers in Python

Binary, decimal, hexadecimal... the base only matters when reading or outputting numbers, adding binary numbers is just the same as adding decimal number : it is just a matter of representation.

How to get the next auto-increment id in mysql

use "mysql_insert_id()". mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.

Below are the example of use:

<?php
    $link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable  VALUES('','value')");
printf("Last inserted record has id %d\n", mysql_insert_id());
    ?>

I hope above example is useful.

How do I tell CMake to link in a static library in the source directory?

CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}, doing the following should succeed:

add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)

how to disable DIV element and everything inside

Try this!

$("#test *").attr("disabled", "disabled").off('click');

I don't see you using jquery above, but you have it listed as a tag.

PDOException SQLSTATE[HY000] [2002] No such file or directory

When using a VirtualMachine make sure you ssh into that machine and navigate to your App folder and call the php artisan migrate command from there.

How do I debug Windows services in Visual Studio?

I found this question, but I think a clear and simple answer is missing.

I don't want to attach my debugger to a process, but I still want to be able to call the service OnStart and OnStop methods. I also want it to run as a console application so that I can log information from NLog to a console.

I found these brilliant guides that does this:

Start by changing the projects Output type to Console Application.

Enter image description here

Change your Program.cs to look like this:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        // Startup as service.
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        };

        if (Environment.UserInteractive)
        {
            RunInteractive(ServicesToRun);
        }
        else
        {
            ServiceBase.Run(ServicesToRun);
        }
    }
}

Then add the following method to allow services running in interactive mode.

static void RunInteractive(ServiceBase[] servicesToRun)
{
    Console.WriteLine("Services running in interactive mode.");
    Console.WriteLine();

    MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart",
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Starting {0}...", service.ServiceName);
        onStartMethod.Invoke(service, new object[] { new string[] { } });
        Console.Write("Started");
    }

    Console.WriteLine();
    Console.WriteLine();
    Console.WriteLine(
        "Press any key to stop the services and end the process...");
    Console.ReadKey();
    Console.WriteLine();

    MethodInfo onStopMethod = typeof(ServiceBase).GetMethod("OnStop",
        BindingFlags.Instance | BindingFlags.NonPublic);
    foreach (ServiceBase service in servicesToRun)
    {
        Console.Write("Stopping {0}...", service.ServiceName);
        onStopMethod.Invoke(service, null);
        Console.WriteLine("Stopped");
    }

    Console.WriteLine("All services stopped.");
    // Keep the console alive for a second to allow the user to see the message.
    Thread.Sleep(1000);
}

Setting up FTP on Amazon Cloud Server

maybe worth mentioning in addition to clone45's answer:

Fixing Write Permissions for Chrooted FTP Users in vsftpd

The vsftpd version that comes with Ubuntu 12.04 Precise does not permit chrooted local users to write by default. By default you will have this in /etc/vsftpd.conf:

chroot_local_user=YES
write_enable=YES

In order to allow local users to write, you need to add the following parameter:

allow_writeable_chroot=YES

Note: Issues with write permissions may show up as following FileZilla errors:

Error: GnuTLS error -15: An unexpected TLS packet was received.
Error: Could not connect to server

References:
Fixing Write Permissions for Chrooted FTP Users in vsftpd
VSFTPd stopped working after update

Right pad a string with variable number of spaces

Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.

Also, this allows for padding a field to the maximum length of its contents.

WITH
cte AS (
  SELECT 'foo' AS value_to_be_padded
  UNION SELECT 'foobar'
),
cte_max AS (
  SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
  CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
  CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;

gitignore all files of extension in directory

It would appear that the ** syntax is supported by git as of version 1.8.2.1 according to the documentation.

Two consecutive asterisks ("**") in patterns matched against full pathname may have special meaning:

  • A leading "**" followed by a slash means match in all directories. For example, "**/foo" matches file or directory "foo" anywhere, the same as pattern "foo". "**/foo/bar" matches file or directory "bar" anywhere that is directly under directory "foo".

  • A trailing "/**" matches everything inside. For example, "abc/**" matches all files inside directory "abc", relative to the location of the .gitignore file, with infinite depth.

  • A slash followed by two consecutive asterisks then a slash matches zero or more directories. For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on.

  • Other consecutive asterisks are considered invalid.

How to create the most compact mapping n ? isprime(n) up to a limit N?

I have got a prime function which works until (2^61)-1 Here:

from math import sqrt
def isprime(num): num > 1 and return all(num % x for x in range(2, int(sqrt(num)+1)))

Explanation:

The all() function can be redefined to this:

def all(variables):
    for element in variables:
        if not element: return False
    return True

The all() function just goes through a series of bools / numbers and returns False if it sees 0 or False.

The sqrt() function is just doing the square root of a number.

For example:

>>> from math import sqrt
>>> sqrt(9)
>>> 3
>>> sqrt(100)
>>> 10

The num % x part returns the remainder of num / x.

Finally, range(2, int(sqrt(num))) means that it will create a list that starts at 2 and ends at int(sqrt(num)+1)

For more information about range, have a look at this website!

The num > 1 part is just checking if the variable num is larger than 1, becuase 1 and 0 are not considered prime numbers.

I hope this helped :)

Windows 10 SSH keys

I'm running Microsoft Windows 10 Pro, Version 10.0.17763 Build 17763, and I see my .ssh folder easily at C:\Users\jrosario\.ssh without having to edit permissions or anything (though in File Explorer, I did select "Show hidden files, folders and drives"): enter image description here

The keys are stored in a text file named known_hosts, which looks roughly like this: enter image description here

Editing hosts file to redirect url?

Apply this trick.

First you need IP address of url you want to redirect to. Lets say you want to redirect to stackoverflow.com To find it, use the ping command in a Command Prompt. Type in:

ping stackoverflow.com

into the command prompt window and you’ll see stackoverflow's numerical IP address. Now use that IP into your host file

104.16.36.249 google.com

yay now google is serving stackoverflow :)

When is std::weak_ptr useful?

http://en.cppreference.com/w/cpp/memory/weak_ptr std::weak_ptr is a smart pointer that holds a non-owning ("weak") reference to an object that is managed by std::shared_ptr. It must be converted to std::shared_ptr in order to access the referenced object.

std::weak_ptr models temporary ownership: when an object needs to be accessed only if it exists, and it may be deleted at any time by someone else, std::weak_ptr is used to track the object, and it is converted to std::shared_ptr to assume temporary ownership. If the original std::shared_ptr is destroyed at this time, the object's lifetime is extended until the temporary std::shared_ptr is destroyed as well.

In addition, std::weak_ptr is used to break circular references of std::shared_ptr.

How to upgrade PowerShell version from 2.0 to 3.0

  1. Install Chocolatey
  2. Run the following commands in CMD

    • choco install powershell

    • choco upgrade powershell

rails 3 validation on uniqueness on multiple attributes

In Rails 2, I would have written:

validates_uniqueness_of :zipcode, :scope => :recorded_at

In Rails 3:

validates :zipcode, :uniqueness => {:scope => :recorded_at}

For multiple attributes:

validates :zipcode, :uniqueness => {:scope => [:recorded_at, :something_else]}

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

insert echo into the specific html element like div which has an id or class

Have you tried this?:

    $string = '';
    while($row = mysql_fetch_array($result))
    {
    //this will combine all the results into one string
    $string .= '<img src="'.$row['name'].'" />
                <div>'.$row['name'].'</div>
                <div>'.$row['title'].'</div>
                <div>'.$row['description'].'</div>
                <div>'.$row['link'].'</div><br />';

    //or this will add the individual result in an array
 /*
     $yourHtml[] = $row;
*/
    }

then you echo the $tring to the place you want it to be

<div id="place_here">
   <?php echo $string; ?>
   <?php 
     //or
    /*
      echo '<img src="'.$yourHtml[0]['name'].'" />;//change the index, or you just foreach loop it
    */
    ?>
</div>

How to return a specific element of an array?

Make sure return type of you method is same what you want to return. Eg: `

  public int get(int[] r)
  {
     return r[0];
  }

`

Note : return type is int, not int[], so it is able to return int.

In general, prototype can be

public Type get(Type[] array, int index)
{
    return array[index];
}

Hibernate openSession() vs getCurrentSession()

openSession: When you call SessionFactory.openSession, it always creates a new Session object and give it to you.

You need to explicitly flush and close these session objects.

As session objects are not thread safe, you need to create one session object per request in multi-threaded environment and one session per request in web applications too.

getCurrentSession: When you call SessionFactory.getCurrentSession, it will provide you session object which is in hibernate context and managed by hibernate internally. It is bound to transaction scope.

When you call SessionFactory.getCurrentSession, it creates a new Session if it does not exist, otherwise use same session which is in current hibernate context. It automatically flushes and closes session when transaction ends, so you do not need to do it externally.

If you are using hibernate in single-threaded environment , you can use getCurrentSession, as it is faster in performance as compared to creating a new session each time.

You need to add following property to hibernate.cfg.xml to use getCurrentSession method:

<session-factory>
    <!--  Put other elements here -->
    <property name="hibernate.current_session_context_class">
          thread
    </property>
</session-factory>

How to set TextView textStyle such as bold, italic

Programmatically:

You can do programmatically using setTypeface() method:

Below is the code for default Typeface

textView.setTypeface(null, Typeface.NORMAL);      // for Normal Text
textView.setTypeface(null, Typeface.BOLD);        // for Bold only
textView.setTypeface(null, Typeface.ITALIC);      // for Italic
textView.setTypeface(null, Typeface.BOLD_ITALIC); // for Bold and Italic

and if you want to set custom Typeface:

textView.setTypeface(textView.getTypeface(), Typeface.NORMAL);      // for Normal Text
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);        // for Bold only
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);      // for Italic
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC); // for Bold and Italic

XML:

You can set directly in XML file in <TextView /> like this:

android:textStyle="normal"
android:textStyle="normal|bold"
android:textStyle="normal|italic"
android:textStyle="bold"
android:textStyle="bold|italic"

Or you can set your fav font (from assets). for more info see link

Django - limiting query results

Actually I think the LIMIT 10 would be issued to the database so slicing would not occur in Python but in the database.

See limiting-querysets for more information.

Table Naming Dilemma: Singular vs. Plural Names

I always thought that was a dumb convention. I use plural table names.

(I believe the rational behind that policy is that it make it easier for ORM code generators to produce object & collection classes, since it is easier to produce a plural name from a singular name than vice-versa)

Compare every item to every other item in ArrayList

What's the problem with using for loop inside, just like outside?

for (int j = i + 1; j < list.size(); ++j) {
    ...
}

In general, since Java 5, I used iterators only once or twice.

How can I run an external command asynchronously from Python?

There are several answers here but none of them satisfied my below requirements:

  1. I don't want to wait for command to finish or pollute my terminal with subprocess outputs.

  2. I want to run bash script with redirects.

  3. I want to support piping within my bash script (for example find ... | tar ...).

The only combination that satiesfies above requirements is:

subprocess.Popen(['./my_script.sh "arg1" > "redirect/path/to"'],
                 stdout=subprocess.PIPE, 
                 stderr=subprocess.PIPE,
                 shell=True)

PHP: Split string into array, like explode with no delimiter

Try this:

    $str = '546788';
    $char_array = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);

How to redirect to Index from another controller?

try:

public ActionResult Index() {
    return RedirectToAction("actionName");
    // or
    return RedirectToAction("actionName", "controllerName");
    // or
    return RedirectToAction("actionName", "controllerName", new {/* routeValues, for example: */ id = 5 });
}

and in .cshtml view:

@Html.ActionLink("linkText","actionName")

OR:

@Html.ActionLink("linkText","actionName","controllerName")

OR:

@Html.ActionLink("linkText", "actionName", "controllerName", 
    new { /* routeValues forexample: id = 6 or leave blank or use null */ }, 
    new { /* htmlAttributes forexample: @class = "my-class" or leave blank or use null */ })

Notice using null in final expression is not recommended, and is better to use a blank new {} instead of null

View not attached to window manager crash

Based on @erakitin answer, but also compatible for Android versions < API level 17. Sadly Activity.isDestroyed() is only supported since API level 17, so if you're targeting an older API level just like me, you'll have to check it yourself. Haven't got the View not attached to window manager exception after that.

Example code

public class MainActivity extends Activity {
    private TestAsyncTask mAsyncTask;
    private ProgressDialog mProgressDialog;
    private boolean mIsDestroyed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (condition) {
            mAsyncTask = new TestAsyncTask();
            mAsyncTask.execute();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mAsyncTask != null && mAsyncTask.getStatus() != AsyncTask.Status.FINISHED) {
            Toast.makeText(this, "Still loading", Toast.LENGTH_LONG).show();
            return;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mIsDestroyed = true;

        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    public class TestAsyncTask extends AsyncTask<Void, Void, AsyncResult> {    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = ProgressDialog.show(MainActivity.this, "Please wait", "doing stuff..");
        }

        @Override
        protected AsyncResult doInBackground(Void... arg0) {
            // Do long running background stuff
            return null;
        }

        @Override
        protected void onPostExecute(AsyncResult result) {
            // Use MainActivity.this.isDestroyed() when targeting API level 17 or higher
            if (mIsDestroyed)// Activity not there anymore
                return;

            mProgressDialog.dismiss();
            // Handle rest onPostExecute
        }
    }
}

How to get a thread and heap dump of a Java process on Windows that's not running in a console

If you are on server-jre 8 and above you can use this:

jcmd PID GC.heap_dump /tmp/dump

How do I stop a program when an exception is raised in Python?

As far as I know, if an exception is not caught by your script, it will be interrupted.

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;

How to generate a simple popup using jQuery

Here is a very simple popup:

<!DOCTYPE html>
<html>
    <head>
        <style>
            #modal {
                position:absolute;
                background:gray;
                padding:8px;
            }

            #content {
                background:white;
                padding:20px;
            }

            #close {
                position:absolute;
                background:url(close.png);
                width:24px;
                height:27px;
                top:-7px;
                right:-7px;
            }
        </style>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script>
            var modal = (function(){
                // Generate the HTML and add it to the document
                $modal = $('<div id="modal"></div>');
                $content = $('<div id="content"></div>');
                $close = $('<a id="close" href="#"></a>');

                $modal.hide();
                $modal.append($content, $close);

                $(document).ready(function(){
                    $('body').append($modal);                       
                });

                $close.click(function(e){
                    e.preventDefault();
                    $modal.hide();
                    $content.empty();
                });
                // Open the modal
                return function (content) {
                    $content.html(content);
                    // Center the modal in the viewport
                    $modal.css({
                        top: ($(window).height() - $modal.outerHeight()) / 2, 
                        left: ($(window).width() - $modal.outerWidth()) / 2
                    });
                    $modal.show();
                };
            }());

            // Wait until the DOM has loaded before querying the document
            $(document).ready(function(){
                $('a#popup').click(function(e){
                    modal("<p>This is popup's content.</p>");
                    e.preventDefault();
                });
            });
        </script>
    </head>
    <body>
        <a id='popup' href='#'>Simple popup</a>
    </body>
</html>

More flexible solution can be found in this tutorial: http://www.jacklmoore.com/notes/jquery-modal-tutorial/ Here's close.png for the sample.

SQL Query - Concatenating Results into One String

If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF trick:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STUFF( (SELECT ',' + CodeName 
                             FROM dbo.AccountCodes 
                             ORDER BY Sort
                             FOR XML PATH('')), 
                            1, 1, '')

The FOR XML PATH('') basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3 etc.) and the STUFF puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.

UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <, > or &, then my current solution will in fact encode those into &lt;, &gt;, and &amp;.

If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.

Android – Listen For Incoming SMS Messages

Note that on some devices your code wont work without android:priority="1000" in intent filter:

<receiver android:name=".listener.SmsListener">
    <intent-filter android:priority="1000">
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

And here is some optimizations:

public class SmsListener extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(intent.getAction())) {
            for (SmsMessage smsMessage : Telephony.Sms.Intents.getMessagesFromIntent(intent)) {
                String messageBody = smsMessage.getMessageBody();
            }
        }
    }
}

Note:
The value must be an integer, such as "100". Higher numbers have a higher priority. The default value is 0. The value must be greater than -1000 and less than 1000.

Here's a link.

Hash function that produces short hashes?

If you don't need an algorithm that's strong against intentional modification, I've found an algorithm called adler32 that produces pretty short (~8 character) results. Choose it from the dropdown here to try it out:

http://www.sha1-online.com/

How to generate unique id in MySQL?

 <?php
    $hostname_conn = "localhost";
    $database_conn = "user_id";
    $username_conn = "root";
    $password_conn = "";
     $conn = mysql_pconnect($hostname_conn, $username_conn,   $password_conn) or trigger_error(mysql_error(),E_USER_ERROR); 
   mysql_select_db($database_conn,$conn);
   // run an endless loop      
    while(1) {       
    $randomNumber = rand(1, 999999);// generate unique random number               
    $query = "SELECT * FROM tbl_rand WHERE the_number='".mysql_real_escape_string ($randomNumber)."'";  // check if it exists in database   
    $res =mysql_query($query,$conn);       
    $rowCount = mysql_num_rows($res);
     // if not found in the db (it is unique), then insert the unique number into data_base and break out of the loop
    if($rowCount < 1) {
    $con = mysql_connect ("localhost","root");      
    mysql_select_db("user_id", $con);       
    $sql = "insert into tbl_rand(the_number) values('".$randomNumber."')";      
    mysql_query ($sql,$con);        
    mysql_close ($con);
    break;
    }   
}
  echo "inserted unique number into Data_base. use it as ID";
   ?>

Shell script to delete directories older than n days

I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.

Finally stumbled on tmpreaper and it has been worked pretty well for us so far.

tmpreaper -t 5d ~/Downloads


tmpreaper  --protect '*.c' -t 5h ~/my_prg

Original Source link

Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting

disabling spring security in spring boot app

Use security.ignored property:

security.ignored=/**

security.basic.enable: false will just disable some part of the security auto-configurations but your WebSecurityConfig still will be registered.

There is a default security password generated at startup

Try to Autowired the AuthenticationManagerBuilder:

@Override
@Autowired
protected void configure(AuthenticationManagerBuilder auth) throws Exception { ... }

Multiple Inheritance in C#

You could have one abstract base class that implements both IFirst and ISecond, and then inherit from just that base.

What does "@" mean in Windows batch scripts

It means not to output the respective command. Compare the following two batch files:

@echo foo

and

echo foo

The former has only foo as output while the latter prints

H:\Stuff>echo foo 
foo

(here, at least). As can be seen the command that is run is visible, too.

echo off will turn this off for the complete batch file. However, the echo off call itself would still be visible. Which is why you see @echo off in the beginning of batch files. Turn off command echoing and don't echo the command turning it off.

Removing that line (or commenting it out) is often a helpful debugging tool in more complex batch files as you can see what is run prior to an error message.

Example: Communication between Activity and Service using Messaging

Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    _nManager.notify(NOTIFICATION_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (_timer != null) {_timer.cancel();}
    _counter=0;
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;
}

Checked myself, everything works like a charm (activity and service names may differ from original).

Linq select object from list depending on objects attribute

Of course!

Use FirstOrDefault() to select the first object which matches the condition:

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Otherwise use Where() to select a subset of your list:

var answers = Answers.Where(a => a.Correct);

"Integer number too large" error message for 600851475143

You need to use a long literal:

obj.function(600851475143l);  // note the "l" at the end

But I would expect that function to run out of memory (or time) ...

Simple PowerShell LastWriteTime compare

Use

ls | % {(get-date) - $_.LastWriteTime }

It can work to retrieve the diff. You can replace ls with a single file.

Nested or Inner Class in PHP

As per Xenon's comment to Anil Özselgin's answer, anonymous classes have been implemented in PHP 7.0, which is as close to nested classes as you'll get right now. Here are the relevant RFCs:

Nested Classes (status: withdrawn)

Anonymous Classes (status: implemented in PHP 7.0)

An example to the original post, this is what your code would look like:

<?php
    public class User {
        public $userid;
        public $username;
        private $password;

        public $profile;
        public $history;

        public function __construct() {
            $this->profile = new class {
                // Some code here for user profile
            }

            $this->history = new class {
                // Some code here for user history
            }
        }
    }
?>

This, though, comes with a very nasty caveat. If you use an IDE such as PHPStorm or NetBeans, and then add a method like this to the User class:

public function foo() {
  $this->profile->...
}

...bye bye auto-completion. This is the case even if you code to interfaces (the I in SOLID), using a pattern like this:

<?php
    public class User {
        public $profile;

        public function __construct() {
            $this->profile = new class implements UserProfileInterface {
                // Some code here for user profile
            }
        }
    }
?>

Unless your only calls to $this->profile are from the __construct() method (or whatever method $this->profile is defined in) then you won't get any sort of type hinting. Your property is essentially "hidden" to your IDE, making life very hard if you rely on your IDE for auto-completion, code smell sniffing, and refactoring.

HTML5 form required attribute. Set custom validation message?

Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/> field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.

I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:

Hello.js

import React, { Component } from "react";
import SelectValid from "./SelectValid";

export default class Hello extends Component {
  render() {
    return (
      <form>
        <SelectValid placeholder="this one is optional" />
        <SelectValid placeholder="this one is required" required />
        <input
          required
          defaultValue="foo"
          onChange={e => e.target.setCustomValidity("")}
          onInvalid={e => e.target.setCustomValidity("foo")}
        />
        <button>button</button>
      </form>
    );
  }
}

SelectValid.js

import React, { Component } from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";

export default class SelectValid extends Component {
  render() {
    this.required = !this.props.required
      ? false
      : this.state && this.state.value ? false : true;
    let inputProps = undefined;
    let onInputChange = undefined;
    if (this.props.required) {
      inputProps = {
        onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
      };
      onInputChange = value => {
        this.selectComponent.input.input.setCustomValidity(
          value
            ? ""
            : this.required
              ? "foo"
              : this.selectComponent.props.value ? "" : "foo"
        );
        return value;
      };
    }
    return (
      <Select
        onChange={value => {
          this.required = !this.props.required ? false : value ? false : true;
          let state = this && this.state ? this.state : { value: null };
          state.value = value;
          this.setState(state);
          if (this.props.onChange) {
            this.props.onChange();
          }
        }}
        value={this && this.state ? this.state.value : null}
        options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
        placeholder={this.props.placeholder}
        required={this.required}
        clearable
        searchable
        inputProps={inputProps}
        ref={input => (this.selectComponent = input)}
        onInputChange={onInputChange}
      />
    );
  }
}

ERROR: Sonar server 'http://localhost:9000' can not be reached

For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.

For example, I needed to add the following line under the 'properties' element:

<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>

Where the url points to our internal sonar deployment.

Error:java: javacTask: source release 8 requires target release 1.8

I fixed it by modify my POM file. Notice the last comment under the highest voted answer.

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF-8</encoding>
        </configuration>
</plugin>

The source must matches the target.

How to detect if a browser is Chrome using jQuery?

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

Nginx no-www to www and www to no-www

Redirect non-www to www

For Single Domain :

server {
        server_name example.com;
        return 301 $scheme://www.example.com$request_uri;
}

For All Domains :

server {
        server_name "~^(?!www\.).*" ;
        return 301 $scheme://www.$host$request_uri;
}

Redirect www to non-www For Single Domain:

server {
        server_name www.example.com;
        return 301 $scheme://example.com$request_uri;
}

For All Domains :

server {
         server_name "~^www\.(.*)$" ;
         return 301 $scheme://$1$request_uri ;
}

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Please try this

 useEffect(() => {
        (async () => {
          const products = await api.index()
          setFilteredProducts(products)
          setProducts(products)
        })()
      }, [])

How to check size of a file using Bash?

For getting the file size in both Linux and Mac OS X (and presumably other BSDs), there are not many options, and most of the ones suggested here will only work on one system.

Given f=/path/to/your/file,

what does work in both Linux and Mac's Bash:

size=$( perl -e 'print -s shift' "$f" )

or

size=$( wc -c "$f" | awk '{print $1}' )

The other answers work fine in Linux, but not in Mac:

  • du doesn't have a -b option in Mac, and the BLOCKSIZE=1 trick doesn't work ("minimum blocksize is 512", which leads to a wrong result)

  • cut -d' ' -f1 doesn't work because on Mac, the number may be right-aligned, padded with spaces in front.

So if you need something flexible, it's either perl's -s operator , or wc -c piped to awk '{print $1}' (awk will ignore the leading white space).

And of course, regarding the rest of your original question, use the -lt (or -gt) operator :

if [ $size -lt $your_wanted_size ]; then etc.

Simple pagination in javascript

i am assuming you will display 10 data in every page

HTML:-

<!DOCTYPE html>
<html>
<head>
    <title>pagination</title>
    <link rel="stylesheet"  href="pathofcssfile.css">
</head>
<body>
    <div>
        <table id="user"></table>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <ul>
    <li value="1">1</li>
    <li value="2">2</li>
    <li value="3">3</li>
    <li value="4">4</li>
    <li value="5">5</li>
    <li value="6">6</li>
    <li value="7">7</li>
    <li value="8">8</li>
    <li value="9">9</li>
    <li value="10">10</li>

    </ul>

    <script src="pathnameofjsfile.js" type="text/javascript"></script>
</body>
</html>

JS:-

var xhr = new XMLHttpRequest();
xhr.open('GET',"https://jsonplaceholder.typicode.com/albums",true);
xhr.send();

var udata;

xhr.onload = function() 
{
    if(this.status == 200) 
    {
        var userdata = JSON.parse(this.responseText);
        console.log(userdata);
        udata = userdata;
        data(1);
    }
}

$("li").click(function ()
{       
var a = $(this).attr("value");
console.log("value li "+ a);
data(a);
});

function data(a)
{  
    var output = "";
    for(i=((a-1)*10);i<(a*10);i++)
    {
        output +='<tr>'+
                 '<td>'+ udata[i].userId + '</td>'+
                 '<td>'+ udata[i].id + '</td>'+
                 '<td>'+ udata[i].title + '</td>'+ '<br>'
                 '</tr>';
    }
    document.getElementById('user').innerHTML = output;
}

CSS:-

ul{
display: flex;
list-style-type:none;
padding: 20px;
}

li{
padding: 20px;
}

td,tr{
    padding: 10px;
}

How to output to the console and file?

Create an output file and custom function:

outputFile = open('outputfile.log', 'w')

def printing(text):
    print(text)
    if outputFile:
        outputFile.write(str(text))

Then instead of print(text) in your code, call printing function.

printing("START")
printing(datetime.datetime.now())
printing("COMPLETE")
printing(datetime.datetime.now())

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}
}

npm run build OR npm run-script build


{
  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"
  }
}

npm start


NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

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

Having been greatly inspired by Postman for Chrome, I decided to write something similar for Firefox.

REST Easy* is a restartless Firefox add-on that aims to provide as much control as possible over requests. The add-on is still in an experimental state (it hasn't even been reviewed by Mozilla yet) but development is progressing nicely.

The project is open source, so if anyone feels compelled to help with development, that would be awesome: https://github.com/nathan-osman/Rest-Easy

* the add-on available from http://addons.mozilla.org will always be slightly behind the code available on GitHub

Calling UserForm_Initialize() in a Module

IMHO the method UserForm_Initialize should remain private bacause it is event handler for Initialize event of the UserForm.

This event handler is called when new instance of the UserForm is created. In this even handler u can initialize the private members of UserForm1 class.

Example:

Standard module code:

Option Explicit

Public Sub Main()
  Dim myUserForm As UserForm1

  Set myUserForm = New UserForm1
  myUserForm.Show

End Sub

User form code:

Option Explicit

Private m_initializationDate As Date

Private Sub UserForm_Initialize()
  m_initializationDate = VBA.DateTime.Date
  MsgBox "Hi from UserForm_Initialize event handler.", vbInformation
End Sub

SQL Server Installation - What is the Installation Media Folder?

If you are using an executable,

  • just run the executable (for example: "en_sql_server_2012_express_edition_with_advanced_services_x64.exe")
  • Navigate to the "options" tab
  • Copy the "Installation Media Root Directory" (should look something like the below snipping)
  • Paste it into the open "Browse for SQL server Installation Media" window

enter image description here

Save yourself the hastle of renaming and unzipping etc.!

How can I generate Unix timestamps?

in Ruby:

>> Time.now.to_i
=> 1248933648

How to connect to a remote Windows machine to execute commands using python?

You can use pywinrm library instead which is cross-platform compatible.

Here is a simple code example:

#!/usr/bin/env python
import winrm

# Create winrm connection.
sess = winrm.Session('https://10.0.0.1', auth=('username', 'password'), transport='kerberos')
result = sess.run_cmd('ipconfig', ['/all'])

Install library via: pip install pywinrm requests_kerberos.


Here is another example from this page to run Powershell script on a remote host:

import winrm

ps_script = """$strComputer = $Host
Clear
$RAM = WmiObject Win32_ComputerSystem
$MB = 1048576

"Installed Memory: " + [int]($RAM.TotalPhysicalMemory /$MB) + " MB" """

s = winrm.Session('windows-host.example.com', auth=('john.smith', 'secret'))
r = s.run_ps(ps_script)
>>> r.status_code
0
>>> r.std_out
Installed Memory: 3840 MB

>>> r.std_err

Reset IntelliJ UI to Default

All above answers are correct, but you loose configuration settings.

But if your IDE's only themes or fonts are changed or some UI related issues and you want to restore to default theme, then just delete

${user.home}/.IntelliJIdea13/config/options/options.xml

file while IDE is not running, then after next restart IDE's theme will gets reset to default.

How do I put a clear button inside my HTML text input box like the iPhone does?

Maybe this simple solution can help:

_x000D_
_x000D_
<input type="text" id="myInput" value="No War"/><button onclick="document.getElementById('myInput').value = ''" title="Clear">X</button></input>
_x000D_
_x000D_
_x000D_

"Actual or formal argument lists differs in length"

The default constructor has no arguments. You need to specify a constructor:

    public Friends( String firstName, String age) { ... }

Using ListView : How to add a header view?

You simply can't use View as a Header of ListView.

Because the view which is being passed in has to be inflated.

Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.

EDIT:

Look at this tutorial Android ListView and ListActivity - Tutorial .

EDIT 2: This link is broken Android ListActivity with a header or footer

Difference between ref and out parameters in .NET

  • A ref variable needs to be initialized before passing it in.
  • An out variable needs to be set in your function implementation
  • out parameters can be thought of as additional return variables (not input)
  • ref parameters can be thought of as both input and output variables.

How to determine when Fragment becomes visible in ViewPager

We have a special case with MVP where the fragment needs to notify the presenter that the view has become visible, and the presenter is injected by Dagger in fragment.onAttach().

setUserVisibleHint() is not enough, we've detected 3 different cases that needed to be addressed (onAttach() is mentioned so that you know when the presenter is available):

  1. Fragment has just been created. The system makes the following calls:

    setUserVisibleHint() // before fragment's lifecycle calls, so presenter is null
    onAttach()
    ...
    onResume()
    
  2. Fragment already created and home button is pressed. When restoring the app to foreground, this is called:

    onResume()
    
  3. Orientation change:

    onAttach() // presenter available
    onResume()
    setUserVisibleHint()
    

We only want the visibility hint to get to the presenter once, so this is how we do it:

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_list, container, false);
    setHasOptionsMenu(true);

    if (savedInstanceState != null) {
        lastOrientation = savedInstanceState.getInt(STATE_LAST_ORIENTATION,
              getResources().getConfiguration().orientation);
    } else {
        lastOrientation = getResources().getConfiguration().orientation;
    }

    return root;
}

@Override
public void onResume() {
    super.onResume();
    presenter.onResume();

    int orientation = getResources().getConfiguration().orientation;
    if (orientation == lastOrientation) {
        if (getUserVisibleHint()) {
            presenter.onViewBecomesVisible();
        }
    }
    lastOrientation = orientation;
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (presenter != null && isResumed() && isVisibleToUser) {
        presenter.onViewBecomesVisible();
    }
}

@Override public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt(STATE_LAST_ORIENTATION, lastOrientation);
}

HTML Input="file" Accept Attribute File Type (CSV)

Dom this attribute is very old and not accepted in modern browsers as far as I know, But here is an alternative to it, Try this

<script type="text/javascript" language="javascript">
function checkfile(sender) {
    var validExts = new Array(".xlsx", ".xls", ".csv");
    var fileExt = sender.value;
    fileExt = fileExt.substring(fileExt.lastIndexOf('.'));
    if (validExts.indexOf(fileExt) < 0) {
      alert("Invalid file selected, valid files are of " +
               validExts.toString() + " types.");
      return false;
    }
    else return true;
}
</script>

<input type="file" id="file" onchange="checkfile(this);" />

I guess it'll help you of course you can change this script according to your needs.

How can I use grep to show just filenames on Linux?

From the grep(1) man page:

  -l, --files-with-matches
          Suppress  normal  output;  instead  print the name of each input
          file from which output would normally have  been  printed.   The
          scanning  will  stop  on  the  first match.  (-l is specified by
          POSIX.)

Set JavaScript variable = null, or leave undefined?

I declare them as undefined when I don't assign a value because they are undefined after all.

Can I have two JavaScript onclick events in one element?

The HTML

<a href="#" id="btn">click</a>

And the javascript

// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
    if (window.addEventListener) {
        return function(target, type, listener){
            target.addEventListener(type, listener, false);
        };
    }
    else {
        return function(object, sEvent, fpNotify){
            object.attachEvent("on" + sEvent, fpNotify);
        };
    }
}());

// find the element
var el = document.getElementById("btn");

// add the first listener
on(el, "click", function(){
    alert("foo");
});

// add the second listener
on(el, "click", function(){
    alert("bar");
});

This will alert both 'foo' and 'bar' when clicked.

How to check is Apache2 is stopped in Ubuntu?

In the command line type service apache2 status then hit enter. The result should say:

Apache2 is running (pid xxxx)

In Go's http package, how do I get the query string on a POST request?

There are two ways of getting query params:

  1. Using reqeust.URL.Query()
  2. Using request.Form

In second case one has to be careful as body parameters will take precedence over query parameters. A full description about getting query params can be found here

https://golangbyexample.com/net-http-package-get-query-params-golang

How can I get Eclipse to show .* files?

1. From Package Explorer open the Filters... dialog:

enter image description here

2. Then uncheck .* resources option:

enter image description here

How to convert binary string value to decimal

According to this : 1 we can write this help function :

    public static int convertBinaryToDecimal(String str) {
        int result = 0;
        for (int i = 0; i < str.length(); i++) {
            int value = Character.getNumericValue(str.charAt(i));
            result = result * 2 + value;
        }
        return result;
    }

Using PropertyInfo to find out the property type

I just stumbled upon this great post. If you are just checking whether the data is of string type then maybe we can skip the loop and use this struct (in my humble opinion)

public static bool IsStringType(object data)
    {
        return (data.GetType().GetProperties().Where(x => x.PropertyType == typeof(string)).FirstOrDefault() != null);
    }

Get record counts for all tables in MySQL database

 SELECT TABLE_NAME,SUM(TABLE_ROWS) 
 FROM INFORMATION_SCHEMA.TABLES 
 WHERE TABLE_SCHEMA = 'your_db' 
 GROUP BY TABLE_NAME;

That's all you need.

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

You can also rescale using sklearn. The advantages are that you can adjust normalize the standard deviation, in addition to mean-centering the data, and that you can do this on either axis, by features, or by records.

from sklearn.preprocessing import scale
X = scale( X, axis=0, with_mean=True, with_std=True, copy=True )

The keyword arguments axis, with_mean, with_std are self explanatory, and are shown in their default state. The argument copy performs the operation in-place if it is set to False. Documentation here.

Redirecting to a certain route based on condition

Here's how I did it, in case it helps anyone:

In the config, I set a publicAccess attribute on the few routes that I want open to the public (like login or register):

$routeProvider
    .when('/', {
        templateUrl: 'views/home.html',
        controller: 'HomeCtrl'
    })
    .when('/login', {
        templateUrl: 'views/login.html',
        controller: 'LoginCtrl',
        publicAccess: true
    })

then in a run block, I set a listener on the $routeChangeStart event that redirects to '/login' unless the user has access or the route is publicly accessible:

angular.module('myModule').run(function($rootScope, $location, user, $route) {

    var routesOpenToPublic = [];
    angular.forEach($route.routes, function(route, path) {
        // push route onto routesOpenToPublic if it has a truthy publicAccess value
        route.publicAccess && (routesOpenToPublic.push(path));
    });

    $rootScope.$on('$routeChangeStart', function(event, nextLoc, currentLoc) {
        var closedToPublic = (-1 === routesOpenToPublic.indexOf($location.path()));
        if(closedToPublic && !user.isLoggedIn()) {
            $location.path('/login');
        }
    });
})

You could obviously change the condition from isLoggedIn to anything else... just showing another way to do it.

PHP is not recognized as an internal or external command in command prompt

Is your path correctly configured?

In Windows, you can do that as described here:

http://www.computerhope.com/issues/ch000549.htm

Setting a WebRequest's body data

Update

See my other SO answer.


Original

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

Spring: How to get parameters from POST body?

You can try using @RequestBodyParam

@RequestMapping(value = "/saveData", headers="Content-Type=application/json", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Boolean> saveData(@RequestBodyParam String source,@RequestBodyParam JsonDto json) throws MyException {
    ...
}

https://github.com/LambdaExpression/RequestBodyParam

The tilde operator in Python

Besides being a bitwise complement operator, ~ can also help revert a boolean value, though it is not the conventional bool type here, rather you should use numpy.bool_.


This is explained in,

import numpy as np
assert ~np.True_ == np.False_

Reversing logical value can be useful sometimes, e.g., below ~ operator is used to cleanse your dataset and return you a column without NaN.

from numpy import NaN
import pandas as pd

matrix = pd.DataFrame([1,2,3,4,NaN], columns=['Number'], dtype='float64')
# Remove NaN in column 'Number'
matrix['Number'][~matrix['Number'].isnull()]

Create a temporary table in MySQL with an index from a select

Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...

CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;

CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid), 
INDEX(tmpid))  
SELECT * FROM tmpLivecheck;

... solved my problem.

Greetings...

Saving a select count(*) value to an integer (SQL Server)

If @myInt is zero it means no rows in the table: it would be NULL if never set at all.

COUNT will always return a row, even for no rows in a table.

Edit, Apr 2012: the rules for this are described in my answer here:Does COUNT(*) always return a result?

Your count/assign is correct but could be either way:

select @myInt = COUNT(*) from myTable
set @myInt = (select COUNT(*) from myTable)

However, if you are just looking for the existence of rows, (NOT) EXISTS is more efficient:

IF NOT EXISTS (SELECT * FROM myTable)

Get month and year from date cells Excel

You could right click on those cells, go to format, select custom, then type mm yyyy.

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

In My case I had to Upgrade the SQL Server since evaluation licence had been expired.

enter image description here

the MySQL service on local computer started and then stopped

Such a problem can very often come due to configuration errors.

Vivek Sethi mentioned 20th December 2012 that it is possible to get logging in the console by running the following command:

C:\Windows\system32>"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.5\my.ini" --standalone --console

Right-clicking on my service in Windows 10, I recognized the --defaults-file= parameter, and with console logging I was able to see what was wrong in my configuration. In my case the path to datadir= and secure-file-priv= was wrong. I hope others can be empowered as well by being able to see logging details in the console. Good luck!

JavaScript set object key by variable

In ES6, you can do like this.

var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var key = "name";_x000D_
    var person = {[key]:"John"};_x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Its called Computed Property Names, its implemented using bracket notation( square brackets) []

Example: { [variableName] : someValue }

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.

For ES5, try something like this

var yourObject = {};

yourObject[yourKey] = "yourValue";

console.log(yourObject );

example:

var person = {};
var key = "name";

person[key] /* this is same as person.name */ = "John";

console.log(person); // should print  Object { name="John"}

_x000D_
_x000D_
    var person = {};_x000D_
    var key = "name";_x000D_
    _x000D_
    person[key] /* this is same as person.name */ = "John";_x000D_
    _x000D_
    console.log(person); // should print  Object { name="John"}
_x000D_
_x000D_
_x000D_

Gmail: 530 5.5.1 Authentication Required. Learn more at

Get to your Gmail account's security settings and set permissions for "Less secure apps" to Enabled. Worked for me.

How to do SQL Like % in Linq?

I'm assuming you're using Linq-to-SQL* (see note below). If so, use string.Contains, string.StartsWith, and string.EndsWith to generate SQL that use the SQL LIKE operator.

from o in dc.Organization
join oh in dc.OrganizationsHierarchy on o.Id equals oh.OrganizationsId
where oh.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

or

from o in dc.Organization
where o.OrganizationsHierarchy.Hierarchy.Contains(@"/12/")
select new { o.Id, o.Name }

Note: * = if you are using the ADO.Net Entity Framework (EF / L2E) in .net 3.5, be aware that it will not do the same translation as Linq-to-SQL. Although L2S does a proper translation, L2E v1 (3.5) will translate into a t-sql expression that will force a full table scan on the table you're querying unless there is another better discriminator in your where clause or join filters.
Update: This is fixed in EF/L2E v4 (.net 4.0), so it will generate a SQL LIKE just like L2S does.

When should I write the keyword 'inline' for a function/method?

In reality, pretty much never. All you're doing is suggesting that the compiler make a given function inline (e.g., replace all calls to this function /w its body). There are no guarantees, of course: the compiler may ignore the directive.

The compiler will generally do a good job of detecting + optimizing things like this.

spark submit add multiple jars in classpath

Just use the --jars parameter. Spark will share those jars (comma-separated) with the executors.

How to change the default encoding to UTF-8 for Apache?

Just a hint if you have long filenames in utf-8: by default they will be shortened to 20 bytes, so it may happen that the last character might be "cut in half" and therefore unrecognized properly. Then you may want to set the following:

IndexOptions Charset=UTF-8 NameWidth=*

NameWidth setting will prevent shortening your file names, making them properly displayed and readable.

As other users already mentioned, this should be added either in httpd.conf or apache2.conf (if you do have admin rights) or in .htaccess (if you don't).

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

Just add this to your local.properties file of your project:

BUILD_DIR=C\:\\Tmp

(The error in Windows is due a long path, so I gave the path to one temporary folder.)

How do I set up Eclipse/EGit with GitHub?

Make sure your refs for pushing are correct. This tutorial is pretty great, right from the documentation:

http://wiki.eclipse.org/EGit/User_Guide#GitHub_Tutorial

You can clone directly from GitHub, you choose where you clone that repository. And when you import that repository to Eclipse, you choose what refspec to push into upstream.

Click on the Git Repository workspace view, and make sure your remote refs are valid. Make sure you are pointing to the right local branch and pushing to the correct remote branch.

Sum the digits of a number

Both lines you posted are fine, but you can do it purely in integers, and it will be the most efficient:

def sum_digits(n):
    s = 0
    while n:
        s += n % 10
        n //= 10
    return s

or with divmod:

def sum_digits2(n):
    s = 0
    while n:
        n, remainder = divmod(n, 10)
        s += remainder
    return s

Even faster is the version without augmented assignments:

def sum_digits3(n):
   r = 0
   while n:
       r, n = r + n % 10, n // 10
   return r

> %timeit sum_digits(n)
1000000 loops, best of 3: 574 ns per loop

> %timeit sum_digits2(n)
1000000 loops, best of 3: 716 ns per loop

> %timeit sum_digits3(n)
1000000 loops, best of 3: 479 ns per loop

> %timeit sum(map(int, str(n)))
1000000 loops, best of 3: 1.42 us per loop

> %timeit sum([int(digit) for digit in str(n)])
100000 loops, best of 3: 1.52 us per loop

> %timeit sum(int(digit) for digit in str(n))
100000 loops, best of 3: 2.04 us per loop

How to delete a workspace in Perforce (using p4v)?

  1. Ctrl + 5

view workspace in p4v

  1. Delete the relevant workspace

enter image description here

What is the command to exit a Console application in C#?

You can use Environment.Exit(0); and Application.Exit

Environment.Exit(0) is cleaner.

Python Socket Multiple Clients

This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.

#!usr/bin/python
from thread import *
import socket
import sys

def clientthread(conn):
    buffer=""
    while True:
        data = conn.recv(8192)
        buffer+=data
        print buffer
    #conn.sendall(reply)
    conn.close()

def main():
    try:
        host = '192.168.1.3'
        port = 6666
        tot_socket = 26
        list_sock = []
        for i in range(tot_socket):
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
            s.bind((host, port+i))
            s.listen(10)
            list_sock.append(s)
            print "[*] Server listening on %s %d" %(host, (port+i))

        while 1:
            for j in range(len(list_sock)):
                conn, addr = list_sock[j].accept()
                print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
                start_new_thread(clientthread ,(conn,))
        s.close()

    except KeyboardInterrupt as msg:
        sys.exit(0)


if __name__ == "__main__":
    main()

Split string in JavaScript and detect line break

Here's the final code I [OP] used. Probably not best practice, but it worked.

function wrapText(context, text, x, y, maxWidth, lineHeight) {

    var breaks = text.split('\n');
    var newLines = "";
    for(var i = 0; i < breaks.length; i ++){
      newLines = newLines + breaks[i] + ' breakLine ';
    }

    var words = newLines.split(' ');
    var line = '';
    console.log(words);
    for(var n = 0; n < words.length; n++) {
      if(words[n] != 'breakLine'){
        var testLine = line + words[n] + ' ';
        var metrics = context.measureText(testLine);
        var testWidth = metrics.width;
        if (testWidth > maxWidth && n > 0) {
          context.fillText(line, x, y);
          line = words[n] + ' ';
          y += lineHeight;
        }
        else {
          line = testLine;
        }
      }else{
          context.fillText(line, x, y);
          line = '';
          y += lineHeight;
      }
    }
    context.fillText(line, x, y);
  }

Is there a minlength validation attribute in HTML5?

I used maxlength and minlength with or without required and it worked for me very well for HTML5.

_x000D_
_x000D_
<input id="passcode" type="password" minlength="8" maxlength="10">
_x000D_
_x000D_
_x000D_

`

When should I use semicolons in SQL Server?

It appears that semicolons should not be used in conjunction with cursor operations: OPEN, FETCH, CLOSE and DEALLOCATE. I just wasted a couple of hours with this. I had a close look at the BOL and noticed that [;] is not shown in the syntax for these cursor statements!!

So I had:

OPEN mycursor;

and this gave me error 16916.

But:

OPEN mycursor

worked.

<DIV> inside link (<a href="">) tag

Nesting of 'a' will not be possible. However if you badly want to keep the structure and still make it work like the way you want, then override the anchor tag click in javascript /jquery .

so you can have 2 event listeners for the two and control them accordingly.

Use multiple custom fonts using @font-face?

If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.

The easiest way I found to find this out was to install the font and see what display name is given.

For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.

Hope that helps.

Extracting substrings in Go

To get substring

  1. find position of "sp"

  2. cut string with array-logical

https://play.golang.org/p/0Redd_qiZM

How to set JFrame to appear centered, regardless of monitor resolution?

You can use this method, which allows the JFrame to be centered and full screen at the same time.

yourframe.setExtendedState(JFrame.MAXIMIZED_BOTH);

How to check a boolean condition in EL?

You can have a look at the EL (expression language) description here.

Both your code are correct, but I prefer the second one, as comparing a boolean to true or false is redundant.

For better readibility, you can also use the not operator:

<c:if test="${not theBooleanVariable}">It's false!</c:if>

How can I make the Android emulator show the soft keyboard?

To be more precise, with Lollipop these are the steps I followed to show soft keyboard:

  1. Settings > Language & Input;
  2. under "Keyboard & input methods" label, select "Current Keyboard";
  3. A Dialog named "Change Keyboard" appears, switch ON "Hardware", then select "Choose keyboards";
  4. another Dialog appears, switch ON the "Sample Soft Keyboard". Here you get an alert about the possibility that keyboard will store everything you write, also passwords. Give OK;
  5. Repeat above steps in order to show "Change Keyboard" Dialog again, here the new option "Sample Soft Keyboard" is available and you can select it.

NOTE: after that, you might experience problems in running you app (as I had). Simply restart the emulator.

Access mysql remote database from command line

edit my.cnf file:

vi /etc/my.cnf:

make sure that:

bind-address=YOUR-SERVER-IP

and if you have the line:

skip-networking

make sure to comment it:

#skip-networking

don't forget to restart:

/etc/init.d/mysqld restart

TSQL Pivot without aggregate function

This should work:

select * from (select [CustomerID]  ,[Demographic] ,[Data]
from [dbo].[pivot]
) as Ter

pivot (max(Data) for  Demographic in (FirstName, MiddleName, LastName, [Date]))as bro

How do I get a list of folders and sub folders without the files?

I don't have enough reputation to comment on any answer. In one of the comments, someone has asked how to ignore the hidden folders in the list. Below is how you can do this.

dir /b /AD-H

What are the rules for calling the superclass constructor?

If you simply want to pass all constructor arguments to the base-class (=parent), here is a minimal example.

This uses templates to forward every constructor call with 1, 2 or 3 arguments to the parent class std::string.

Code

Live-Version

#include <iostream>
#include <string>

class ChildString: public std::string
{
    public:
        template<typename... Args>
        ChildString(Args... args): std::string(args...)
        {
            std::cout 
                << "\tConstructor call ChildString(nArgs="
                << sizeof...(Args) << "): " << *this
                << std::endl;
        }

};

int main()
{
    std::cout << "Check out:" << std::endl;
    std::cout << "\thttp://www.cplusplus.com/reference/string/string/string/" << std::endl;
    std::cout << "for available string constructors" << std::endl;

    std::cout << std::endl;
    std::cout << "Initialization:" << std::endl;
    ChildString cs1 ("copy (2)");

    char char_arr[] = "from c-string (4)";
    ChildString cs2 (char_arr);

    std::string str = "substring (3)";
    ChildString cs3 (str, 0, str.length());

    std::cout << std::endl;
    std::cout << "Usage:" << std::endl;
    std::cout << "\tcs1: " << cs1 << std::endl;
    std::cout << "\tcs2: " << cs2 << std::endl;
    std::cout << "\tcs3: " << cs3 << std::endl;

    return 0;
}

Output

Check out:
    http://www.cplusplus.com/reference/string/string/string/
for available string constructors

Initialization:
    Constructor call ChildString(nArgs=1): copy (2)
    Constructor call ChildString(nArgs=1): from c-string (4)
    Constructor call ChildString(nArgs=3): substring (3)

Usage:
    cs1: copy (2)
    cs2: from c-string (4)
    cs3: substring (3)

Update: Using Variadic Templates

To generalize to n arguments and simplify

        template <class C>
        ChildString(C arg): std::string(arg)
        {
            std::cout << "\tConstructor call ChildString(C arg): " << *this << std::endl;
        }
        template <class C1, class C2>
        ChildString(C1 arg1, C2 arg2): std::string(arg1, arg2)
        {
            std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
        }
        template <class C1, class C2, class C3>
        ChildString(C1 arg1, C2 arg2, C3 arg3): std::string(arg1, arg2, arg3)
        {
            std::cout << "\tConstructor call ChildString(C1 arg1, C2 arg2, C3 arg3): " << *this << std::endl;
        }

to

template<typename... Args>
        ChildString(Args... args): std::string(args...)
        {
            std::cout 
                << "\tConstructor call ChildString(nArgs="
                << sizeof...(Args) << "): " << *this
                << std::endl;
        }

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

Maximum size of an Array in Javascript

The maximum length until "it gets sluggish" is totally dependent on your target machine and your actual code, so you'll need to test on that (those) platform(s) to see what is acceptable.

However, the maximum length of an array according to the ECMA-262 5th Edition specification is bound by an unsigned 32-bit integer due to the ToUint32 abstract operation, so the longest possible array could have 232-1 = 4,294,967,295 = 4.29 billion elements.

How to dismiss ViewController in Swift?

In Swift 3.0 to 4.0 it's as easy as typing this into your function:

self.dismiss(animated: true, completion: nil)

Or if you're in a navigation controller you can "pop" it:

self.navigationController?.popViewController(animated: true)

How can I find where Python is installed on Windows?

If you have Python in your environment variable then you can use the following command in cmd:

 where python

or for Unix enviroment

 which python

command line image :

enter image description here

Moment.js transform to date object

Since momentjs has no control over javascript date object I found a work around to this.

_x000D_
_x000D_
const currentTime = new Date();    _x000D_
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");_x000D_
const convertTimeObject = new Date(convertTime);
_x000D_
_x000D_
_x000D_

This will give you a javascript date object with the converted time

Twitter Bootstrap inline input with dropdown

Current state: default implementation in docs

Currently there is a default implementation of input+dropdown combo in the documentation here (search for "Button dropdowns"). I leave the original solution for the record and for those who cannot use solution now included in the documentation.

Original solution

Yes, it is possible. As a matter of fact, there is one example in the Twitter Bootstrap documentation (follow the link and search "Examples" for dropdown buttons):

<div class="btn-group">
    <a class="btn btn-primary" href="#">
        <i class="icon-user icon-white"></i> User
    </a>
    <a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
        <span class="caret"></span>
    </a>
    <ul class="dropdown-menu">
        <li><a href="#"><i class="icon-pencil"></i> Edit</a></li>
        <li><a href="#"><i class="icon-trash"></i> Delete</a></li>
        <li><a href="#"><i class="icon-ban-circle"></i> Ban</a></li>
        <li class="divider"></li>
        <li><a href="#"><i class="i"></i> Make admin</a></li>
    </ul>
</div>

If enclosed within text, it can look like this (with text on the button changed, nothing else):

Twitter Bootstrap dropdown button within text

EDIT:

If you are trying to achieve <input> with appended dropdown menu as in the dropdown buttons, then this is one of the solutions:

  1. Add a btn-group class to the element that has input-append class,
  2. Add elements with classes dropdown-toggle and dropdown-menu at the end of the element with class input-append,
  3. Override style for element matching .input-append .btn.dropdown-menu so it does not have float: left (otherwise it will get into next line).

The resulting code may look like this:

<div class="input-append btn-group">
    <input class="span2" id="appendedInputButton" size="16" type="text">
    <a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="#">
        <span class="caret"></span>
    </a>
    <ul class="dropdown-menu">
        <li><a href="#"><i class="icon-pencil"></i> Edit</a></li>
        <li><a href="#"><i class="icon-trash"></i> Delete</a></li>
        <li><a href="#"><i class="icon-ban-circle"></i> Ban</a></li>
        <li class="divider"></li>
        <li><a href="#"><i class="i"></i> Make admin</a></li>
    </ul>
</div>

with a little support from this style override:

.input-append .btn.dropdown-toggle {
    float: none;
}

and give you the exact same result as this:

enter image description here

EDIT 2: Updated the CSS selector (was .dropdown-menu, is .dropdown-toggle).

How do I see which version of Swift I'm using?

To see the default version of swift installed on your machine then from the command line, type the following :

swift --version

Apple Swift version 4.1.2 (swiftlang-902.0.54 clang-902.0.39.2)

Target: x86_64-apple-darwin17.6.0

This is most likely the version that is included in the app store version of Xcode that you have installed (unless you have changed it).

If you want to determine the actual version of Swift being used by a particular version of Xcode (a beta, for instance) then from the command line, invoke the swift binary within the Xcode bundle and pass it the parameter --version

/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift --version

Apple Swift version 4.2 (swiftlang-1000.0.16.7 clang-1000.10.25.3)

Target: x86_64-apple-darwin17.6.0

Mongodb: failed to connect to server on first connect

To connect to mongodb with mongoose, you can use :

mongoose.connect('mongodb://localhost/users_test');

or

mongoose.connect('localhost/users_test');

or

mongoose.connect('localhost','users_test');

But not mongoose.connect('mongodb:localhost/users_test');, it doesnt match the right hostname (mongodb instead of localhost)

How to automatically update your docker containers, if base-images are updated

I'm not going into the whole question of whether or not you want unattended updates in production (I think not). I'm just leaving this here for reference in case anybody finds it useful. Update all your docker images to the latest version with the following command in your terminal:

# docker images | awk '(NR>1) && ($2!~/none/) {print $1":"$2}' | xargs -L1 docker pull

Simplest way to restart service on a remote computer

I recommend the method given by doofledorfer.

If you really want to do it via a direct API call, then look at the OpenSCManager function. Below are sample functions to take a machine name and service, and stop or start them.

function ServiceStart(sMachine, sService : string) : boolean;  //start service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    psTemp     : PChar;
    dwChkP     : DWord;
begin
  ss.dwCurrentState := 0;
  schm := OpenSCManager(PChar(sMachine),Nil,SC_MANAGER_CONNECT);  //connect to the service control manager

  if(schm > 0)then begin // if successful...
    schs := OpenService( schm,PChar(sService),SERVICE_START or SERVICE_QUERY_STATUS);    // open service handle, start and query status
    if(schs > 0)then begin     // if successful...
      psTemp := nil;
      if (StartService(schs,0,psTemp)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_RUNNING <> ss.dwCurrentState)do begin
          dwChkP := ss.dwCheckPoint;  //dwCheckPoint contains a value incremented periodically to report progress of a long operation.  Store it.
          Sleep(ss.dwWaitHint);  //Sleep for recommended time before checking status again
          if(not QueryServiceStatus(schs,ss))then
            break;  //couldn't check status
          if(ss.dwCheckPoint < dwChkP)then
            Break;  //if QueryServiceStatus didn't work for some reason, avoid infinite loop
        end;  //while not running
      CloseServiceHandle(schs);
    end;  //if able to get service handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_RUNNING = ss.dwCurrentState;  //if we were able to start it, return true
end;

function ServiceStop(sMachine, sService : string) : boolean;  //stop service, return TRUE if successful
var schm, schs : SC_Handle;
    ss         : TServiceStatus;
    dwChkP     : DWord;
begin
  schm := OpenSCManager(PChar(sMachine),nil,SC_MANAGER_CONNECT);

  if(schm > 0)then begin
    schs := OpenService(schm,PChar(sService),SERVICE_STOP or SERVICE_QUERY_STATUS);
    if(schs > 0)then begin
      if (ControlService(schs,SERVICE_CONTROL_STOP,ss)) and (QueryServiceStatus(schs,ss)) then
        while(SERVICE_STOPPED <> ss.dwCurrentState) do begin
          dwChkP := ss.dwCheckPoint;
          Sleep(ss.dwWaitHint);
          if(not QueryServiceStatus(schs,ss))then
            Break;

          if(ss.dwCheckPoint < dwChkP)then
            Break;
        end;  //while
      CloseServiceHandle(schs);
    end;  //if able to get svc handle
    CloseServiceHandle(schm);
  end;  //if able to get svc mgr handle
  Result := SERVICE_STOPPED = ss.dwCurrentState;
end;

Cannot find mysql.sock

(Q1) How can I find the socket file?

The default location for the socket file is /tmp/mysql.sock, to find the socket file for your system use this.

mysqladmin variables | grep socket

If you have just installed MySql the mysql.sock file will not be created until the server is started. Use this command to start it.

sudo launchctl load -F /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

If prompted for a password you can pass the username root or other username like this. Terminal will prompt you for the password.

mysqladmin --user root --password variables | grep socket

(Q2) How can I refresh locate index

Refresh the locate db with this command.

sudo /usr/libexec/locate.updatedb

javascript setTimeout() not working

Use:

setTimeout(startTimer,startInterval); 

You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().

Enabling error display in PHP via htaccess only

.htaccess:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

How to Convert an int to a String?

You can use

text_Rate.setText(""+sdRate);

ECMAScript 6 arrow function that returns an object

You must wrap the returning object literal into parentheses. Otherwise curly braces will be considered to denote the function’s body. The following works:

p => ({ foo: 'bar' });

You don't need to wrap any other expression into parentheses:

p => 10;
p => 'foo';
p => true;
p => [1,2,3];
p => null;
p => /^foo$/;

and so on.

Reference: MDN - Returning object literals

How can I avoid running ActiveRecord callbacks?

If you are using Rails 2. You could use SQL query for updating your column without running callbacks and validations.

YourModel.connection.execute("UPDATE your_models SET your_models.column_name=#{value} WHERE your_models.id=#{ym.id}")

I think it should work in any rails versions.

Using NOT operator in IF conditions

It is generally not a bad idea to avoid the !-operator if you have the choice. One simple reason is that it can be a source of errors, because it is possible to overlook it. More readable can be: if(conditionA==false) in some cases. This mainly plays a role if you skip the else part. If you have an else-block anyway you should not use the negation in the if-condition.

Except for composed-conditions like this:

if(!isA() && isB() && !isNotC())

Here you have to use some sort of negation to get the desired logic. In this case, what really is worth thinking about is the naming of the functions or variables. Try to name them so you can often use them in simple conditions without negation.

In this case you should think about the logic of isNotC() and if it could be replaced by a method isC() if it makes sense.

Finally your example has another problem when it comes to readability which is even more serious than the question whether to use negation or not: Does the reader of the code really knows when doSomething() returns true and when false? If it was false was it done anyway? This is a very common problem, which ends in the reader trying to find out what the return values of functions really mean.

Return multiple values to a method caller

Future version of C# is going to include named tuples. Have a look at this channel9 session for the demo https://channel9.msdn.com/Events/Build/2016/B889

Skip to 13:00 for the tuple stuff. This will allow stuff like:

(int sum, int count) Tally(IEnumerable<int> list)
{
// calculate stuff here
return (0,0)
}

int resultsum = Tally(numbers).sum

(incomplete example from video)

Start and stop a timer PHP

Use the microtime function. The documentation includes example code.

What does the variable $this mean in PHP?

It is the way to reference an instance of a class from within itself, the same as many other object oriented languages.

From the PHP docs:

The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Writing file to web server - ASP.NET

protected void TestSubmit_ServerClick(object sender, EventArgs e)
{
  using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/data.txt"), true))
 {
  _testData.WriteLine(TextBox1.Text); // Write the file.
 }         
}

Server.MapPath takes a virtual path and returns an absolute one. "~" is used to resolve to the application root.

Defining TypeScript callback type

You can declare a new type:

declare type MyHandler = (myArgument: string) => void;

var handler: MyHandler;

Update.

The declare keyword is not necessary. It should be used in the .d.ts files or in similar cases.

How to get the current location latitude and longitude in android

You can use following class as service class to run your application in background

import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

    private GPSTracker gpsTracker;
    private Handler handler= new Handler();
    private Timer timer = new Timer();
    private Distance pastDistance = new Distance();
     private Distance currentDistance = new Distance();
    public static double DISTANCE;
    boolean flag = true ;
    private double totalDistance ;
    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {

        super.onStart(intent, startId);
        gpsTracker = new GPSTracker(HomeFragment.HOMECONTEXT);
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        if(flag){
                            pastDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                            pastDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                            flag = false;
                        }else{
                            currentDistance.setLatitude(gpsTracker.getLocation().getLatitude());
                            currentDistance.setLongitude(gpsTracker.getLocation().getLongitude());
                            flag = comapre_LatitudeLongitude();
                        }
                        Toast.makeText(HomeFragment.HOMECONTEXT, "latitude:"+gpsTracker.getLocation().getLatitude(), 4000).show();

                    }
                });


            }
        };

        timer.schedule(timerTask,0, 5000);

    }

    private double distance(double lat1, double lon1, double lat2, double lon2) {
          double theta = lon1 - lon2;
          double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
          dist = Math.acos(dist);
          dist = rad2deg(dist);
          dist = dist * 60 * 1.1515;
           return (dist);
        }

       private double deg2rad(double deg) {
          return (deg * Math.PI / 180.0);
        }
       private double rad2deg(double rad) {
          return (rad * 180.0 / Math.PI);
   }


    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }



    @Override
    public void onDestroy() {

        super.onDestroy();
        System.out.println("--------------------------------onDestroy -stop service ");
        timer.cancel();
        DISTANCE = totalDistance ;
    }
    public boolean comapre_LatitudeLongitude(){

        if(pastDistance.getLatitude() == currentDistance.getLatitude() && pastDistance.getLongitude() == currentDistance.getLongitude()){
            return false;
        }else{

            final double distance = distance(pastDistance.getLatitude(),pastDistance.getLongitude(),currentDistance.getLatitude(),currentDistance.getLongitude());
            System.out.println("Distance in mile :"+distance);
            handler.post(new Runnable() {

                @Override
                public void run() {
                    float kilometer=1.609344f;

                    totalDistance = totalDistance +  distance * kilometer;
                    DISTANCE = totalDistance;
                    //Toast.makeText(HomeFragment.HOMECONTEXT, "distance in km:"+DISTANCE, 4000).show();

                }
            });

            return true;
        }

    }

}

Add One another class to get location

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class GPSTracker implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null; 
double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

protected LocationManager locationManager;
private Location m_Location;
 public GPSTracker(Context context) {
    this.mContext = context;
    m_Location = getLocation();
    System.out.println("location Latitude:"+m_Location.getLatitude());
    System.out.println("location Longitude:"+m_Location.getLongitude());
    System.out.println("getLocation():"+getLocation());
    }

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Context.LOCATION_SERVICE);

        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } 
        else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

public void stopUsingGPS() {
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
    }
}

public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    }

    return latitude;
}

public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    }

    return longitude;
}

public boolean canGetLocation() {
    return this.canGetLocation;
}

@Override
public void onLocationChanged(Location arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}


}

// --------------Distance.java

 public class Distance  {
    private double latitude ;
    private double longitude;
        public double getLatitude() {
            return latitude;
        }
        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }
        public double getLongitude() {
            return longitude;
        }
        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }



}

.prop() vs .attr()

Gary Hole answer is very relevant to solve the problem if the code is written in such way

obj.prop("style","border:1px red solid;")

Since the prop function return CSSStyleDeclaration object, above code will not working properly in some browser(tested with IE8 with Chrome Frame Plugin in my case).

Thus changing it into following code

obj.prop("style").cssText = "border:1px red solid;"

solved the problem.

How to convert Strings to and from UTF8 byte arrays in Java

As an alternative, StringUtils from Apache Commons can be used.

 byte[] bytes = {(byte) 1};
 String convertedString = StringUtils.newStringUtf8(bytes);

or

 String myString = "example";
 byte[] convertedBytes = StringUtils.getBytesUtf8(myString);

If you have non-standard charset, you can use getBytesUnchecked() or newString() accordingly.

String.equals() with multiple conditions (and one action on result)

If you develop for Android KitKat or newer, you could also use a switch statement (see: Android coding with switch (String)). e.g.

switch(yourString)
{
     case "john":
          //do something for john
     case "mary":
          //do something for mary
}

How do I import a .dmp file into Oracle?

imp system/system-password@SID file=directory-you-selected\FILE.dmp log=log-dir\oracle_load.log fromuser=infodba touser=infodba commit=Y

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

How to multiply individual elements of a list with a number?

Here is a functional approach using map, itertools.repeat and operator.mul:

import operator
from itertools import repeat


def scalar_multiplication(vector, scalar):
    yield from map(operator.mul, vector, repeat(scalar))

Example of usage:

>>> v = [1, 2, 3, 4]
>>> c = 3
>>> list(scalar_multiplication(v, c))
[3, 6, 9, 12]

Aggregate multiple columns at once

We can use the formula method of aggregate. The variables on the 'rhs' of ~ are the grouping variables while the . represents all other variables in the 'df1' (from the example, we assume that we need the mean for all the columns except the grouping), specify the dataset and the function (mean).

aggregate(.~id1+id2, df1, mean)

Or we can use summarise_each from dplyr after grouping (group_by)

library(dplyr)
df1 %>%
    group_by(id1, id2) %>% 
    summarise_each(funs(mean))

Or using summarise with across (dplyr devel version - ‘0.8.99.9000’)

df1 %>% 
    group_by(id1, id2) %>%
    summarise(across(starts_with('val'), mean))

Or another option is data.table. We convert the 'data.frame' to 'data.table' (setDT(df1), grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD) and get the mean.

library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)] 

data

df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b", 
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"), 
val1 = c(1L, 
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L, 
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"), 
class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8"))

No server in Eclipse; trying to install Tomcat

Eclipse IDE for Java Developers 'Servers' doesn't exist. Therefore download correct Eclipse IDE. It is Eclipse IDE for Enterprise Java Developers(Eclipse IDE for Java EE Developers). This way is easy.

How to make a JFrame Modal in Swing java

If you're prepared to use a JDialog instead of a JFrame, you can set the ModalityType to APPLICATION_MODAL.

This provides identical behaviour to your typical JOptionPane:

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

public class MyDialog extends JFrame {

public MyDialog() {
    setBounds(300, 300, 300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    setLayout(new FlowLayout());
    JButton btn = new JButton("TEST");
    add(btn);
    btn.addActionListener(new ActionListener() 
    {

        @Override
        public void actionPerformed(ActionEvent e) {
            showDialog();
        }
    });
}

private void showDialog() 
{

    JDialog dialog = new JDialog(this, Dialog.ModalityType.APPLICATION_MODAL);
    //OR, you can do the following...
    //JDialog dialog = new JDialog();
    //dialog.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);

    dialog.setBounds(350, 350, 200, 200);
    dialog.setVisible(true);
}

public static void main(String[] args) 
{
    new MyDialog();
}
}

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Change the selected value of a drop-down list with jQuery

<asp:DropDownList id="MyDropDown" runat="server" />

Use $("select[name$='MyDropDown']").val().

Removing single-quote from a string in php

Try this one. You can strip just ' and " with:

$FileName = str_replace(array('\'', '"'), '', $UserInput); 

How do I update Ruby Gems from behind a Proxy (ISA-NTLM)

If you are having problems getting authenticated through your proxy, be sure to set the environment variables in exactly the format below:

set HTTP_PROXY=some.proxy.com
set HTTP_PROXY_USER=user
set HTTP_PROXY_PASS=password

The user:password@ syntax doesn't seem to work and there are also some badly named environment variables floating around on Stack Overflow and various forum posts.

Also be aware that it can take a while for your gems to start downloading. At first I thought it wasn't working but with a bit of patience they started downloading as expected.

Strtotime() doesn't work with dd/mm/YYYY format

$srchDate = date_format(date_create_from_format('d/m/Y', $srchDate), 'Y/m/d');

This will work for you. You convert the String into a custom date format where you can specify to PHP what the original format of the String is that had been given to it. Now that it is a date format, you can convert it to PHP's default date format, which is the same that is used by MySQL.

Using Java with Microsoft Visual Studio 2012

IntegraStudio enables syntax coloring, building, debugging and finding definition and references (F12 and ALT-F12) for Java projects in Visual Studio.

Error: Cannot access file bin/Debug/... because it is being used by another process

I've had this error crop up on me before, even in Visual Studio 2008. It came back and more prevalent in Visual Studio 2012.

Here is what I do.

Paste this in the troublesome project's pre-build event:

if exist "$(TargetPath).locked" del "$(TargetPath).locked"
if exist "$(TargetPath)" if not exist "$(TargetPath).locked" move "$(TargetPath)" "$(TargetPath).locked"

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Use case/esac to test:

case "$var" in
  "") echo "zero length";;
esac

matching query does not exist Error in Django

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return UniversityDetails.objects.get(email__exact=email)
    except UniversityDetails.DoesNotExist:
        return False

What happens if you don't commit a transaction to a database (say, SQL Server)?

Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.

Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).

Accessing variables from other functions without using global variables

I think your best bet here may be to define a single global-scoped variable, and dumping your variables there:

var MyApp = {}; // Globally scoped object

function foo(){
    MyApp.color = 'green';
}

function bar(){
    alert(MyApp.color); // Alerts 'green'
} 

No one should yell at you for doing something like the above.

How to select a dropdown value in Selenium WebDriver using Java

Actually select does select but not placing the selected values to the respective field . Where wondered the below snippet works perfectly

driver.findElement(By.name("period")).sendKeys("Last 52 Weeks");

SQL Server Express CREATE DATABASE permission denied in database 'master'

For SQL server 2012,

  1. First, log in to the SQL server as an administrator and go to Security tab

  2. Then move into Server Roles and double click on sysadmin role

  3. Now add user which you want to give permission to create Database by clicking Add button

  4. Click OK button and now run the query

Hope this will help for someone

Python Replace \\ with \

Your original string, a = 'a\\nb' does not actually have two '\' characters, the first one is an escape for the latter. If you do, print a, you'll see that you actually have only one '\' character.

>>> a = 'a\\nb'
>>> print a
a\nb

If, however, what you mean is to interpret the '\n' as a newline character, without escaping the slash, then:

>>> b = a.replace('\\n', '\n')
>>> b
'a\nb'
>>> print b
a
b

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

One of the way to do this is you can use ResponseEntity as a return object.

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)

public ResponseEntity<?> create(@RequestBody String data) {

if(everything_fine)
    return new ResponseEntity<>(RestModel, HttpStatus.OK);
else
    return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);

}

How can I combine two HashMap objects containing the same types?

you can use - addAll method

http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html

But there is always this issue that - if your two hash maps have any key same - then it will override the value of the key from first hash map with the value of the key from second hash map.

For being on safer side - change the key values - you can use prefix or suffix on the keys - ( different prefix/suffix for first hash map and different prefix/suffix for second hash map )

make: *** No rule to make target `all'. Stop

Your makefile should ideally be named makefile, not make. Note that you can call your makefile anything you like, but as you found, you then need the -f option with make to specify the name of the makefile. Using the default name of makefile just makes life easier.

MySQL: NOT LIKE

I don't know why

cfg_name_unique NOT LIKE '%categories%' 

still returns those two values, but maybe exclude them explicit:

SELECT *
    FROM developer_configurations_cms

    WHERE developer_configurations_cms.cat_id = '1'
    AND developer_configurations_cms.cfg_variables LIKE '%parent_id=2%'
    AND developer_configurations_cms.cfg_name_unique NOT LIKE '%categories%'
    AND developer_configurations_cms.cfg_name_unique NOT IN ('categories_posts', 'categories_news')

Chrome not rendering SVG referenced via <img> tag

looks like a Chrome bug, i did something else as i almost got crazy because of this... using Chrom debugger if you change the css of the svg object it shows on the screen.

so what i did was: 1. check for screen size 2. listen to the "load" event of my SVG object 3. when the element is loaded i change its css using jQuery 4. it did the trick for me

_x000D_
_x000D_
if (jQuery(window).width() < 769) {_x000D_
_x000D_
  jQuery('object#mysvg-logo')[0].addEventListener('load', function() {_x000D_
       jQuery("object#mysvg-logo").css('width','181px');_x000D_
  }, true);_x000D_
_x000D_
}
_x000D_
width: 180px;
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<object id="mysvg-logo" type="image/svg+xml" data="my svg logo url here">Your browser does not support SVG</object>
_x000D_
_x000D_
_x000D_

Round number to nearest integer

Your solution is calling round without specifying the second argument (number of decimal places)

>>> round(0.44)
0
>>> round(0.64)
1

which is a much better result than

>>> int(round(0.44, 2))
0
>>> int(round(0.64, 2))
0

From the Python documentation at https://docs.python.org/3/library/functions.html#round

round(number[, ndigits])

Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

Convert from lowercase to uppercase all values in all character variables in dataframe

From the dplyr package you can also use the mutate_all() function in combination with toupper(). This will affect both character and factor classes.

library(dplyr)
df <- mutate_all(df, funs=toupper)

Bootstrap Modal Backdrop Remaining

The problem is that bootstrap removes the backdrop asynchronously. So when you call hide and show quickly after each other, the backdrop isn't removed.

The solution (as you've mentioned) is to wait for the modal to have been hidden completely, using the 'hidden.bs.modal' event. Use jQuery one to only perform the callback once. I've forked your jsfiddle to show how this would work.

// wait for the backdrop to be removed nicely.
loadingModal.one('hidden.bs.modal', function()
{
    loadingModal.modal("show");

    //Again simulate 3 seconds
    setTimeout(function () {
        loadingModal.modal("hide");
    }, 3000);
});
// hide for the first time, after binding to the hidden event.
loadingModal.modal("hide");

Looking through the code in Bootstrap:

This is what makes hiding the modal asynchronous:

$.support.transition && this.$element.hasClass('fade') ?
    this.$element
        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
        .emulateTransitionEnd(Modal.TRANSITION_DURATION) :
    this.hideModal()

This checks whether transitions are supported and the fade class is included on the modal. When both are true, it waits for the fade effect to complete, before hiding the modal. This waiting happens again before removing the backdrop.

This is why removing the fade class will make hiding the modal synchronous (no more waiting for CSS fade effect to complete) and why the solution by reznic works.

This check determines whether to add or remove the backdrop. isShown = true is performed synchronously. When you call hide and show quickly after each other, isShown becomes true and the check adds a backdrop, instead of removing the previous one, creating the problem you're having.

PowerShell says "execution of scripts is disabled on this system."

I have also faced similar issue try this hope it helps someone As I'm using windows so followed the steps as given below Open command prompt as an administrator and then go to this path

C:\Users\%username%\AppData\Roaming\npm\

Look for the file ng.ps1 in this folder (dir) and then delete it (del ng.ps1)

You can also clear npm cache after this though it should work without this step as well. Hope it helps as it worked for me.

Hope it helps

How to pause a YouTube player when hiding the iframe?

Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:

    function toggleVideo(state) {
        if(state == 'hide'){
            $('#video-div').modal('hide');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
        else {
            $('#video-div').modal('show');
            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
        }
    }

The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .

For more on the html see RobW's answer.

How do I create a circle or square with just CSS - with a hollow center?

i don't know of a simple css(2.1 standard)-only solution for circles, but for squares you can do easily:

.squared {
    border: 2x solid black;
}

then, use the following html code:

<img src="…" alt="an image " class="squared" />

Calculating sum of repeated elements in AngularJS ng-repeat

You can use a custom Angular filter that takes the dataset object array and the key in each object to sum. The filter can then return the sum:

.filter('sumColumn', function(){
        return function(dataSet, columnToSum){
            let sum = 0;

            for(let i = 0; i < dataSet.length; i++){
                sum += parseFloat(dataSet[i][columnToSum]) || 0;
            }

            return sum;
        };
    })

Then in your table to sum a column you can use:

<th>{{ dataSet | sumColumn: 'keyInObjectToSum' }}</th>

How to validate an OAuth 2.0 access token for a resource server?

Update Nov. 2015: As per Hans Z. below - this is now indeed defined as part of RFC 7662.

Original Answer: The OAuth 2.0 spec (RFC 6749) doesn't clearly define the interaction between a Resource Server (RS) and Authorization Server (AS) for access token (AT) validation. It really depends on the AS's token format/strategy - some tokens are self-contained (like JSON Web Tokens) while others may be similar to a session cookie in that they just reference information held server side back at the AS.

There has been some discussion in the OAuth Working Group about creating a standard way for an RS to communicate with the AS for AT validation. My company (Ping Identity) has come up with one such approach for our commercial OAuth AS (PingFederate): https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=lzn1564003025072.html#lzn1564003025072__section_N10578_N1002A_N10001. It uses REST based interaction for this that is very complementary to OAuth 2.0.

Directory-tree listing in Python

If you need globbing abilities, there's a module for that as well. For example:

import glob
glob.glob('./[0-9].*')

will return something like:

['./1.gif', './2.txt']

See the documentation here.

Arrays in cookies PHP

Using serialize and unserialize on cookies is a security risk. Users (or attackers) can alter cookie data, then when you unserialize it, it could run PHP code on your server. Cookie data should not be trusted. Use JSON instead!

From PHP's site:

Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

beyond top level package error in relative import

EDIT: There are better/more coherent answers to this question in other questions:


Why doesn't it work? It's because python doesn't record where a package was loaded from. So when you do python -m test_A.test, it basically just discards the knowledge that test_A.test is actually stored in package (i.e. package is not considered a package). Attempting from ..A import foo is trying to access information it doesn't have any more (i.e. sibling directories of a loaded location). It's conceptually similar to allowing from ..os import path in a file in math. This would be bad because you want the packages to be distinct. If they need to use something from another package, then they should refer to them globally with from os import path and let python work out where that is with $PATH and $PYTHONPATH.

When you use python -m package.test_A.test, then using from ..A import foo resolves just fine because it kept track of what's in package and you're just accessing a child directory of a loaded location.

Why doesn't python consider the current working directory to be a package? NO CLUE, but gosh it would be useful.

Dynamically add event listener

I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:

ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }

If i´m adding a listener

this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
    alert('Clicking the document');
})

I´d expect my function to execute what i intended, not the total opposite which is remove the listener.

// I´d expect an alert('Clicking the document'); 
this.listenToClick();
// what you actually get is removing the listener, so nothing...

In the given scenario, It´d actually make to more sense to name it like:

// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
    console.log('Clicking the document', evt);
})

let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
    console.log('Clicking the button', evt);
});

There must be a good reason for this but in my opinion it´s very misleading and not intuitive.

Calling a stored procedure in Oracle with IN and OUT parameters

Go to Menu Tool -> SQL Output, Run the PL/SQL statement, the output will show on SQL Output panel.

Creating new table with SELECT INTO in SQL

The syntax for creating a new table is

CREATE TABLE new_table
AS
SELECT *
  FROM old_table

This will create a new table named new_table with whatever columns are in old_table and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.

SELECT INTO is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.

Circle-Rectangle collision detection (intersection)

Here's a fast one-line test for this:

if (length(max(abs(center - rect_mid) - rect_halves, 0)) <= radius ) {
  // They intersect.
}

This is the axis-aligned case where rect_halves is a positive vector pointing from the rectangle middle to a corner. The expression inside length() is a delta vector from center to a closest point in the rectangle. This works in any dimension.

COUNT / GROUP BY with active record?

This code counts rows with date range:

Controller:

$this->load->model("YourModelName");
$data ['query'] = $this->YourModelName->get_report();

Model:

  public function get_report()
     {   
       $query = $this->db->query("SELECT  *
FROM   reservation WHERE arvdate <= '2016-7-20' AND  dptrdate >= '2016-10-25' ");
       return $query;
     }

where 'arvdate' and 'dptrdate' are two dates on database and 'reservation' is the table name.

View:

<?php
 echo $query->num_rows();
?>

This code is to return number of rows. To return table data, then use

$query->rows();
return $row->table_column_name;

What is PEP8's E128: continuation line under-indented for visual indent?

PEP-8 recommends you indent lines to the opening parentheses if you put anything on the first line, so it should either be indenting to the opening bracket:

urlpatterns = patterns('',
                       url(r'^$', listing, name='investment-listing'))

or not putting any arguments on the starting line, then indenting to a uniform level:

urlpatterns = patterns(
    '',
    url(r'^$', listing, name='investment-listing'),
)

urlpatterns = patterns(
    '', url(r'^$', listing, name='investment-listing'))

I suggest taking a read through PEP-8 - you can skim through a lot of it, and it's pretty easy to understand, unlike some of the more technical PEPs.

Reference - What does this error mean in PHP?

Notice: Trying to get property of non-object error

Happens when you try to access a property of an object while there is no object.

A typical example for a non-object notice would be

$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object

In this case, $users is an array (so not an object) and it does not have any properties.

This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).

This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.

As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.

It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object

The problem is accessing the nodeValue property (field) of the first item while it has not been checked if it exists or not in the $result collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:

$result  = $xpath->query("//*[@id='detail-sections']/div[1]");
$div     = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
    $divText = $div->nodeValue;
}
echo $divText;

Related errors:

jQuery - add additional parameters on submit (NOT ajax)

Similar answer, but I just wanted to make it available for an easy/quick test.

_x000D_
_x000D_
var input = $("<input>")_x000D_
               .attr("name", "mydata").val("go Rafa!");_x000D_
_x000D_
$('#easy_test').append(input);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<form id="easy_test">_x000D_
  _x000D_
</form>
_x000D_
_x000D_
_x000D_

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

@XmlElement
public void setAge(int age) {
    this.age = age;
}

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

@XmlElement(name="Age")
public void setAge(int age) {
    this.age = age;
}

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

Confirmation before closing of tab/browser

The shortest solution for the year 2020 (for those happy people who don't need to support IE)

Tested in Chrome, Firefox, Safari.

function onBeforeUnload(e) {
    if (thereAreUnsavedChanges()) {
        e.preventDefault();
        e.returnValue = '';
        return;
    }

    delete e['returnValue'];
}

window.addEventListener('beforeunload', onBeforeUnload);

Actually no one modern browser (Chrome, Firefox, Safari) displays the "return value" as a question to user. Instead they show their own confirmation text (it depends on browser). But we still need to return some (even empty) string to trigger that confirmation on Chrome.

More explanations see on MDN here and here.

Non-static method requires a target

All the answers are pointing to a Lambda expression with an NRE (Null Reference Exception). I have found that it also occurs when using Linq to Entities. I thought it would be helpful to point out that this exception is not limited to just an NRE inside a Lambda expression.

Using BufferedReader to read Text File

Use try with resources. this will automatically close the resources.

try (BufferedReader br = new BufferedReader(new FileReader("C:/test.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (Exception e) {

}