Programs & Examples On #Textcompositionmanager

Groovy write to file (newline)

@Comment for ID:14. It's for me rather easier to write:

out.append it

instead of

out.println it

println did on my machine only write the first file of the ArrayList, with append I get the whole List written into the file.

Kindly anyway for the quick-and-dirty-solution.

When use getOne and findOne methods Spring Data JPA

TL;DR

T findOne(ID id) (name in the old API) / Optional<T> findById(ID id) (name in the new API) relies on EntityManager.find() that performs an entity eager loading.

T getOne(ID id) relies on EntityManager.getReference() that performs an entity lazy loading. So to ensure the effective loading of the entity, invoking a method on it is required.

findOne()/findById() is really more clear and simple to use than getOne().
So in the very most of cases, favor findOne()/findById() over getOne().


API Change

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Previously, it was defined in the CrudRepository interface as :

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is which one defined in the QueryByExampleExecutor interface as :

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want to that as replacement.

In fact, the method with the same behavior is still there in the new API but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional. Which is not so bad to prevent NullPointerException.

So, the actual choice is now between Optional<T> findById(ID id) and T getOne(ID id).


Two distinct methods that rely on two distinct JPA EntityManager retrieval methods

1) The Optional<T> findById(ID id) javadoc states that it :

Retrieves an entity by its id.

As we look into the implementation, we can see that it relies on EntityManager.find() to do the retrieval :

public Optional<T> findById(ID id) {

    Assert.notNull(id, ID_MUST_NOT_BE_NULL);

    Class<T> domainType = getDomainClass();

    if (metadata == null) {
        return Optional.ofNullable(em.find(domainType, id));
    }

    LockModeType type = metadata.getLockModeType();

    Map<String, Object> hints = getQueryHints().withFetchGraphs(em).asMap();

    return Optional.ofNullable(type == null ? em.find(domainType, id, hints) : em.find(domainType, id, type, hints));
}

And here em.find() is an EntityManager method declared as :

public <T> T find(Class<T> entityClass, Object primaryKey,
                  Map<String, Object> properties);

Its javadoc states :

Find by primary key, using the specified properties

So, retrieving a loaded entity seems expected.

2) While the T getOne(ID id) javadoc states (emphasis is mine) :

Returns a reference to the entity with the given identifier.

In fact, the reference terminology is really board and JPA API doesn't specify any getOne() method.
So the best thing to do to understand what the Spring wrapper does is looking into the implementation :

@Override
public T getOne(ID id) {
    Assert.notNull(id, ID_MUST_NOT_BE_NULL);
    return em.getReference(getDomainClass(), id);
}

Here em.getReference() is an EntityManager method declared as :

public <T> T getReference(Class<T> entityClass,
                              Object primaryKey);

And fortunately, the EntityManager javadoc defined better its intention (emphasis is mine) :

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

So, invoking getOne() may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.

It means that if we invoke getOne() and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable.
For example if the proxy object is serialized, you could get a null reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException is thrown.
So in this kind of situation, the throw of EntityNotFoundException that is the main reason to use getOne() to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.

In any case, to ensure its loading you have to manipulate the entity while the session is opened. You can do it by invoking any method on the entity.
Or a better alternative use findById(ID id) instead of.


Why a so unclear API ?

To finish, two questions for Spring-Data-JPA developers:

  • why not having a clearer documentation for getOne() ? Entity lazy loading is really not a detail.

  • why do you need to introduce getOne() to wrap EM.getReference() ?
    Why not simply stick to the wrapped method :getReference() ? This EM method is really very particular while getOne() conveys a so simple processing.

How to call a method function from another class?

In class WeatherRecord:

First import the class if they are in different package else this statement is not requires

Import <path>.ClassName



Then, just referene or call your object like:

Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();



But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.

Date.date(date,month,year);   // this is enough to call those static function 


Have clear concept on Object and Static functions. Click me

How to retrieve value from elements in array using jQuery?

Your syntax is incorrect.

card_value = $(array[i]).val(); or card_value = array[i].value;

array[i] is not a jQuery object (for some reason).

Checking your browser's console can be helpful for things like this.

Provide schema while reading csv file as a dataframe

I'm using the solution provided by Arunakiran Nulu in my analysis (see the code). Despite it is able to assign the correct types to the columns, all the values returned are null. Previously, I've tried to the option .option("inferSchema", "true") and it returns the correct values in the dataframe (although different type).

val customSchema = StructType(Array(
    StructField("numicu", StringType, true),
    StructField("fecha_solicitud", TimestampType, true),
    StructField("codtecnica", StringType, true),
    StructField("tecnica", StringType, true),
    StructField("finexploracion", TimestampType, true),
    StructField("ultimavalidacioninforme", TimestampType, true),
    StructField("validador", StringType, true)))

val df_explo = spark.read
        .format("csv")
        .option("header", "true")
        .option("delimiter", "\t")
        .option("timestampFormat", "yyyy/MM/dd HH:mm:ss") 
        .schema(customSchema)
        .load(filename)

Result

root


|-- numicu: string (nullable = true)
 |-- fecha_solicitud: timestamp (nullable = true)
 |-- codtecnica: string (nullable = true)
 |-- tecnica: string (nullable = true)
 |-- finexploracion: timestamp (nullable = true)
 |-- ultimavalidacioninforme: timestamp (nullable = true)
 |-- validador: string (nullable = true)

and the table is:

|numicu|fecha_solicitud|codtecnica|tecnica|finexploracion|ultimavalidacioninforme|validador|
+------+---------------+----------+-------+--------------+-----------------------+---------+
|  null|           null|      null|   null|          null|                   null|     null|
|  null|           null|      null|   null|          null|                   null|     null|
|  null|           null|      null|   null|          null|                   null|     null|
|  null|           null|      null|   null|          null|                   null|     null|

Best Practice to Use HttpClient in Multithreaded Environment

With HttpClient 4.5 you can do this:

CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();

Note that this one implements Closeable (for shutting down of the connection manager).

How to specify the JDK version in android studio?

You can use cmd + ; for Mac or Ctrl + Alt + Shift + S for Windows/Linux to pull up the Project Structure dialog. In there, you can set the JDK location as well as the Android SDK location.

Project Structure Dialog

To get your JDK location, run /usr/libexec/java_home -v 1.7 in terminal. Send 1.7 for Java 7 or 1.8 for Java 8.

Detecting superfluous #includes in C/C++?

Also check out include-what-you-use, which solves a similar problem.

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

I had this issue, as I had copied a (fairly generic) webpage from one of my ASP.Net applications into a new application.

I changed the relevant namespace commands, to reflect the new location of the file... but... I had forgotten to change the Inherits parameter in the aspx page itself.

<%@ Page MasterPageFile="" StylesheetTheme="" Language="C#"
    AutoEventWireup="true" CodeBehind="MikesReports.aspx.cs" 
    Inherits="MikesCompany.MikesProject.MikesReports" %>

Once I had changed the Inherits parameter, the error went away.

Why use Redux over Facebook Flux?

You might be best starting with reading this post by Dan Abramov where he discusses various implementations of Flux and their trade-offs at the time he was writing redux: The Evolution of Flux Frameworks

Secondly that motivations page you link to does not really discuss the motivations of Redux so much as the motivations behind Flux (and React). The Three Principles is more Redux specific though still does not deal with the implementation differences from the standard Flux architecture.

Basically, Flux has multiple stores that compute state change in response to UI/API interactions with components and broadcast these changes as events that components can subscribe to. In Redux, there is only one store that every component subscribes to. IMO it feels at least like Redux further simplifies and unifies the flow of data by unifying (or reducing, as Redux would say) the flow of data back to the components - whereas Flux concentrates on unifying the other side of the data flow - view to model.

JavaScript for detecting browser language preference

First of all, excuse me for my English. I would like to share my code, because it works and it is different than the others given anwers. In this exemple,if you speak French (France, Belgium or other french language) you are redirected on the french page, otherwise on the english page, depending on the browser configuration :

_x000D_
_x000D_
<script type="text/javascript">_x000D_
        $(document).ready(function () {_x000D_
            var userLang = navigator.language || navigator.userLanguage;_x000D_
            if (userLang.startsWith("fr")) {_x000D_
                    window.location.href = '../fr/index.html';_x000D_
                }_x000D_
            else {_x000D_
                    window.location.href = '../en/index.html';_x000D_
                }_x000D_
            });_x000D_
    </script>
_x000D_
_x000D_
_x000D_

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

How do I check whether a file exists without exceptions?

If the reason you're checking is so you can do something like if file_exists: open_it(), it's safer to use a try around the attempt to open it. Checking and then opening risks the file being deleted or moved or something between when you check and when you try to open it.

If you're not planning to open the file immediately, you can use os.path.isfile

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

import os.path
os.path.isfile(fname) 

if you need to be sure it's a file.

Starting with Python 3.4, the pathlib module offers an object-oriented approach (backported to pathlib2 in Python 2.7):

from pathlib import Path

my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists

To check a directory, do:

if my_file.is_dir():
    # directory exists

To check whether a Path object exists independently of whether is it a file or directory, use exists():

if my_file.exists():
    # path exists

You can also use resolve(strict=True) in a try block:

try:
    my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
    # doesn't exist
else:
    # exists

How to kill a running SELECT statement

There is no need to kill entire session. In Oracle 18c you could use ALTER SYSTEM CANCEL:

Cancelling a SQL Statement in a Session

You can cancel a SQL statement in a session using the ALTER SYSTEM CANCEL SQL statement.

Instead of terminating a session, you can cancel a high-load SQL statement in a session. When you cancel a DML statement, the statement is rolled back.

ALTER SYSTEM CANCEL SQL 'SID, SERIAL[, @INST_ID][, SQL_ID]';

If @INST_ID is not specified, the instance ID of the current session is used.

If SQL_ID is not specified, the currently running SQL statement in the specified session is terminated.

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

How to convert a string into double and vice versa?

Adding to olliej's answer, you can convert from an int back to a string with NSNumber's stringValue:

[[NSNumber numberWithInt:myInt] stringValue]

stringValue on an NSNumber invokes descriptionWithLocale:nil, giving you a localized string representation of value. I'm not sure if [NSString stringWithFormat:@"%d",myInt] will give you a properly localized reprsentation of myInt.

Java JTable setting Column Width

This code is worked for me without setAutoResizeModes.

        TableColumnModel columnModel = jTable1.getColumnModel();
        columnModel.getColumn(1).setPreferredWidth(170);
        columnModel.getColumn(1).setMaxWidth(170);
        columnModel.getColumn(2).setPreferredWidth(150);
        columnModel.getColumn(2).setMaxWidth(150);
        columnModel.getColumn(3).setPreferredWidth(40);
        columnModel.getColumn(3).setMaxWidth(40);

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:

Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."

He then implements an action filter that maps the JSON to C# objects with code shown.

MySQL & Java - Get id of the last inserted value (JDBC)

Wouldn't you just change:

numero = stmt.executeUpdate(query);

to:

numero = stmt.executeUpdate(query, Statement.RETURN_GENERATED_KEYS);

Take a look at the documentation for the JDBC Statement interface.

Update: Apparently there is a lot of confusion about this answer, but my guess is that the people that are confused are not reading it in the context of the question that was asked. If you take the code that the OP provided in his question and replace the single line (line 6) that I am suggesting, everything will work. The numero variable is completely irrelevant and its value is never read after it is set.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

You have 3 options:

1) Get default value

dt = datetime??DateTime.Now;

it will assign DateTime.Now (or any other value which you want) if datetime is null

2) Check if datetime contains value and if not return empty string

if(!datetime.HasValue) return "";
dt = datetime.Value;

3) Change signature of method to

public string ConvertToPersianToShow(DateTime  datetime)

It's all because DateTime? means it's nullable DateTime so before assigning it to DateTime you need to check if it contains value and only then assign.

ImportError: No module named PyQt4

It is likely that you are running the python executable from /usr/bin (Apple version) instead of /usr/loca/bin (Brew version)

You can either

a) check your PATH variable

or

b) run brew doctor

or

c) run which python

to check if it is the case.

Why plt.imshow() doesn't display the image?

plt.imshow displays the image on the axes, but if you need to display multiple images you use show() to finish the figure. The next example shows two figures:

import numpy as np
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
plt.imshow(X_train[1])
plt.show()

In Google Colab, if you comment out the show() method from previous example just a single image will display (the later one connected with X_train[1]).

Here is the content from the help:

plt.show(*args, **kw)
        Display a figure.
        When running in ipython with its pylab mode, display all
        figures and return to the ipython prompt.

        In non-interactive mode, display all figures and block until
        the figures have been closed; in interactive mode it has no
        effect unless figures were created prior to a change from
        non-interactive to interactive mode (not recommended).  In
        that case it displays the figures but does not block.

        A single experimental keyword argument, *block*, may be
        set to True or False to override the blocking behavior
        described above.



plt.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
        Display an image on the axes.

Parameters
----------
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
    Display the image in `X` to current axes.  `X` may be an
    array or a PIL image. If `X` is an array, it
    can have the following shapes and types:

    - MxN -- values to be mapped (float or int)
    - MxNx3 -- RGB (float or uint8)
    - MxNx4 -- RGBA (float or uint8)

    The value for each component of MxNx3 and MxNx4 float arrays
    should be in the range 0.0 to 1.0. MxN arrays are mapped
    to colors based on the `norm` (mapping scalar to scalar)
    and the `cmap` (mapping the normed scalar to a color).

Replace transparency in PNG images with white background

It appears that your command is correct so the problem might be due to missing support for PNG (). You can check with convert -list configure or just try the following:

sudo yum install libpng libpng-devel

jQuery and AJAX response header

The unfortunate truth about AJAX and the 302 redirect is that you can't get the headers from the return because the browser never gives them to the XHR. When a browser sees a 302 it automatically applies the redirect. In this case, you would see the header in firebug because the browser got it, but you would not see it in ajax, because the browser did not pass it. This is why the success and the error handlers never get called. Only the complete handler is called.

http://www.checkupdown.com/status/E302.html

The 302 response from the Web server should always include an alternative URL to which redirection should occur. If it does, a Web browser will immediately retry the alternative URL. So you never actually see a 302 error in a Web browser

Here are some stackoverflow posts on the subject. Some of the posts describe hacks to get around this issue.

How to manage a redirect request after a jQuery Ajax call

Catching 302 FOUND in JavaScript

HTTP redirect: 301 (permanent) vs. 302 (temporary)

How to add row of data to Jtable from values received from jtextfield and comboboxes

Peeskillet's lame tutorial for working with JTables in Netbeans GUI Builder

  • Set the table column headers
    1. Highglight the table in the design view then go to properties pane on the very right. Should be a tab that says "Properties". Make sure to highlight the table and not the scroll pane surrounding it, or the next step wont work
    2. Click on the ... button to the right of the property model. A dialog should appear.
    3. Set rows to 0, set the number of columns you want, and their names.
  • Add a button to the frame somwhere,. This button will be clicked when the user is ready to submit a row

    1. Right-click on the button and select Events -> Action -> actionPerformed
    2. You should see code like the following auto-generated

      private void jButton1ActionPerformed(java.awt.event.ActionEvent) {}
      
  • The jTable1 will have a DefaultTableModel. You can add rows to the model with your data

    private void jButton1ActionPerformed(java.awt.event.ActionEvent) {
        String data1 = something1.getSomething();
        String data2 = something2.getSomething();
        String data3 = something3.getSomething();
        String data4 = something4.getSomething();
    
        Object[] row = { data1, data2, data3, data4 };
    
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
    
        model.addRow(row);
    
        // clear the entries.
    }
    

So for every set of data like from a couple text fields, a combo box, and a check box, you can gather that data each time the button is pressed and add it as a row to the model.

How to indent HTML tags in Notepad++

Step 1: Open plugin manager in notepad++

Plugins -> Plugin Manager -> Show Plugin Manager.

Step 2:install XML Tool plugin

Search "XML TOOLS" from the "Available" option then click in install.

Now you can use shortcut key CTRL+ALT+SHIFT+B to indent the code.

401 Unauthorized: Access is denied due to invalid credentials

I faced similar issue.

The folder was shared and Authenticated Users permission was provided, which solved my issue.

correct way of comparing string jquery operator =

First of all you should use double "==" instead of "=" to compare two values. Using "=" You assigning value to variable in this case "somevar"

Java: How can I compile an entire directory structure of code ?

The already existing answers seem to only concern oneself with the *.java files themselves and not how to easily do it with library files that might be needed for the build.

A nice one-line situation which recursively gets all *.java files as well as includes *.jar files necessary for building is:

javac -cp ".:lib/*" -d bin $(find ./src/* | grep .java)

Here the bin file is the destination of class files, lib (and potentially the current working directory) contain the library files and all the java files in the src directory and beneath are compiled.

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

SwiftUI

in SwiftUI, there is a View called Divider that is perfectly matched for this. You can add it below any view by embedding them into a simple VStack:

VStack {
    Text("This could be any View")
    Divider()
}

How do I add the Java API documentation to Eclipse?

Old question, but I had current problems with this issue. So I provide you my solution. Now the sources and javadocs are inside the jdk. So, unzip your jdk version.You can see that contanins a "src.zip" file. Here are your needed sources and doc files. Follow the path: Window->Preferences->Java->Installed JREs-> select your jre/jrd and press "Edit" Select all .jar files, and press Source Attachement. Select the "External File..." button, and point it to src.zip file.

Maibe a restart to Eclipse is needed. (normally not) Now you should see the docs, and also the sources for the classes from jdk.

How do I execute code AFTER a form has loaded?

I had the same problem, and solved it as follows:

Actually I want to show Message and close it automatically after 2 second. For that I had to generate (dynamically) simple form and one label showing message, stop message for 1500 ms so user read it. And Close dynamically created form. Shown event occur After load event. So code is

Form MessageForm = new Form();
MessageForm.Shown += (s, e1) => { 
    Thread t = new Thread(() => Thread.Sleep(1500)); 
    t.Start(); 
    t.Join(); 
    MessageForm.Close(); 
};

How do I create a GUI for a windows application using C++?

I have used wxWidgets for small project and I loved it. Qt is another good choice but for commercial use you would probably need to buy a licence. If you write in C++ don't use Win32 API as you will end up making it object oriented. This is not easy and time consuming. Also Win32 API has too many macros and feels over complicated for what it offers.

How much RAM is SQL Server actually using?

Go to management studio and run sp_helpdb <db_name>, it will give detailed disk usage for the specified database. Running it without any parameter values will list high level information for all databases in the instance.

Python - Move and overwrite files and folders

I had a similar problem. I wanted to move files and folder structures and overwrite existing files, but not delete anything which is in the destination folder structure.

I solved it by using os.walk(), recursively calling my function and using shutil.move() on files which I wanted to overwrite and folders which did not exist.

It works like shutil.move(), but with the benefit that existing files are only overwritten, but not deleted.

import os
import shutil

def moverecursively(source_folder, destination_folder):
    basename = os.path.basename(source_folder)
    dest_dir = os.path.join(destination_folder, basename)
    if not os.path.exists(dest_dir):
        shutil.move(source_folder, destination_folder)
    else:
        dst_path = os.path.join(destination_folder, basename)
        for root, dirs, files in os.walk(source_folder):
            for item in files:
                src_path = os.path.join(root, item)
                if os.path.exists(dst_file):
                    os.remove(dst_file)
                shutil.move(src_path, dst_path)
            for item in dirs:
                src_path = os.path.join(root, item)
                moverecursively(src_path, dst_path)

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I needed a package from github that was written in typscript. I did a git pull of the most recent version from the master branch into the root of my main project. I then went into the directory and did an npm install so that the gulp commands would work that generates ES5 modules. Anyway, to make the long story short, my build process was trying to build files from this new folder so I had to move it out of my root. This was causing these same errors.

How to code a BAT file to always run as admin mode?

The other answer requires that you enter the Administrator account password. Also, running under an account in the Administrator Group is not the same as run as administrator see: UAC on Wikipedia

Windows 7 Instructions

In order to run as an Administrator, create a shortcut for the batch file.

  1. Right click the batch file and click copy
  2. Navigate to where you want the shortcut
  3. Right click the background of the directory
  4. Select Paste Shortcut

Then you can set the shortcut to run as administrator:

  1. Right click the shortcut
  2. Choose Properties
  3. In the Shortcut tab, click Advanced
  4. Select the checkbox "Run as administrator"
  5. Click OK, OK

Now when you double click the shortcut it will prompt you for UAC confirmation and then Run as administrator (which as I said above is different than running under an account in the Administrator Group)

Check the screenshot below

Screenshot

Note: When you do so to Run As Administrator, the current directory (path) will not be same as the bat file. This can cause some problems in many cases that the bat file refer to relative files beside it. For example, in my Windows 7 the cur dir will be SYSTEM32 instead of bat file location! To workaround it, you should use

cd "%~dp0"

or better

pushd "%~dp0"

to ensure cur dir is at the same path where the bat file is.

How to compare two maps by their values

If you want to compare two Maps then, below code may help you

(new TreeMap<String, Object>(map1).toString().hashCode()) == new TreeMap<String, Object>(map2).toString().hashCode()

What's the difference between SHA and AES encryption?

SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.

AES Reference

How to run test methods in specific order in JUnit4?

The (as yet unreleased) change https://github.com/junit-team/junit/pull/386 introduces a @SortMethodsWith. https://github.com/junit-team/junit/pull/293 at least made the order predictable without that (in Java 7 it can be quite random).

Generating random numbers with normal distribution in Excel

About the recalculation:

You can keep your set of random values from changing every time you make an adjustment, by adjusting the automatic recalculation, to: manual recalculate. (Re)calculations are then only done when you press F9. Or shift F9.

See this link (though for older excel version than the current 2013) for some info about it: https://support.office.com/en-us/article/Change-formula-recalculation-iteration-or-precision-73fc7dac-91cf-4d36-86e8-67124f6bcce4.

How to do a Postgresql subquery in select clause with join in from clause like SQL Server?

I know this is old, but since Postgresql 9.3 there is an option to use a keyword "LATERAL" to use RELATED subqueries inside of JOINS, so the query from the question would look like:

SELECT 
    name, author_id, count(*), t.total
FROM
    names as n1
    INNER JOIN LATERAL (
        SELECT 
            count(*) as total
        FROM 
            names as n2
        WHERE 
            n2.id = n1.id
            AND n2.author_id = n1.author_id
    ) as t ON 1=1
GROUP BY 
    n1.name, n1.author_id

Excel function to get first word from sentence in other cell

Generic solution extracting the first "n" words of refcell string into a new string of "x" number of characters

=LEFT(SUBSTITUTE(***refcell***&" "," ",REPT(" ",***x***),***n***),***x***)

Assuming A1 has text string to extract, the 1st word extracted to a 15 character result

=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",15),1),15)

This would result in "Toronto" being returned to a 15 character string. 1st 2 words extracted to a 30 character result

=LEFT(SUBSTITUTE(A1&" "," ",REPT(" ",30),2),30)

would result in "Toronto is" being returned to a 30 character string

How do I completely rename an Xcode project (i.e. inclusive of folders)?

To add to @luke-west 's excellent answer:

When using CocoaPods

After step 2:

  1. Quit XCode.
  2. In the master folder, rename OLD.xcworkspace to NEW.xcworkspace.

After step 4:

  1. In XCode: choose and edit Podfile from the project navigator. You should see a target clause with the OLD name. Change it to NEW.
  2. Quit XCode.
  3. In the project folder, delete the OLD.podspec file.
  4. rm -rf Pods/
  5. Run pod install.
  6. Open XCode.
  7. Click on your project name in the project navigator.
  8. In the main pane, switch to the Build Phases tab.
  9. Under Link Binary With Libraries, look for libPods-OLD.a and delete it.
  10. If you have an objective-c Bridging header go to Build settings and change the location of the header from OLD/OLD-Bridging-Header.h to NEW/NEW-Bridging-Header.h
  11. Clean and run.

Some projects cannot be imported because they already exist in the workspace error in Eclipse

It was happened to me when

I delete project from eclipse Project Explorer and not checked the remove content from disk.

Next time when I tried to import same project in workspace then got same problem.

To solve I just did FYI work that every kid can do :)

So How I solved it:

  1. Cut Ctrl + x myProject folder from eclipse workspace to other location ie Desktop
  2. Right Click Navigator (you can get it from Window > Show View > Navigator) and Refresh (it will prompt following dialog) enter image description here
  3. Just click Yes button and move your project folder back to eclipse workspace directory
  4. Import again!
  5. Now Rock 'n' Role

What is size_t in C?

The manpage for types.h says:

size_t shall be an unsigned integer type

"use database_name" command in PostgreSQL

Use this commad when first connect to psql

=# psql <databaseName> <usernamePostgresql>

Grid of responsive squares

The accepted answer is great, however this can be done with flexbox.

Here's a grid system written with BEM syntax that allows for 1-10 columns to be displayed per row.

If there the last row is incomplete (for example you choose to show 5 cells per row and there are 7 items), the trailing items will be centered horizontally. To control the horizontal alignment of the trailing items, simply change the justify-content property under the .square-grid class.

.square-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.square-grid__cell {
  background-color: rgba(0, 0, 0, 0.03);
  box-shadow: 0 0 0 1px black;
  overflow: hidden;
  position: relative;
}

.square-grid__content {
  left: 0;
  position: absolute;
  top: 0;
}

.square-grid__cell:after {
  content: '';
  display: block;
  padding-bottom: 100%;
}

// Sizes – Number of cells per row

.square-grid__cell--10 {
  flex-basis: 10%;
}

.square-grid__cell--9 {
  flex-basis: 11.1111111%;
}

.square-grid__cell--8 {
  flex-basis: 12.5%;
}

.square-grid__cell--7 {
  flex-basis: 14.2857143%;
}

.square-grid__cell--6 {
  flex-basis: 16.6666667%;
}

.square-grid__cell--5 {
  flex-basis: 20%;
}

.square-grid__cell--4 {
  flex-basis: 25%;
}

.square-grid__cell--3 {
  flex-basis: 33.333%;
}

.square-grid__cell--2 {
  flex-basis: 50%;
}

.square-grid__cell--1 {
  flex-basis: 100%;
}

_x000D_
_x000D_
.square-grid {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.square-grid__cell {_x000D_
  background-color: rgba(0, 0, 0, 0.03);_x000D_
  box-shadow: 0 0 0 1px black;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.square-grid__content {_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
.square-grid__cell:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  padding-bottom: 100%;_x000D_
}_x000D_
_x000D_
// Sizes – Number of cells per row_x000D_
_x000D_
.square-grid__cell--10 {_x000D_
  flex-basis: 10%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--9 {_x000D_
  flex-basis: 11.1111111%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--8 {_x000D_
  flex-basis: 12.5%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--7 {_x000D_
  flex-basis: 14.2857143%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--6 {_x000D_
  flex-basis: 16.6666667%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--5 {_x000D_
  flex-basis: 20%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--4 {_x000D_
  flex-basis: 25%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--3 {_x000D_
  flex-basis: 33.333%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--2 {_x000D_
  flex-basis: 50%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--1 {_x000D_
  flex-basis: 100%;_x000D_
}
_x000D_
<div class='square-grid'>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: https://jsfiddle.net/patrickberkeley/noLm1r45/3/

This is tested in FF and Chrome.

if-else statement inside jsx: ReactJS

Just Tried that:

return(
  <>
    {
      main-condition-1 && 
      main-condition-2 &&
      (sub-condition ? (<p>Hi</p>) : (<p>Hello</p>))
     }
  </>
)

Let me know what you guys think!!!

Amazon S3 upload file and get URL

Similarly if you want link through s3Client you can use below.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

jQuery Toggle Text?

Modifying my answer from your other question, I would do this:

$(function() {
 $("#show-background").click(function () {
  var c = $("#content-area");
  var o = (c.css('opacity') == 0) ? 1 : 0;
  var t = (o==1) ? 'Show Background' : 'Show Text';
  c.animate({opacity: o}, 'slow');
  $(this).text(t);
 });
});

Find the closest ancestor element that has a specific class

Based on the the8472 answer and https://developer.mozilla.org/en-US/docs/Web/API/Element/matches here is cross-platform 2017 solution:

if (!Element.prototype.matches) {
    Element.prototype.matches =
        Element.prototype.matchesSelector ||
        Element.prototype.mozMatchesSelector ||
        Element.prototype.msMatchesSelector ||
        Element.prototype.oMatchesSelector ||
        Element.prototype.webkitMatchesSelector ||
        function(s) {
            var matches = (this.document || this.ownerDocument).querySelectorAll(s),
                i = matches.length;
            while (--i >= 0 && matches.item(i) !== this) {}
            return i > -1;
        };
}

function findAncestor(el, sel) {
    if (typeof el.closest === 'function') {
        return el.closest(sel) || null;
    }
    while (el) {
        if (el.matches(sel)) {
            return el;
        }
        el = el.parentElement;
    }
    return null;
}

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

You can do the following to install java 8 on your machine. First get the link of tar that you want to install. You can do this by:

  1. go to java downloads page and find the appropriate download.
  2. Accept the license agreement and download it.
  3. In the download page in your browser right click and copy link address.

Then in your terminal:

$ cd /tmp
$ wget http://download.oracle.com/otn-pub/java/jdk/8u74-b02/jdk-8u74-linux-x64.tar.gz\?AuthParam\=1458001079_a6c78c74b34d63befd53037da604746c
$ tar xzf jdk-8u74-linux-x64.tar.gz?AuthParam=1458001079_a6c78c74b34d63befd53037da604746c
$ sudo mv jdk1.8.0_74 /opt
$ cd /opt/jdk1.8.0_74/
$ sudo update-alternatives --install /usr/bin/java java /opt/jdk1.8.0_91/bin/java 2
$ sudo update-alternatives --config java // select version
$ sudo update-alternatives --install /usr/bin/jar jar /opt/jdk1.8.0_91/bin/jar 2
$ sudo update-alternatives --install /usr/bin/javac javac /opt/jdk1.8.0_91/bin/javac 2
$ sudo update-alternatives --set jar /opt/jdk1.8.0_91/bin/jar
$ sudo update-alternatives --set javac /opt/jdk1.8.0_74/bin/javac
$ java -version // you should have the updated java

C fopen vs open

open() will be called at the end of each of the fopen() family functions. open() is a system call and fopen() are provided by libraries as a wrapper functions for user easy of use

How to make CREATE OR REPLACE VIEW work in SQL Server?

SQL Server 2016 Answer

With SQL Server 2016 you can now do (MSDN Source):

DROP VIEW IF EXISTS dbo.MyView

Text file with 0D 0D 0A line breaks

Just saying, this is also the value (kind of...) that is returned from php upon:

<?php var_dump(urlencode(PHP_EOL)); ?> 
    // Prints: string '%0D%0A' (length=6)-- used in 5.4.24 at least

How does the SQL injection from the "Bobby Tables" XKCD comic work?

A single quote is the start and end of a string. A semicolon is the end of a statement. So if they were doing a select like this:

Select *
From Students
Where (Name = '<NameGetsInsertedHere>')

The SQL would become:

Select *
From Students
Where (Name = 'Robert'); DROP TABLE STUDENTS; --')
--             ^-------------------------------^

On some systems, the select would get ran first followed by the drop statement! The message is: DONT EMBED VALUES INTO YOUR SQL. Instead use parameters!

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

As John Saunders says, check if the class/property names matches the capital casing of your XML. If this isn't the case, the problem will also occur.

Change old commit message on Git

Just wanted to provide a different option for this. In my case, I usually work on my individual branches then merge to master, and the individual commits I do to my local are not that important.

Due to a git hook that checks for the appropriate ticket number on Jira but was case sensitive, I was prevented from pushing my code. Also, the commit was done long ago and I didn't want to count how many commits to go back on the rebase.

So what I did was to create a new branch from latest master and squash all commits from problem branch into a single commit on new branch. It was easier for me and I think it's good idea to have it here as future reference.

From latest master:

git checkout -b new-branch

Then

git merge --squash problem-branch
git commit -m "new message" 

Referece: https://github.com/rotati/wiki/wiki/Git:-Combine-all-messy-commits-into-one-commit-before-merging-to-Master-branch

Which characters need to be escaped in HTML?

The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):

Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.

For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.

These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "), or (iv) unquoted — with the following restrictions:

... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

How to use jQuery in chrome extension?

Apart from the solutions already mentioned, you can also download jquery.min.js locally and then use it -

For downloading -

wget "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"

manifest.json -

"content_scripts": [
   {
    "js": ["/path/to/jquery.min.js", ...]
   }
],

in html -

<script src="/path/to/jquery.min.js"></script>

Reference - https://developer.chrome.com/extensions/contentSecurityPolicy

Why does flexbox stretch my image rather than retaining aspect ratio?

I faced the same issue with a Foundation menu. align-self: center; didn't work for me.

My solution was to wrap the image with a <div style="display: inline-table;">...</div>

pip installs packages successfully, but executables not found from command line

check your $PATH

tox has a command line mode:

audrey:tests jluc$ pip list | grep tox
tox (2.3.1)

where is it?

(edit: the 2.7 stuff doesn't matter much here, sub in any 3.x and pip's behaving pretty much the same way)

audrey:tests jluc$ which tox
/opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin/tox

and what's in my $PATH?

audrey:tests jluc$ echo $PATH
/opt/chefdk/bin:/opt/chefdk/embedded/bin:/opt/local/bin:..../opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin...

Notice the /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin? That's what allows finding my pip-installed stuff

Now, to see where things are from Python, try doing this (substitute rosdep for tox).

$python
>>> import tox
>>> tox.__file__

that prints out:

'/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/tox/__init__.pyc'

Now, cd to the directory right above lib in the above. Do you see a bin directory? Do you see rosdep in that bin? If so try adding the bin to your $PATH.

audrey:2.7 jluc$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7
audrey:2.7 jluc$ ls -1

output:

Headers
Python
Resources
bin
include
lib
man
share

Vertical rulers in Visual Studio Code

Visual Studio Code: Version 1.14.2 (1.14.2)

  1. Press Shift + Command + P to open panel
    • For non-macOS users, press Ctrl+P
  2. Enter "settings.json" to open setting files.
  3. At default setting, you can see this:

    // Columns at which to show vertical rulers
    "editor.rulers": [],
    

    This means the empty array won't show the vertical rulers.

  4. At right window "user setting", add the following:

    "editor.rulers": [140]

Save the file, and you will see the rulers.

Postgresql : syntax error at or near "-"

Wrap it in double quotes

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

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

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

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />
</a>

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />
</a>

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

Mongoose delete array element in document and save

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

How to get last N records with activerecord?

In my rails (rails 4.2) project, I use

Model.last(10) # get the last 10 record order by id

and it works.

What is the difference between a Docker image and a container?

A container is just an executable binary that is to be run by the host OS under a set of restrictions that are preset using an application (e.g., Docker) that knows how to tell the OS which restrictions to apply.

The typical restrictions are process-isolation related, security related (like using SELinux protection) and system-resource related (memory, disk, CPU, and networking).

Until recently, only kernels in Unix-based systems supported the ability to run executables under strict restrictions. That's why most container talk today involves mostly Linux or other Unix distributions.

Docker is one of those applications that knows how to tell the OS (Linux mostly) what restrictions to run an executable under. The executable is contained in the Docker image, which is just a tarfile. That executable is usually a stripped-down version of a Linux distribution's User space (Ubuntu, CentOS, Debian, etc.) preconfigured to run one or more applications within.

Though most people use a Linux base as the executable, it can be any other binary application as long as the host OS's kernel can run it (see creating a simple base image using scratch). Whether the binary in the Docker image is an OS User space or simply an application, to the OS host it is just another process, a contained process ruled by preset OS boundaries.

Other applications that, like Docker, can tell the host OS which boundaries to apply to a process while it is running, include LXC, libvirt, and systemd. Docker used to use these applications to indirectly interact with the Linux OS, but now Docker interacts directly with Linux using its own library called "libcontainer".

So containers are just processes running in a restricted mode, similar to what chroot used to do.

IMO, what sets Docker apart from any other container technology is its repository (Docker Hub) and their management tools which makes working with containers extremely easy.

See Docker (software).

Is Visual Studio Community a 30 day trial?

In my case, I already was signed in. So I had to sign out and sign in again.

In spanish Cerrar Sesion is sign out.

screenshot

How to convert unix timestamp to calendar date moment.js

moment(timestamp).format('''any format''')

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Disabling tab focus on form elements

$('.tabDisable').on('keydown', function(e)
{ 
  if (e.keyCode == 9)  
  {
    e.preventDefault();
  }
});

Put .tabDisable to all tab disable DIVs Like

<div class='tabDisable'>First Div</div> <!-- Tab Disable Div -->
<div >Second Div</div> <!-- No Tab Disable Div -->
<div class='tabDisable'>Third Div</div> <!-- Tab Disable Div -->

Edit existing excel workbooks and sheets with xlrd and xlwt

As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils module (Thanks Oliver)

Here is the proper way to do it:

#xlrd, xlutils and xlwt modules need to be installed.  
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy

rb = open_workbook("names.xls")
wb = copy(rb)

s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')

This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.

How to detect the OS from a Bash script?

In bash, use $OSTYPE and $HOSTTYPE, as documented; this is what I do. If that is not enough, and if even uname or uname -a (or other appropriate options) does not give enough information, there’s always the config.guess script from the GNU project, made exactly for this purpose.

How long will my session last?

In general you can say session.gc_maxlifetime specifies the maximum lifetime since the last change of your session data (not the last time session_start was called!). But PHP’s session handling is a little bit more complicated.

Because the session data is removed by a garbage collector that is only called by session_start with a probability of session.gc_probability devided by session.gc_divisor. The default values are 1 and 100, so the garbage collector is only started in only 1% of all session_start calls. That means even if the the session is already timed out in theory (the session data had been changed more than session.gc_maxlifetime seconds ago), the session data can be used longer than that.

Because of that fact I recommend you to implement your own session timeout mechanism. See my answer to How do I expire a PHP session after 30 minutes? for more details.

Can't import Numpy in Python

Have you installed it?

On debian/ubuntu:

aptitude install python-numpy

On windows:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems:

http://sourceforge.net/projects/numpy/files/NumPy/

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

Is it possible to make abstract classes in Python?

Use the abc module to create abstract classes. Use the abstractmethod decorator to declare a method abstract, and declare a class abstract using one of three ways, depending upon your Python version.

In Python 3.4 and above, you can inherit from ABC. In earlier versions of Python, you need to specify your class's metaclass as ABCMeta. Specifying the metaclass has different syntax in Python 3 and Python 2. The three possibilities are shown below:

# Python 3.4+
from abc import ABC, abstractmethod
class Abstract(ABC):
    @abstractmethod
    def foo(self):
        pass
# Python 3.0+
from abc import ABCMeta, abstractmethod
class Abstract(metaclass=ABCMeta):
    @abstractmethod
    def foo(self):
        pass
# Python 2
from abc import ABCMeta, abstractmethod
class Abstract:
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        pass

Whichever way you use, you won't be able to instantiate an abstract class that has abstract methods, but will be able to instantiate a subclass that provides concrete definitions of those methods:

>>> Abstract()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Abstract with abstract methods foo
>>> class StillAbstract(Abstract):
...     pass
... 
>>> StillAbstract()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class StillAbstract with abstract methods foo
>>> class Concrete(Abstract):
...     def foo(self):
...         print('Hello, World')
... 
>>> Concrete()
<__main__.Concrete object at 0x7fc935d28898>

Entityframework Join using join method and lambdas

Generally i prefer the lambda syntax with LINQ, but Join is one example where i prefer the query syntax - purely for readability.

Nonetheless, here is the equivalent of your above query (i think, untested):

var query = db.Categories         // source
   .Join(db.CategoryMaps,         // target
      c => c.CategoryId,          // FK
      cm => cm.ChildCategoryId,   // PK
      (c, cm) => new { Category = c, CategoryMaps = cm }) // project result
   .Select(x => x.Category);  // select result

You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.

How to center align the ActionBar title in Android?

My solution will be to keep text part of tool bar separate, to define style and say, center or whichever alignment. It can be done in XML itself. Some paddings can be specified after doing calculations when you have actions that are visible always. I have moved two attributes from toolbar to its child TextView. This textView can be provided id to be accessed from fragments.

    <?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" >
            <!--android:theme="@style/defaultTitleTheme"
            app:titleTextColor="@color/white"-->
            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:paddingStart="@dimen/icon_size"
                android:text="@string/title_home"
                style="@style/defaultTitleTheme"
                tools:ignore="RtlSymmetry" />
        </androidx.appcompat.widget.Toolbar>
    </com.google.android.material.appbar.AppBarLayout>

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Submit form without page reloading

You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.

I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.

How to force view controller orientation in iOS 8?

I have the same problem and waste so many time for it. So now I have my solution. My app setting is just support portrait only.However, some screens into my app need have landscape only.I fix it by have a variable isShouldRotate at AppDelegate. And the function at AppDelegate:

func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int {
    if isShouldRotate == true {
        return Int(UIInterfaceOrientationMask.Landscape.rawValue)
    }
    return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}

And finally when a ViewControllerA need landscape state. Just do that: before push/present to ViewControllerA assign isShouldRotate to true. Don't forget when pop/dismiss that controller assign isShouldRotate to false at viewWillDisappear.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Instead of "right click"....start your session (once you're in the command prompt window) by keying Alt/SpaceBar. That will open the Command Prompt window menu and you'll see your familiar, underlined keyboard command shortcuts, just like in Windows GUI.

Good luck!

node.js vs. meteor.js what's the difference?

Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.

Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).

So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...

In Tkinter is there any way to make a widget not visible?

For someone who hate OOP like me (This is based on Bryan Oakley's answer)

import tkinter as tk

def show_label():
    label1.lift()

def hide_label():
    label1.lower()

root = tk.Tk()
frame1 = tk.Frame(root)
frame1.pack()

label1 = tk.Label(root, text="Hello, world")
label1.pack(in_=frame1)

button1 = tk.Button(root, text="Click to hide label",command=hide_label)
button2 = tk.Button(root, text="Click to show label", command=show_label)
button1.pack(in_=frame1)
button2.pack(in_=frame1)

root.mainloop()

SOAP Action WSDL

the service have 4 operations: 1. GetServiceDetails 2. GetArrivalBoard 3. GetDepartureBoard 4. GetArrivalDepartureBoard

Implementation of web service

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Here is where you went wrong:

this.result = http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result.json());

it should be:

http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result);

or

http.get('friends.json')
                  .subscribe(result => this.result =result.json());

You have made two mistakes:

1- You assigned the observable itself to this.result. When you actually wanted to assign the list of friends to this.result. The correct way to do it is:

  • you subscribe to the observable. .subscribe is the function that actually executes the observable. It takes three callback parameters as follow:

    .subscribe(success, failure, complete);

for example:

.subscribe(
    function(response) { console.log("Success Response" + response)},
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
);

Usually, you take the results from the success callback and assign it to your variable. the error callback is self explanatory. the complete callback is used to determine that you have received the last results without any errors. On your plunker, the complete callback will always be called after either the success or the error callback.

2- The second mistake, you called .json() on .map(res => res.json()), then you called it again on the success callback of the observable. .map() is a transformer that will transform the result to whatever you return (in your case .json()) before it's passed to the success callback you should called it once on either one of them.

PostgreSQL, checking date relative to "today"

You could also check using the age() function

select * from mytable where age( mydate, now() ) > '1 year';

age() wil return an interval.

For example age( '2015-09-22', now() ) will return -1 years -7 days -10:56:18.274131

See postgresql documentation

How do I find Waldo with Mathematica?

I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.

The two challenges with training a Waldo classifier would be:

  1. Determining the right image feature transform. This is where @Heike's answer would be useful: a red filter and a stripped pattern detector (e.g., wavelet or DCT decomposition) would be a good way to turn raw pixels into a format that the classification algorithm could learn from. A block-based decomposition that assesses all subsections of the image would also be required ... but this is made easier by the fact that Waldo is a) always roughly the same size and b) always present exactly once in each image.
  2. Obtaining enough training examples. SVMs work best with at least 100 examples of each class. Commercial applications of boosting (e.g., the face-focusing in digital cameras) are trained on millions of positive and negative examples.

A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!

However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!

Restrict varchar() column to specific values?

Have you already looked at adding a check constraint on that column which would restrict values? Something like:

CREATE TABLE SomeTable
(
   Id int NOT NULL,
   Frequency varchar(200),
   CONSTRAINT chk_Frequency CHECK (Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly'))
)

error TS2339: Property 'x' does not exist on type 'Y'

I'm no expert in Typescript, but I think the main problem is the way of accessing data. Seeing how you described your Images interface, you can define any key as a String.

When accessing a property, the "dot" syntax (images.main) supposes, I think, that it already exists. I had such problems without Typescript, in "vanilla" Javascript, where I tried to access data as:

return json.property[0].index

where index was a variable. But it interpreted index, resulting in a:

cannot find property "index" of json.property[0]

And I had to find a workaround using your syntax:

return json.property[0][index]

It may be your only option there. But, once again, I'm no Typescript expert, if anyone knows a better solution / explaination about what happens, feel free to correct me.

mysql stored-procedure: out parameter

If you are calling from within Stored Procedure don't use @. In my case it returns 0

CALL SP_NAME(L_OUTPUT_PARAM)

Defining TypeScript callback type

I just found something in the TypeScript language specification, it's fairly easy. I was pretty close.

the syntax is the following:

public myCallback: (name: type) => returntype;

In my example, it would be

class CallbackTest
{
    public myCallback: () => void;

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

'git status' shows changed files, but 'git diff' doesn't

You did not really ask an actual question, but since this is a general use case I'm using quite often here's what I do. You may try this yourself and see if the error persists.

My assumption on your use case:

You have an existing directory containing files and directories and now want to convert it into a Git repository that is cloned from some place else without changing any data in your current directory.

There are really two ways.

Clone repo - mv .git - git reset --hard

This method is what you did - to clone the existing repository into an empty directory, then move the .git directory into the destination directory. To work without problems, this generally requires you then to run

git reset --hard

However, that would change the state of files in your current directory. You can try this on a full copy/rsync of your directory and study what changes. At least afterwards you should no longer see discrepancies between git log and status.

Init new repository - point to origin

The second is less disturbing: cd into your destination, and start a new repository with

git init

Then you tell that new repository, that it has an ancestor some place else:

git remote add origin original_git_repo_path

Then safely

git fetch origin master

to copy over the data without changing your local files. Everything should be fine now.

I always recommend the second way for being less error-prone.

how to call a onclick function in <a> tag?

Fun! There are a few things to tease out here:

  • $leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
  • Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
  • <a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: <a href="http://www.google.com">Google homepage</a>.
  • You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
  • Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>.
  • Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
  • Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ....
  • Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: <a href="http://www.google.com" target="_blank">Google homepage</a>.

Hope those are useful.

shuffling/permutating a DataFrame in pandas

From the docs use sample():

In [79]: s = pd.Series([0,1,2,3,4,5])

# When no arguments are passed, returns 1 row.
In [80]: s.sample()
Out[80]: 
0    0
dtype: int64

# One may specify either a number of rows:
In [81]: s.sample(n=3)
Out[81]: 
5    5
2    2
4    4
dtype: int64

# Or a fraction of the rows:
In [82]: s.sample(frac=0.5)
Out[82]: 
5    5
4    4
1    1
dtype: int64

Webdriver Screenshot

I understand you are looking for an answer in python, but here is how one would do it in ruby..

http://watirwebdriver.com/screenshots/

If that only works by saving in current directory only.. I would first assign the image to a variable and then save that variable to disk as a PNG file.

eg:

 image = b.screenshot.png

 File.open("testfile.png", "w") do |file|
  file.puts "#{image}"
 end

where b is the browser variable used by webdriver. i have the flexibility to provide an absolute or relative path in "File.open" so I can save the image anywhere.

Java Set retain order?

Iterator returned by Set is not suppose to return data in Ordered way. See this Two java.util.Iterators to the same collection: do they have to return elements in the same order?

How do I set a column value to NULL in SQL Server Management Studio?

Use This:

Update Table Set Column = CAST(NULL As Column Type) where Condition

Like This:

Update News Set Title = CAST(NULL As nvarchar(100)) Where ID = 50

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

You can find the codes in the DB2 Information Center. Here's a definition of the -302 from the z/OS Information Center:

THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE

On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW, if it's negative, you'll look for SQLxxxxN, where xxxx is the code you're looking up.

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

Here's my take experience with E7 async/await:

In case you have an async helperFunction() called from your test... (one explicilty with the ES7 async keyword, I mean)

? make sure, you call that as await helperFunction(whateverParams) (well, yeah, naturally, once you know...)

And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:

it('my test', async () => { ...

How many spaces will Java String.trim() remove?

Example of Java trim() removing spaces:

public class Test
{
    public static void main(String[] args)
    {
        String str = "\n\t This is be trimmed.\n\n";

        String newStr = str.trim();     //removes newlines, tabs and spaces.

        System.out.println("old = " + str);
        System.out.println("new = " + newStr);
    }
}

OUTPUT

old = 
 This is a String.


new = This is a String.

How do I get a list of installed CPAN modules?

perldoc -q installed

claims that cpan -l will do the trick, however it's not working for me. The other option:

cpan -a

does spit out a nice list of installed packages and has the nice side effect of writing them to a file.

How to display an unordered list in two columns?

In updateColumns() need if (column >= columns.length) rather than if (column > columns.length) to list all elements (C is skipped for example) so:

function updateColumns(){
    column = 0;
    columnItems.each(function(idx, el){
        if (column >= columns.length){
            column = 0;
        }
        console.log(column, el, idx);
        $(columns.get(column)).append(el);
        column += 1;
    });
}

http://jsfiddle.net/e2vH9/1/

Converting a string to JSON object

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

link:-

http://api.jquery.com/jQuery.parseJSON/

Easy way to print Perl array? (with a little formatting)

You can simply print it.

@a = qw(abc def hij);

print "@a";

You will got:

abc def hij

How to post ASP.NET MVC Ajax form using JavaScript rather than submit button

Simply place normal button indide Ajax.BeginForm and on click find parent form and normal submit. Ajax form in Razor:

@using (Ajax.BeginForm("AjaxPost", "Home", ajaxOptions))
    {        
        <div class="form-group">
            <div class="col-md-12">

                <button class="btn btn-primary" role="button" type="button" onclick="submitParentForm($(this))">Submit parent from Jquery</button>
            </div>
        </div>
    }

and Javascript:

function submitParentForm(sender) {
    var $formToSubmit = $(sender).closest('form');

    $formToSubmit.submit();
}

Who sets response content-type in Spring MVC (@ResponseBody)

I found solution for Spring 3.1. with using @ResponseBody annotation. Here is example of controller using Json output:

@RequestMapping(value = "/getDealers", method = RequestMethod.GET, 
produces = "application/json; charset=utf-8")
@ResponseBody
public String sendMobileData() {

}

What is the difference between Cloud Computing and Grid Computing?

Cloud Computing is a large group of interconnected computers.The data are hidden form the user. Grid computing is more than one computers interconnected to resolve the problem.grid computing is worked in cloud computing.

How do I convert a string to a double in Python?

Be aware that if your string number contains more than 15 significant digits float(s) will round it.In those cases it is better to use Decimal

Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info

Setting focus on an HTML input box on page load

This line:

<input type="password" name="PasswordInput"/>

should have an id attribute, like so:

<input type="password" name="PasswordInput" id="PasswordInput"/>

Django 1.7 - makemigrations not detecting changes

First this solution is applicable to those who are facing the same issue during deployment on heroku server, I was facing same issue.

To deploy, there is a mandatory step which is to add django_heroku.settings(locals()) in settings.py file.

Changes: When I changed the above line to django_heroku.settings(locals(), databases=False), it worked flawlessly.

what is trailing whitespace and how can I handle this?

Trailing whitespace is any spaces or tabs after the last non-whitespace character on the line until the newline.

In your posted question, there is one extra space after try:, and there are 12 extra spaces after pass:

>>> post_text = '''\
...             if self.tagname and self.tagname2 in list1:
...                 try: 
...                     question = soup.find("div", "post-text")
...                     title = soup.find("a", "question-hyperlink")
...                     self.list2.append(str(title)+str(question)+url)
...                     current += 1
...                 except AttributeError:
...                     pass            
...             logging.info("%s questions passed, %s questions \
...                 collected" % (count, current))
...             count += 1
...         return self.list2
... '''
>>> for line in post_text.splitlines():
...     if line.rstrip() != line:
...         print(repr(line))
... 
'                try: '
'                    pass            '

See where the strings end? There are spaces before the lines (indentation), but also spaces after.

Use your editor to find the end of the line and backspace. Many modern text editors can also automatically remove trailing whitespace from the end of the line, for example every time you save a file.

Pipenv: Command Not Found

That happens because you are not installing it globally (system wide). For it to be available in your path you need to install it using sudo, like this:

$ sudo pip install pipenv

Insert a background image in CSS (Twitter Bootstrap)

isn't the problem the following line is incorrect as the statement for background-repeat isn't closed before the next statement for display...

background-repeat:no-repeatdisplay: compact;

Shouldn't this be

background-repeat:no-repeat;
display: compact;

adding or removing quotes (in my experience) makes no difference if the URL is correct. Is the path to the image correct? If you give a relative path to a resource in a CSS it's relative to the CSS file, not the file including the CSS.

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Correct way to quit a Qt program?

You can call qApp.exit();. I always use that and never had a problem with it.

If you application is a command line application, you might indeed want to return an exit code. It's completely up to you what the code is.

How do I tar a directory of files and folders without including the directory itself?

 tar -cvzf  tarlearn.tar.gz --remove-files mytemp/*

If the folder is mytemp then if you apply the above it will zip and remove all the files in the folder but leave it alone

 tar -cvzf  tarlearn.tar.gz --remove-files --exclude='*12_2008*' --no-recursion mytemp/*

You can give exclude patterns and also specify not to look into subfolders too

how to wait for first command to finish?

Shell scripts, no matter how they are executed, execute one command after the other. So your code will execute results.sh after the last command of st_new.sh has finished.

Now there is a special command which messes this up: &

cmd &

means: "Start a new background process and execute cmd in it. After starting the background process, immediately continue with the next command in the script."

That means & doesn't wait for cmd to do it's work. My guess is that st_new.sh contains such a command. If that is the case, then you need to modify the script:

cmd &
BACK_PID=$!

This puts the process ID (PID) of the new background process in the variable BACK_PID. You can then wait for it to end:

while kill -0 $BACK_PID ; do
    echo "Process is still active..."
    sleep 1
    # You can add a timeout here if you want
done

or, if you don't want any special handling/output simply

wait $BACK_PID

Note that some programs automatically start a background process when you run them, even if you omit the &. Check the documentation, they often have an option to write their PID to a file or you can run them in the foreground with an option and then use the shell's & command instead to get the PID.

Finding and removing non ascii characters from an Oracle Varchar2

You can try something like following to search for the column containing non-ascii character :

select * from your_table where your_col <> asciistr(your_col);

jQuery Set Selected Option Using Next

$('your_select option:selected').next('option').prop('selected', true)

Android Studio with Google Play Services

Google Play services Integration in Android studio.

Step 1:

SDK manager->Tools Update this

1.Google play services
2.Android Support Repository

Step 2:

chance in build.gradle 
defaultConfig {
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services:4.0.+'
}

Step 3:

 android.manifest.xml
<uses-sdk
        android:minSdkVersion="8" />

Step 4:

Sync project file with grandle.
wait for few minute.

Step 5:

File->Project Structure find error with red bulb images,click on go to add dependencies select your app module.
Save

Please put comment if you have require help. Happy coding.

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

I needed something that I could use to search all my servers using CMS and search by server, DB, schema or table. This is what I found (originally posted by Michael Sorens here: How do I list all tables in all databases in SQL Server in a single result set? ).

SET NOCOUNT ON
DECLARE @AllTables TABLE
        (
         ServerName NVARCHAR(200)
        ,DBName NVARCHAR(200)
        ,SchemaName NVARCHAR(200)
        ,TableName NVARCHAR(200)
        )
DECLARE @SearchSvr NVARCHAR(200)
       ,@SearchDB NVARCHAR(200)
       ,@SearchS NVARCHAR(200)
       ,@SearchTbl NVARCHAR(200)
       ,@SQL NVARCHAR(4000)

SET @SearchSvr = NULL  --Search for Servers, NULL for all Servers
SET @SearchDB = NULL  --Search for DB, NULL for all Databases
SET @SearchS = NULL  --Search for Schemas, NULL for all Schemas
SET @SearchTbl = NULL  --Search for Tables, NULL for all Tables

SET @SQL = 'SELECT @@SERVERNAME
        ,''?''
        ,s.name
        ,t.name
         FROM [?].sys.tables t 
         JOIN sys.schemas s on t.schema_id=s.schema_id 
         WHERE @@SERVERNAME LIKE ''%' + ISNULL(@SearchSvr, '') + '%''
         AND ''?'' LIKE ''%' + ISNULL(@SearchDB, '') + '%''
         AND s.name LIKE ''%' + ISNULL(@SearchS, '') + '%''
         AND t.name LIKE ''%' + ISNULL(@SearchTbl, '') + '%''
      -- AND ''?'' NOT IN (''master'',''model'',''msdb'',''tempdb'',''SSISDB'')
           '
-- Remove the '--' from the last statement in the WHERE clause to exclude system tables

INSERT  INTO @AllTables
        (
         ServerName
        ,DBName
        ,SchemaName
        ,TableName
        )
        EXEC sp_MSforeachdb @SQL
SET NOCOUNT OFF
SELECT  *
FROM    @AllTables
ORDER BY 1,2,3,4

How to push JSON object in to array using javascript

You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-

var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
    console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
    my_json = feed;
    console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
    data.push(my_json);
     //["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
}); 
console.log(data);

Convert Year/Month/Day to Day of Year in Python

Use datetime.timetuple() to convert your datetime object to a time.struct_time object then get its tm_yday property:

from datetime import datetime
day_of_year = datetime.now().timetuple().tm_yday  # returns 1 for January 1st

Android ImageView Fixing Image Size

Fix ImageView's size with dp or fill_parent and set android:scaleType to fitXY.

Multiprocessing a for loop?

Alternatively

with Pool() as pool: 
    pool.map(fits.open, [name + '.fits' for name in datainput])

How do I remove the non-numeric character from a string in java?

Another regex solution:

string.replace(/\D/g,'');  //remove the non-Numeric

Similarly, you can

string.replace(/\W/g,'');  //remove the non-alphaNumeric

In RegEX, the symbol '\' would make the letter following it a template: \w -- alphanumeric, and \W - Non-AlphaNumeric, negates when you capitalize the letter.

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

What is the color code for transparency in CSS?

Or you could just put

background-color: rgba(0,0,0,0.0);

That should solve your problem.

Copy tables from one database to another in SQL Server

You may go with this way: ( a general example )

insert into QualityAssuranceDB.dbo.Customers (columnA, ColumnB)
Select columnA, columnB from DeveloperDB.dbo.Customers

Also if you need to generate the column names as well to put in insert clause, use:

    select (name + ',') as TableColumns from sys.columns 
where object_id = object_id('YourTableName')

Copy the result and paste into query window to represent your table column names and even this will exclude the identity column as well:

    select (name + ',') as TableColumns from sys.columns 
where object_id = object_id('YourTableName') and is_identity = 0

Remember the script to copy rows will work if the databases belongs to the same location.


You can Try This.

select * into <Destination_table> from <Servername>.<DatabaseName>.dbo.<sourceTable>

Server name is optional if both DB is in same server.

How to get a list of programs running with nohup

You can also just use the top command and your user ID will indicate the jobs running and the their times.

$ top

(this will show all running jobs)

$ top -U [user ID]

(This will show jobs that are specific for the user ID)

Pandas groupby month and year

There are different ways to do that.

  • I created the data frame to showcase the different techniques to filter your data.
df = pd.DataFrame({'Date':['01-Jun-13','03-Jun-13', '15-Aug-13', '20-Jan-14', '21-Feb-14'],

'abc':[100,-20,40,25,60],'xyz':[200,50,-5,15,80] })

  • I separated months/year/day and seperated month-year as you explained.
def getMonth(s):
  return s.split("-")[1]

def getDay(s):
  return s.split("-")[0]

def getYear(s):
  return s.split("-")[2]

def getYearMonth(s):
  return s.split("-")[1]+"-"+s.split("-")[2]
  • I created new columns: year, month, day and 'yearMonth'. In your case, you need one of both. You can group using two columns 'year','month' or using one column yearMonth
df['year']= df['Date'].apply(lambda x: getYear(x))
df['month']= df['Date'].apply(lambda x: getMonth(x))
df['day']= df['Date'].apply(lambda x: getDay(x))
df['YearMonth']= df['Date'].apply(lambda x: getYearMonth(x))

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
3  20-Jan-14   25   15   14   Jan  20    Jan-14
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • You can go through the different groups in groupby(..) items.

In this case, we are grouping by two columns:

for key,g in df.groupby(['year','month']):
    print key,g

Output:

('13', 'Jun')         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
('13', 'Aug')         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
('14', 'Jan')         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
('14', 'Feb')         Date  abc  xyz year month day YearMonth

In this case, we are grouping by one column:

for key,g in df.groupby(['YearMonth']):
    print key,g

Output:

Jun-13         Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
Aug-13         Date  abc  xyz year month day YearMonth
2  15-Aug-13   40   -5   13   Aug  15    Aug-13
Jan-14         Date  abc  xyz year month day YearMonth
3  20-Jan-14   25   15   14   Jan  20    Jan-14
Feb-14         Date  abc  xyz year month day YearMonth
4  21-Feb-14   60   80   14   Feb  21    Feb-14
  • In case you wanna access to specific item, you can use get_group

print df.groupby(['YearMonth']).get_group('Jun-13')

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13
  • Similar to get_group. This hack would help to filter values and get the grouped values.

This also would give the same result.

print df[df['YearMonth']=='Jun-13'] 

Output:

        Date  abc  xyz year month day YearMonth
0  01-Jun-13  100  200   13   Jun  01    Jun-13
1  03-Jun-13  -20   50   13   Jun  03    Jun-13

You can select list of abc or xyz values during Jun-13

print df[df['YearMonth']=='Jun-13'].abc.values
print df[df['YearMonth']=='Jun-13'].xyz.values

Output:

[100 -20]  #abc values
[200  50]  #xyz values

You can use this to go through the dates that you have classified as "year-month" and apply cretiria on it to get related data.

for x in set(df.YearMonth): 
    print df[df['YearMonth']==x].abc.values
    print df[df['YearMonth']==x].xyz.values

I recommend also to check this answer as well.

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

Try

sdiff file1 file2

It ususally works much better in most cases for me. You may want to sort files prior, if order of lines is not important (e.g. some text config files).

For example,

sdiff -w 185 file1.cfg file2.cfg

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Exception of type 'System.OutOfMemoryException' was thrown.

I just restarted Visual Studio and did IISRESET which solved the problem.

A potentially dangerous Request.Form value was detected from the client

I faced this same problem while sending some email templates from aspx page to code behind....

So I tried to solve this by adding

 <httpRuntime requestValidationMode="2.0" />

in my web config under enter code here` but that did not helped me unless I putted

ValidateRequest="false"

attrribute in the page directive of the aspx page.

Difference between spring @Controller and @RestController annotation

@Controller is used in legacy systems which use JSPs. it can return views. @RestController is to mark the controller is providing REST services with JSON response type. so it wraps @Controller and @ResponseBody annotations together.

NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

i had the same error while working with hibernate, i had added below dependency in my pom.xml that solved the problem

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.10</version>
    </dependency>

reference https://mvnrepository.com/artifact/org.slf4j/slf4j-api

SQL Case Expression Syntax?

Sybase has the same case syntax as SQL Server:

Description

Supports conditional SQL expressions; can be used anywhere a value expression can be used.

Syntax

case 
     when search_condition then expression 
    [when search_condition then expression]...
    [else expression]
end

Case and values syntax

case expression
     when expression then expression 
    [when expression then expression]...
    [else expression]
end

Parameters

case

begins the case expression.

when

precedes the search condition or the expression to be compared.

search_condition

is used to set conditions for the results that are selected. Search conditions for case expressions are similar to the search conditions in a where clause. Search conditions are detailed in the Transact-SQL User’s Guide.

then

precedes the expression that specifies a result value of case.

expression

is a column name, a constant, a function, a subquery, or any combination of column names, constants, and functions connected by arithmetic or bitwise operators. For more information about expressions, see “Expressions” in.

Example

select disaster, 
       case
            when disaster = "earthquake" 
                then "stand in doorway"
            when disaster = "nuclear apocalypse" 
                then "hide in basement"
            when monster = "zombie apocalypse" 
                then "hide with Chuck Norris"
            else
                then "ask mom"
       end 
  from endoftheworld

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Use these following commands, this will solve the error:

sudo apt-get install postgresql

then fire:

sudo apt-get install python-psycopg2

and last:

sudo apt-get install libpq-dev

How to specify more spaces for the delimiter using cut?

Personally, I tend to use awk for jobs like this. For example:

ps axu| grep jboss | grep -v grep | awk '{print $5}'

Batch - If, ElseIf, Else

Recommendation. Do not use user-added REM statements to block batch steps. Use conditional GOTO instead. That way you can predefine and test the steps and options. The users also get much simpler changes and better confidence.

@Echo on
rem Using flags to control command execution

SET ExecuteSection1=0
SET ExecuteSection2=1

@echo off

IF %ExecuteSection1%==0 GOTO EndSection1
ECHO Section 1 Here

:EndSection1

IF %ExecuteSection2%==0 GOTO EndSection2
ECHO Section 2 Here
:EndSection2

Correctly determine if date string is a valid date in that format

    /**** date check is a recursive function. it's need 3 argument 
    MONTH,DAY,YEAR. ******/

    $always_valid_date = $this->date_check($month,$day,$year);

    private function date_check($month,$day,$year){

        /** checkdate() is a php function that check a date is valid 
        or not. if valid date it's return true else false.   **/

        $status = checkdate($month,$day,$year);

        if($status == true){

            $always_valid_date = $year . '-' . $month . '-' . $day;

            return $always_valid_date;

        }else{
            $day = ($day - 1);

            /**recursive call**/

            return $this->date_check($month,$day,$year);
        }

    }

How to launch jQuery Fancybox on page load?

Its simple:

Make your element hidden first like this:

<div id="hidden" style="display:none;">
    Hi this is hidden
</div>

Then call your javascript:

<script type="text/javascript">
    $(document).ready(function() {
        $.fancybox("#hidden");
    });
</script>

Check out the image below:

enter image description here

Another example:

<div id="example2" style="display:none;">
        <img src="http://theinstitute.ieee.org/img/07tiProductsandServicesiStockphoto-1311258460873.jpg" />
    </div>

 <script type="text/javascript">
        $(document).ready(function() {
            $.fancybox("#example2");
        });
    </script>

enter image description here

Convert .pfx to .cer

the simple way I believe is to import it then export it, using the certificate manager in Windows Management Console.

Does swift have a trim method on String?

Swift 3

let result = " abc ".trimmingCharacters(in: .whitespacesAndNewlines)

JQuery show and hide div on mouse click (animate)

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".click-header").click(function(){
            $(this).next(".hidden-content").slideToggle("slow");
            $(this).toggleClass("expanded-header");
        });
    });
</script>
.demo-container {
    margin:0 auto;
    width: 600px;
    text-align:center;
}
.click-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-down.png) no-repeat 50% 50%;
}
.expanded-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-up.png) no-repeat 50% 50%;
}
.hidden-content {
    display:none;
    border: 1px solid #d7dbd8;
    padding: 20px;
    text-align: center;
}
<div class="demo-container">
    <div class="click-header">&nbsp;</div>
    <div class="hidden-content">Lorem Ipsum.</div>
</div>

How to save a pandas DataFrame table as a png

As jcdoming suggested, use Seaborn heatmap():

import seaborn as sns
import matplotlib.pyplot as plt

fig = plt.figure(facecolor='w', edgecolor='k')
sns.heatmap(df.head(), annot=True, cmap='viridis', cbar=False)
plt.savefig('DataFrame.png')

DataFrame as a heat map

Is it possible to open a Windows Explorer window from PowerShell?

Use any of these:

  1. start .
  2. explorer .
  3. start explorer .
  4. ii .
  5. invoke-item .

You may apply any of these commands in PowerShell.

Just in case you want to open the explorer from the command prompt, the last two commands don't work, and the first three work fine.

MySQL Cannot Add Foreign Key Constraint

One additional cause of this error is when your tables or columns contain reserved keywords:

Sometimes one does forget these.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

I hope this can help someone who was faced with my same problem.

This answer uses the Bootstrap DatePicker Plugin, which is not native to bootstrap.

Make sure you install Bootstrap DatePicker through NuGet

Create a small piece of JavaScript and name it DatePickerReady.js save it in Scripts dir. This will make sure it works even in non HTML5 browsers although those are few nowadays.

if (!Modernizr.inputtypes.date) {
    $(function () {

       $(".datecontrol").datepicker();

    });
}

Set the bundles

bundles.Add(New ScriptBundle("~/bundles/bootstrap").Include(
              "~/Scripts/bootstrap.js",
              "~/Scripts/bootstrap-datepicker.js",
              "~/Scripts/DatePickerReady.js",
              "~/Scripts/respond.js"))

bundles.Add(New StyleBundle("~/Content/css").Include(
              "~/Content/bootstrap.css",
              "~/Content/bootstrap-datepicker3.css",
              "~/Content/site.css"))

Now set the Datatype so that when EditorFor is used MVC will identify what is to be used.

<Required>
<DataType(DataType.Date)>
Public Property DOB As DateTime? = Nothing

Your view code should be

@Html.EditorFor(Function(model) model.DOB, New With {.htmlAttributes = New With {.class = "form-control datecontrol", .PlaceHolder = "Enter Date of Birth"}})

and voila

enter image description here

Dropping connected users in Oracle database

Here's how I "automate" Dropping connected users in Oracle database:

# A shell script to Drop a Database Schema, forcing off any Connected Sessions (for example, before an Import) 
# Warning! With great power comes great responsibility.
# It is often advisable to take an Export before Dropping a Schema

if [ "$1" = "" ] 
then
    echo "Which Schema?"
    read schema
else
    echo "Are you sure? (y/n)"
    read reply
    [ ! $reply = y ] && return 1
    schema=$1
fi

sqlplus / as sysdba <<EOF
set echo on
alter user $schema account lock;
-- Exterminate all sessions!
begin     
  for x in ( select sid, serial# from v\$session where username=upper('$schema') )
  loop  
   execute immediate ( 'alter system kill session '''|| x.Sid || ',' || x.Serial# || ''' immediate' );  
  end loop;  
  dbms_lock.sleep( seconds => 2 ); -- Prevent ORA-01940: cannot drop a user that is currently connected
end;
/
drop user $schema cascade;
quit
EOF

Changing file permission in Python

os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)

stat

The following flags can also be used in the mode argument of os.chmod():

stat.S_ISUID Set UID bit.

stat.S_ISGID Set-group-ID bit. This bit has several special uses. For a directory it indicates that BSD semantics is to be used for that directory: files created there inherit their group ID from the directory, not from the effective group ID of the creating process, and directories created there will also get the S_ISGID bit set. For a file that does not have the group execution bit (S_IXGRP) set, the set-group-ID bit indicates mandatory file/record locking (see also S_ENFMT).

stat.S_ISVTX Sticky bit. When this bit is set on a directory it means that a file in that directory can be renamed or deleted only by the owner of the file, by the owner of the directory, or by a privileged process.

stat.S_IRWXU Mask for file owner permissions.

stat.S_IRUSR Owner has read permission.

stat.S_IWUSR Owner has write permission.

stat.S_IXUSR Owner has execute permission.

stat.S_IRWXG Mask for group permissions.

stat.S_IRGRP Group has read permission.

stat.S_IWGRP Group has write permission.

stat.S_IXGRP Group has execute permission.

stat.S_IRWXO Mask for permissions for others (not in group).

stat.S_IROTH Others have read permission.

stat.S_IWOTH Others have write permission.

stat.S_IXOTH Others have execute permission.

stat.S_ENFMT System V file locking enforcement. This flag is shared with S_ISGID: file/record locking is enforced on files that do not have the group execution bit (S_IXGRP) set.

stat.S_IREAD Unix V7 synonym for S_IRUSR.

stat.S_IWRITE Unix V7 synonym for S_IWUSR.

stat.S_IEXEC Unix V7 synonym for S_IXUSR.

Warning: The method assertEquals from the type Assert is deprecated

You're using junit.framework.Assert instead of org.junit.Assert.

Is it possible to override / remove background: none!important with jQuery?

With a <script> right after the <style> that applies the !important things, you should be able to do something like this:

var lastStylesheet = document.styleSheets[document.styleSheets.length - 1];
lastStylesheet.disabled = true;

document.write('<style type="text/css">');
// Call fixBackground for each element that needs fixing
document.write('</style>');

lastStylesheet.disabled = false;

function fixBackground(el) {
    document.write('html #' + el.id + ' { background-image: ' +
        document.defaultView.getComputedStyle(el).backgroundImage +
        ' !important; }');
}

This probably depends on what kind of browser compatibility you need, though.

error "Could not get BatchedBridge, make sure your bundle is packaged properly" on start of app

For me, it's because adb was not in the PATH. It's located /Users/man/Library/Android/sdk/platform-tools for me, it may be somewhere else for you, but anyway, find it and add it to your path to see if that help.

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

Why don't you start with this command-line:

$ sudo service elasticsearch status

I did it and get:

"There is insufficient memory for the Java Runtime..."

Then I edited /etc/elasticsearch/jvm.options file:

...

################################################################

# Xms represents the initial size of total heap space
# Xmx represents the maximum size of total heap space

#-Xms2g
#-Xms2g

-Xms512m
-Xmx512m

################################################################

...

This worked like a charm.

How to declare a inline object with inline variables without a parent class

You can also declare 'x' with the keyword var:

var x = new
{
  driver = new
  {
    firstName = "john",
    lastName = "walter"
  },
  car = new
  {
    brand = "BMW"
  }
};

This will allow you to declare your x object inline, but you will have to name your 2 anonymous objects, in order to access them. You can have an array of "x" :

x.driver.firstName // "john"
x.car.brand // "BMW"

var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"

Elevating process privilege programmatically?

According to the article Chris Corio: Teach Your Apps To Play Nicely With Windows Vista User Account Control, MSDN Magazine, Jan. 2007, only ShellExecute checks the embedded manifest and prompts the user for elevation if needed, while CreateProcess and other APIs don't. Hope it helps.

See also: same article as .chm.

How to fix Ora-01427 single-row subquery returns more than one row in select?

The only subquery appears to be this - try adding a ROWNUM limit to the where to be sure:

(SELECT C.I_WORKDATE
         FROM T_COMPENSATION C
         WHERE C.I_COMPENSATEDDATE = A.I_REQDATE AND ROWNUM <= 1
         AND C.I_EMPID = A.I_EMPID)

You do need to investigate why this isn't unique, however - e.g. the employee might have had more than one C.I_COMPENSATEDDATE on the matched date.

For performance reasons, you should also see if the lookup subquery can be rearranged into an inner / left join, i.e.

 SELECT 
    ...
    REPLACE(TO_CHAR(C.I_WORKDATE, 'DD-Mon-YYYY'),
            ' ',
            '') AS WORKDATE,
    ...
 INNER JOIN T_EMPLOYEE_MS E
    ...
     LEFT OUTER JOIN T_COMPENSATION C
          ON C.I_COMPENSATEDDATE = A.I_REQDATE
          AND C.I_EMPID = A.I_EMPID
    ...

How can I set size of a button?

Try with setPreferredSize instead of setSize.

UPDATE: GridLayout take up all space in its container, and BoxLayout seams to take up all the width in its container, so I added some glue-panels that are invisible and just take up space when the user stretches the window. I have just done this horizontally, and not vertically, but you could implement that in the same way if you want it.

Since GridLayout make all cells in the same size, it doesn't matter if they have a specified size. You have to specify a size for its container instead, as I have done.

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

public class PanelModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel(new GridLayout(4, 4));
        firstPanel.setPreferredSize(new Dimension(4*100, 4*100));
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                firstPanel.add(new JButton());
            }
        }

        JPanel firstGluePanel = new JPanel(new BorderLayout());
        firstGluePanel.add(firstPanel, BorderLayout.WEST);
        firstGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        firstGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        JPanel secondPanel = new JPanel(new GridLayout(13, 5));
        secondPanel.setPreferredSize(new Dimension(5*40, 13*40));
        for (int i=1; i<=5; i++) {
            for (int j=1; j<=13; j++) {
                secondPanel.add(new JButton());
            }
        }

        JPanel secondGluePanel = new JPanel(new BorderLayout());
        secondGluePanel.add(secondPanel, BorderLayout.WEST);
        secondGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        secondGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        mainPanel.add(firstGluePanel);
        mainPanel.add(secondGluePanel);
        frame.getContentPane().add(mainPanel);

        //frame.setSize(400,600);
        frame.pack();
        frame.setVisible(true);
    }
}

How to make this Header/Content/Footer layout using CSS?

Here is how to to that:

The header and footer are 30px height.

The footer is stuck to the bottom of the page.

HTML:

<div id="header">
</div>
<div id="content">
</div>
<div id="footer">
</div>

CSS:

#header {
    height: 30px;
}
#footer {
    height: 30px;
    position: absolute;
    bottom: 0;
}
body {
    height: 100%;
    margin-bottom: 30px;
}

Try it on jsfiddle: http://jsfiddle.net/Usbuw/

Adding an image to a PDF using iTextSharp and scale it properly

Personally, I use something close from fubo's solution and it works well:

image.ScaleToFit(document.PageSize);
image.SetAbsolutePosition(0,0);

Facebook user url by id

The easiest and the most correct (and legal) way is to use graph api.

Just perform the request: http://graph.facebook.com/4

which returns

{
   "id": "4",
   "name": "Mark Zuckerberg",
   "first_name": "Mark",
   "last_name": "Zuckerberg",
   "link": "http://www.facebook.com/zuck",
   "username": "zuck",
   "gender": "male",
   "locale": "en_US"
}

and take the link key.

You can also reduce the traffic by using fields parameter: http://graph.facebook.com/4?fields=link to get only what you need:

{
   "link": "http://www.facebook.com/zuck",
   "id": "4"
}

LaTeX package for syntax highlighting of code in various languages

LGrind does this. It's a mature LaTeX package that's been around since adam was a cowboy and has support for many programming languages.

Logging framework incompatibility

SLF4J 1.5.11 and 1.6.0 versions are not compatible (see compatibility report) because the argument list of org.slf4j.spi.LocationAwareLogger.log method has been changed (added Object[] p5):

SLF4J 1.5.11:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Throwable p5 )

SLF4J 1.6.0:

LocationAwareLogger.log ( org.slf4j.Marker p1, String p2, int p3,
                          String p4, Object[] p5, Throwable p6 )

See compatibility reports for other SLF4J versions on this page.

You can generate such reports by the japi-compliance-checker tool.

enter image description here

Tomcat starts but home page cannot open with url http://localhost:8080

If you started tomcat through eclipse, It can be solved in different ways too.

Method 1:

  1. Right click on server --> Properties
  2. click on Switch location and apply.

enter image description here

enter image description here Method2:

  1. Double click in the server in eclipse.
  2. Change Server location to Use tomcat installation(takes control of tomcat installation).

iterrows pandas get next rows value

This can be solved also by izipping the dataframe (iterator) with an offset version of itself.

Of course the indexing error cannot be reproduced this way.

Check this out

import pandas as pd
from itertools import izip

df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])   

for id1, id2 in izip(df.iterrows(),df.ix[1:].iterrows()):
    print id1[1]['value']
    print id2[1]['value']

which gives

AA
BB
BB
CC

MVC 4 Edit modal form using Bootstrap

I prefer to avoid using Ajax.BeginForm helper and do an Ajax call with JQuery. In my experience it is easier to maintain code written like this. So below are the details:

Models

public class ManagePeopleModel
{
    public List<PersonModel> People { get; set; }
    ... any other properties
}

public class PersonModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    ... any other properties
}

Parent View

This view contains the following things:

  • records of people to iterate through
  • an empty div that will be populated with a modal when a Person needs to be edited
  • some JavaScript handling all ajax calls
@model ManagePeopleModel

<h1>Manage People</h1>

@using(var table = Html.Bootstrap().Begin(new Table()))
{
    foreach(var person in Model.People)
    {
        <tr>
            <td>@person.Id</td>
            <td>@Person.Name</td>
            <td>@person.Age</td>
            <td>@html.Bootstrap().Button().Text("Edit Person").Data(new { @id = person.Id }).Class("btn-trigger-modal")</td>
        </tr>
    }
}

@using (var m = Html.Bootstrap().Begin(new Modal().Id("modal-person")))
{

}

@section Scripts
{
    <script type="text/javascript">
        // Handle "Edit Person" button click.
        // This will make an ajax call, get information for person,
        // put it all in the modal and display it
        $(document).on('click', '.btn-trigger-modal', function(){
            var personId = $(this).data('id');
            $.ajax({
                url: '/[WhateverControllerName]/GetPersonInfo',
                type: 'GET',
                data: { id: personId },
                success: function(data){
                    var m = $('#modal-person');
                    m.find('.modal-content').html(data);
                    m.modal('show');
                }
            });
        });

        // Handle submitting of new information for Person.
        // This will attempt to save new info
        // If save was successful, it will close the Modal and reload page to see updated info
        // Otherwise it will only reload contents of the Modal
        $(document).on('click', '#btn-person-submit', function() {
            var self = $(this);
            $.ajax({
                url: '/[WhateverControllerName]/UpdatePersonInfo',
                type: 'POST',
                data: self.closest('form').serialize(),
                success: function(data) {
                    if(data.success == true) {
                        $('#modal-person').modal('hide');
                        location.reload(false)
                    } else {
                        $('#modal-person').html(data);
                    }
                }
            });
        });
    </script>
}

Partial View

This view contains a modal that will be populated with information about person.

@model PersonModel
@{
    // get modal helper
    var modal = Html.Bootstrap().Misc().GetBuilderFor(new Modal());
}

@modal.Header("Edit Person")
@using (var f = Html.Bootstrap.Begin(new Form()))
{
    using (modal.BeginBody())
    {
        @Html.HiddenFor(x => x.Id)
        @f.ControlGroup().TextBoxFor(x => x.Name)
        @f.ControlGroup().TextBoxFor(x => x.Age)
    }
    using (modal.BeginFooter())
    {
        // if needed, add here @Html.Bootstrap().ValidationSummary()
        @:@Html.Bootstrap().Button().Text("Save").Id("btn-person-submit")
        @Html.Bootstrap().Button().Text("Close").Data(new { dismiss = "modal" })
    }
}

Controller Actions

public ActionResult GetPersonInfo(int id)
{
    var model = db.GetPerson(id); // get your person however you need
    return PartialView("[Partial View Name]", model)
}

public ActionResult UpdatePersonInfo(PersonModel model)
{
    if(ModelState.IsValid)
    {
        db.UpdatePerson(model); // update person however you need
        return Json(new { success = true });
    }
    // else
    return PartialView("[Partial View Name]", model);
}

node.js execute system command synchronously

Just to add that even though there are few usecases where you should use them, spawnSync / execFileSync / execSync were added to node.js in these commits: https://github.com/joyent/node/compare/d58c206862dc...e8df2676748e

How to correctly link php-fpm and Nginx Docker containers?

I think we also need to give the fpm container the volume, dont we? So =>

fpm:
    image: php:fpm
    volumes:
        - ./:/var/www/test/

If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:

[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

Another important difference is that the Hashtable type supports lock-free multiple readers and a single writer at the same time, while Dictionary does not.

Passing vector by reference

You can pass vector by reference just like this:

void do_something(int el, std::vector<int> &arr){
    arr.push_back(el);
}

However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).

In order to achieve exactly the same result you should write:

void do_something(int el, std::vector<int> &arr){
    if (arr.size() == 0) { // can't modify value of non-existent element
        arr.push_back(el);
    } else {
        arr[0] = el;
    }
}

In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).

Get bytes from std::string in C++

If this is just plain vanilla C, then:

strcpy(buffer, text.c_str());

Assuming that buffer is allocated and large enough to hold the contents of 'text', which is the assumption in your original code.

If encrypt() takes a 'const char *' then you can use

encrypt(text.c_str())

and you do not need to copy the string.

Check if a variable exists in a list in Bash

You can use (* wildcards) outside a case statement, too, if you use double brackets:

string='My string';

if [[ $string == *My* ]]
then
echo "It's there!";
fi

How to copy a file from remote server to local machine?

I would recommend to use sftp, use this command sftp -oPort=7777 user@host where -oPort is custom port number of ssh , in case if u changed it to 7777, then u can use -oPort, else if use only port 22 then plain sftp user@host which asks for the password , then u can log in, and u can navigate to required location using cd /home/user then a simple command get table u can download it, If u want to download a directory/folder get -r someDirectory will do it. If u want the file permissions also to exist then get -Pr someDirectory. For uploading on to remote change get to put in above commands.

How do I generate random integers within a specific range in Java?

Use:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

The integer x is now the random number that has a possible outcome of 5-10.

Remove icon/logo from action bar on android

Add the following code in your action bar styles:

<item name="android:displayOptions">showHome|homeAsUp|showTitle</item>
<item name="displayOptions">showHome|homeAsUp|showTitle</item>
<item name="android:icon">@android:color/transparent</item> <!-- This does the magic! -->

PS: I'm using Actionbar Sherlock and this works just fine.

How can I make my string property nullable?

String is a reference type and always nullable, you don't need to do anything special. Specifying that a type is nullable is necessary only for value types.

View HTTP headers in Google Chrome?

You can find the headers option in the Network tab in Developer's console in Chrome:

  1. In Chrome press F12 to open Developer's console.
  2. Select the Network tab. This tab gives you the information about the requests fired from the browser.
  3. Select a request by clicking on the request name. There you can find the Header information for that request along with some other information like Preview, Response and Timing.

Also, in my version of Chrome (50.0.2661.102), it gives an extension named LIVE HTTP Headers which gives information about the request headers for all the HTTP requests.

update: added image

enter image description here

Zoom to fit all markers in Mapbox or Leaflet

You also can locate all features inside a FeatureGroup or all the featureGroups, see how it works!

_x000D_
_x000D_
//Group1_x000D_
m1=L.marker([7.11, -70.11]);_x000D_
m2=L.marker([7.33, -70.33]);_x000D_
m3=L.marker([7.55, -70.55]);_x000D_
fg1=L.featureGroup([m1,m2,m3]);_x000D_
_x000D_
//Group2_x000D_
m4=L.marker([3.11, -75.11]);_x000D_
m5=L.marker([3.33, -75.33]);_x000D_
m6=L.marker([3.55, -75.55]);_x000D_
fg2=L.featureGroup([m4,m5,m6]);_x000D_
_x000D_
//BaseMap_x000D_
baseLayer = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');_x000D_
var map = L.map('map', {_x000D_
  center: [3, -70],_x000D_
  zoom: 4,_x000D_
  layers: [baseLayer, fg1, fg2]_x000D_
});_x000D_
_x000D_
//locate group 1_x000D_
function LocateOne() {_x000D_
    LocateAllFeatures(map, fg1);_x000D_
}_x000D_
_x000D_
function LocateAll() {_x000D_
    LocateAllFeatures(map, [fg1,fg2]);_x000D_
}_x000D_
_x000D_
//Locate the features_x000D_
function LocateAllFeatures(iobMap, iobFeatureGroup) {_x000D_
  if(Array.isArray(iobFeatureGroup)){   _x000D_
   var obBounds = L.latLngBounds();_x000D_
   for (var i = 0; i < iobFeatureGroup.length; i++) {_x000D_
    obBounds.extend(iobFeatureGroup[i].getBounds());_x000D_
   }_x000D_
   iobMap.fitBounds(obBounds);   _x000D_
  } else {_x000D_
   iobMap.fitBounds(iobFeatureGroup.getBounds());_x000D_
  }_x000D_
}
_x000D_
.mymap{_x000D_
  height: 300px;_x000D_
  width: 100%;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>_x000D_
<link href="https://unpkg.com/[email protected]/dist/leaflet.css" rel="stylesheet"/>_x000D_
_x000D_
<div id="map" class="mymap"></div>_x000D_
<button onclick="LocateOne()">locate group 1</button>_x000D_
<button onclick="LocateAll()">locate All</button>
_x000D_
_x000D_
_x000D_

How to do constructor chaining in C#

You use standard syntax (using this like a method) to pick the overload, inside the class:

class Foo 
{
    private int id;
    private string name;

    public Foo() : this(0, "") 
    {
    }

    public Foo(int id, string name) 
    {
        this.id = id;
        this.name = name;
    }

    public Foo(int id) : this(id, "") 
    {
    }

    public Foo(string name) : this(0, name) 
    {
    }
}

then:

Foo a = new Foo(), b = new Foo(456,"def"), c = new Foo(123), d = new Foo("abc");

Note also:

  • you can chain to constructors on the base-type using base(...)
  • you can put extra code into each constructor
  • the default (if you don't specify anything) is base()

For "why?":

  • code reduction (always a good thing)
  • necessary to call a non-default base-constructor, for example:

    SomeBaseType(int id) : base(id) {...}
    

Note that you can also use object initializers in a similar way, though (without needing to write anything):

SomeType x = new SomeType(), y = new SomeType { Key = "abc" },
         z = new SomeType { DoB = DateTime.Today };

Eclipse - java.lang.ClassNotFoundException

I had the same problem. All what I did was,

i). Generated Eclipse artifacts

mvn clean eclipse:eclipse

ii). Refresh the project and rerun your junit test. Should work fine.

Cast a Double Variable to Decimal

You only use the M for a numeric literal, when you cast it's just:

decimal dtot = (decimal)doubleTotal;

Note that a floating point number is not suited to keep an exact value, so if you first add numbers together and then convert to Decimal you may get rounding errors. You may want to convert the numbers to Decimal before adding them together, or make sure that the numbers aren't floating point numbers in the first place.

Load image from resources

You can always use System.Resources.ResourceManager which returns the cached ResourceManager used by this class. Since chan1 and chan2 represent two different images, you may use System.Resources.ResourceManager.GetObject(string name) which returns an object matching your input with the project resources

Example

object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project
channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image

Notice: Resources.ResourceManager.GetObject(string name) may return null if the string specified was not found in the project resources.

Thanks,
I hope you find this helpful :)

Unable to open project... cannot be opened because the project file cannot be parsed

I just ran into same problem. I removed generated strings by git as always but Xcode still refused to open .xcodeproj file. But everything was correct, no missing brackets etc. Finally I tried to quit Xcode and open project when Xcode was closed.. then it worked. I hope this helps someone.

EDIT:

for resolving conflicts in your .xcodeproj file you can use this handy script:

  1. Create empty .sh file in your project directory ( e.g. resolve_conflicts.sh )
  2. Here is the script:

    projectfile=find -d . -name 'project.pbxproj' projectdir=echo *.xcodeproj projectfile="${projectdir}/project.pbxproj" tempfile="${projectdir}/project.pbxproj.out" savefile="${projectdir}/project.pbxproj.mergesave"

    cat $projectfile | grep -v "<<<<<<< HEAD" | grep -v "=======" | grep -v "^>>>>>>> " > $tempfile mv $tempfile $projectfile

  3. Run it from terminal using sh command: sh resolve_conflicts.sh

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

Replace all double quotes within String

This is to remove double quotes in a string.

str1 = str.replace(/"/g, "");
alert(str1);

Incompatible implicit declaration of built-in function ‘malloc’

The stdlib.h file contains the header information or prototype of the malloc, calloc, realloc and free functions.

So to avoid this warning in ANSI C, you should include the stdlib header file.

Changing Font Size For UITableView Section Headers

Here it is, You have to follow write a few methods here. #Swift 5

func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    
    let header = view as? UITableViewHeaderFooterView
    header?.textLabel?.font = UIFont.init(name: "Montserrat-Regular", size: 14)
    header?.textLabel?.textColor = .greyishBrown
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    
    return 26
}

Have a good luck

Preventing multiple clicks on button

I modified the solution by @Kalyani and so far it's been working beautifully!

$('selector').click(function(event) {
  if(!event.detail || event.detail == 1){ return true; }
  else { return false; }
});

Numeric for loop in Django templates

For those who are looking to simple answer, just needing to display an amount of values, let say 3 from 100 posts for example just add {% for post in posts|slice:"3" %} and loop it normally and only 3 posts will be added.