Programs & Examples On #Ajp

The Apache JServ Protocol is an efficient protocol to connect backend web servers to front end web servers.

Unable to find a @SpringBootConfiguration when doing a JpaTest

This is more the the error itself, not answering the original question:

We were migrating from java 8 to java 11. Application compiled successfully, but the errors Unable to find a @SpringBootConfiguration started to appear in the integration tests when ran from command line using maven (from IntelliJ it worked).

It appeared that maven-failsafe-plugin stopped seeing the classes on classpath, we fixed that by telling failsafe plugin to include the classes manually:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <configuration>
                <additionalClasspathElements>
                    <additionalClasspathElement>${basedir}/target/classes</additionalClasspathElement>
                </additionalClasspathElements>
            </configuration>
            ...
        </plugin>

Spring Data and Native Query with pagination

Removing \n#pageable\n from both query and count query worked for me. Springboot version : 2.1.5.RELEASE DB : Mysql

A child container failed during start java.util.concurrent.ExecutionException

Some time this problem occur due to incompatible java version and tomcat version.Choose the compatible version of both.

Apache Proxy: No protocol handler was valid

For my Apache2.4 + php5-fpm installation to start working, I needed to activate the following Apache modules:

sudo a2enmod proxy
sudo a2enmod proxy_fcgi

No need for proxy_http, and this is what sends all .php files straight to php5-fpm:

<FilesMatch \.php$>
    SetHandler "proxy:unix:/var/run/php5-fpm.sock|fcgi://localhost"
</FilesMatch>

Name [jdbc/mydb] is not bound in this Context

You need a ResourceLink in your META-INF/context.xml file to make the global resource available to the web application.

 <ResourceLink name="jdbc/mydb"
             global="jdbc/mydb"
              type="javax.sql.DataSource" />

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

Please verify your .project and .classpath files. Verify the java version and other reuqired details. If those and missing or mis matched

BeanFactory not initialized or already closed - call 'refresh' before

In my case, this error was due to the Network connection error that i was noticed in log.

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

javax.naming.NameNotFoundException: Name is not bound in this Context. Unable to find

You can also add

<Resource 
auth="Container" 
driverClassName="org.apache.derby.jdbc.EmbeddedDriver" 
maxActive="20" 
maxIdle="10" 
maxWait="-1" 
name="ds/flexeraDS" 
type="javax.sql.DataSource" 
url="jdbc:derby:flexeraDB;create=true" 
/> 

under META-INF/context.xml file (This will be only at application level).

SQL Error: 0, SQLState: 08S01 Communications link failure

The communication link between the driver and the data source to which the driver was attempting to connect failed before the function completed processing. So usually its a network error. This could be caused by packet drops or badly configured Firewall/Switch.

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:

http://localhost:8080/YourProject/yourfile.jsp

then your problem will be solved.

No Spring WebApplicationInitializer types detected on classpath

tomcat-maven-plugin in test

Tomcat usually does not add classes in src/test/java to the classpath. They are missing if you run tomcat in scope test. To order tomcat to respect classes in test, use -Dmaven.tomcat.useTestClasspath=true or add

<properties>
   <maven.tomcat.useTestClasspath>true</maven.tomcat.useTestClasspath>
</properties>

To your pom.xml.

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

This problem may occur due to apache not getting required port (default is 80).

The port may be being used by other services.

For example: Skype also has default port 80.

Installing Skype and Apache both on same machine will cause conflict and hence Apache will not start.

Either, you change Skype port or change Apache port as described in following steps:

Change the ports of Apache and it will work for you. Go to httpd.conf

How to change port for Apache:

Search for:

ServerName localhost:80

Change it to:

ServerName localhost:81

Also Search For:

Listen 80

Change it to:

Listen 81

If you have created any virtual hosts, change the ports there also. Then restart your apache.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

I had the same problem in my tomcat server but when i check deeply i found that i add a new tag in my web.xml file and the server doesn't accept it so check your file to if any update happened then restart your tomcat and will be good .

Tomcat is not deploying my web project from Eclipse

I had the same problem. I fixed it by makinbg the following entry in org.eclipse.wst.common.project.facet.core.xml

<runtime name="Apache Tomcat v7.0" />

Now this complete file looks like -

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
    <runtime name="Apache Tomcat v7.0" />
    <fixed facet="wst.jsdt.web" />
    <installed facet="java" version="1.5" />
    <installed facet="jst.web" version="2.3" />
    <installed facet="wst.jsdt.web" version="1.0" />
</faceted-project>

Error message "Forbidden You don't have permission to access / on this server"

    I changed 
    Order Deny,Allow
    Deny From All      in .htaccess to   " Require all denied "    and restarted apache but it did not help.

Path for apache2.conf in ubuntu is /etc/apache2/apache.conf

Then I added following lines in apache2.conf and then my folder is working fine

    <Directory /path of required folder>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
       </Directory>

   and run  " Sudo service apache2 restart " 

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

Tomcat 7 "SEVERE: A child container failed during start"

This seems like that the servlet api version which you using is older than the xsd you are using in web.xml eg 3.0

use this one ****http://java.sun.com/xml/ns/javaee/" id="WebApp_ID" version="2.5"> ****

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

org.springframework.beans.factory.BeanCreationException: Error creating bean with name

According to the stack trace, your issue is that your app cannot find org.apache.commons.dbcp.BasicDataSource, as per this line:

java.lang.ClassNotFoundException: org.apache.commons.dbcp.BasicDataSource

I see that you have commons-dbcp in your list of jars, but for whatever reason, your app is not finding the BasicDataSource class in it.

How to set level logging to DEBUG in Tomcat?

Firstly, the level name to use is FINE, not DEBUG. Let's assume for a minute that DEBUG is actually valid, as it makes the following explanation make a bit more sense...

In the Handler specific properties section, you're setting the logging level for those handlers to DEBUG. This means the handlers will handle any log messages with the DEBUG level or higher. It doesn't necessarily mean any DEBUG messages are actually getting passed to the handlers.

In the Facility specific properties section, you're setting the logging level for a few explicitly-named loggers to DEBUG. For those loggers, anything at level DEBUG or above will get passed to the handlers.

The default logging level is INFO, and apart from the loggers mentioned in the Facility specific properties section, all loggers will have that level.

If you want to see all FINE messages, add this:

.level = FINE

However, this will generate a vast quantity of log messages. It's probably more useful to set the logging level for your code:

your.package.level = FINE

See the Tomcat 6/Tomcat 7 logging documentation for more information. The example logging.properties file shown there uses FINE instead of DEBUG:

...
1catalina.org.apache.juli.FileHandler.level = FINE
...

and also gives you examples of setting additional logging levels:

# For example, set the com.xyz.foo logger to only log SEVERE
# messages:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.session.ManagerBase.level = FINE

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You can change the port number:

Open the server tab in eclipse -> right click open click on open---->you can change the port number.

Run the application with http://localhost:8080/Applicationname it will give output and also check http://localhost:8080/Applicationname/index.jsp

How do you determine what technology a website is built on?

There are all sorts of things you can look out for, but it doesn't really give you any certainty as to the technology behind a site. In general, information like that is something people will want to hide, as the more information that is exposed the easier it might be for malicious parties to identify security vulnerabilities or denial of service holes.

If I was interested I'd probably look, in no particular order, at:

  • urls, and file extensions.
  • HTTP response headers
  • Source code for comments, or standard JS libraries

Incidentally, the tools mentioned in other answers are only looking at some of the above properties of the site for you, albeit automatically, and slightly quicker. :)

What are the lesser known but useful data structures?

Left Leaning Red-Black Trees. A significantly simplified implementation of red-black trees by Robert Sedgewick published in 2008 (~half the lines of code to implement). If you've ever had trouble wrapping your head around the implementation of a Red-Black tree, read about this variant.

Very similar (if not identical) to Andersson Trees.

I do not understand how execlp() works in Linux

The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:

execl("/bin/ls", "ls", "-la", NULL);

The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:

execlp("ls", "ls", "-la", NULL);

Pass a simple string from controller to a view MVC3

To pass a string to the view as the Model, you can do:

public ActionResult Index()
{
    string myString = "This is my string";
    return View((object)myString);
}

You must cast it to an object so that MVC doesn't try to load the string as the view name, but instead pass it as the model. You could also write:

return View("Index", myString);

.. which is a bit more verbose.

Then in your view, just type it as a string:

@model string

<p>Value: @Model</p>

Then you can manipulate Model how you want.

For accessing it from a Layout page, it might be better to create an HtmlExtension for this:

public static string GetThemePath(this HtmlHelper helper)
{
    return "/path-to-theme";
}

Then inside your layout page:

<p>Value: @Html.GetThemePath()</p>

Hopefully you can apply this to your own scenario.

Edit: explicit HtmlHelper code:

namespace <root app namespace>
{
    public static class Helpers
    {
        public static string GetThemePath(this HtmlHelper helper)
        {
            return System.Web.Hosting.HostingEnvironment.MapPath("~") + "/path-to-theme";
        }
    }
}

Then in your view:

@{
    var path = Html.GetThemePath();
    // .. do stuff
}

Or: <p>Path: @Html.GetThemePath()</p>

Edit 2:

As discussed, the Helper will work if you add a @using statement to the top of your view, with the namespace pointing to the one that your helper is in.

How to empty a char array?

simpler is better - make sense?

in this case just members[0] = 0 works. don't make a simple question so complicated.

How can I see what I am about to push with git?

To see which files are changed and view the actual code changes compared to the master branch you could use:

git diff --stat --patch origin master

NOTE: If you happen to use any of the Intellij IDEs then you can right-click your top-level project, select Git > Compare with branch > and pick the origin you want e.g. origin/master. In the file tree that will appear you can double-click the files to see a visual diff. Unlike the command-line option above you can edit your local versions from the diff window.

Create a circular button in BS3

(Not cross-browser tested), but this is my answer:

.btn-circle {
  width: 40px;
  height: 40px;
  line-height: 40px; /* adjust line height to align vertically*/
  padding:0;
  border-radius: 50%;
}
  • vertical center via the line-height property
  • padding becomes useless and must be reset
  • border-radius independant of the button size

Matplotlib scatterplot; colour as a function of a third variable

Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

  • Plot points corresponding to Physical variable 'A' in RED.
  • Plot points corresponding to Physical variable 'B' in BLUE.
  • Plot points corresponding to Physical variable 'C' in GREEN.

In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

x=['A','B','B','C','A','B']
y=[15,30,25,18,22,13]

# Function to map the colors as a list from the input list of x variables
def pltcolor(lst):
    cols=[]
    for l in lst:
        if l=='A':
            cols.append('red')
        elif l=='B':
            cols.append('blue')
        else:
            cols.append('green')
    return cols
# Create the colors list using the function above
cols=pltcolor(x)

plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
plt.grid(True)
plt.show()

Coloring scatter plot as a function of x variable

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

MySQL Results as comma separated list

You can use GROUP_CONCAT to perform that, e.g. something like

SELECT p.id, p.name, GROUP_CONCAT(s.name) AS site_list
FROM sites s
INNER JOIN publications p ON(s.id = p.site_id)
GROUP BY p.id, p.name;

Windows batch script to unhide files hidden by virus

echo "Enter Drive letter" 
set /p driveletter=

attrib -s -h -a /s /d  %driveletter%:\*.*

AngularJS: Can't I set a variable value on ng-click?

You can use some thing like this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div ng-app="" ng-init="btn1=false" ng-init="btn2=false">_x000D_
    <p>_x000D_
      <input type="submit" ng-disabled="btn1||btn2" ng-click="btn1=true" ng-model="btn1" />_x000D_
    </p>_x000D_
    <p>_x000D_
      <button ng-disabled="btn1||btn2" ng-model="btn2" ng-click="btn2=true">Click Me!</button>_x000D_
    </p>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I keep track of pip-installed packages in an Anaconda (Conda) environment?

My which pip shows the following path:

$ which pip
/home/kmario23/anaconda3/bin/pip

So, whatever package I install using pip install <package-name> will have to be reflected in the list of packages when the list is exported using:

$ conda list --export > conda_list.txt

But, I don't. So, instead I used the following command as suggested by several others:

# get environment name by
$ conda-env list

# get list of all installed packages by (conda, pip, etc.,)
$ conda-env export -n <my-environment-name> > all_packages.yml
# if you haven't created any specific env, then just use 'root'

Now, I can see all the packages in my all-packages.yml file.

What is "string[] args" in Main class for?

It's an array of the parameters/arguments (hence args) that you send to the program. For example ping 172.16.0.1 -t -4

These arguments are passed to the program as an array of strings.

string[] args // Array of Strings containing arguments.

Hiding axis text in matplotlib plots

If you want to hide just the axis text keeping the grid lines:

frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])

Doing set_visible(False) or set_ticks([]) will also hide the grid lines.

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64 macro and other printf issues altogether:

#include <fmt/core.h>

int main() {
  uint64_t ui64 = 90;
  fmt::print("test uint64_t : {}\n", ui64);
}

The formatting facility based on this library is proposed for standardization in C++20: P0645.

Disclaimer: I'm the author of {fmt}.

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

This will find all rows in the table that have errors, print out the row's primary key and the error that occurred on that row...

This is in C#, but converting it to VB should not be hard.

 foreach (DataRow dr in dataTable)
 {
   if (dr.HasErrors)
     {
        Debug.Write("Row ");
        foreach (DataColumn dc in dataTable.PKColumns)
          Debug.Write(dc.ColumnName + ": '" + dr.ItemArray[dc.Ordinal] + "', ");
        Debug.WriteLine(" has error: " + dr.RowError);
     }
  }

Oops - sorry PKColumns is something I added when I extended DataTable that tells me all the columns that make up the primary key of the DataTable. If you know the Primary Key columns in your datatable you can loop through them here. In my case, since all my datatables know their PK cols I can write debug for these errors automatically for all tables.

The output looks like this:

Row FIRST_NAME: 'HOMER', LAST_NAME: 'SIMPSON', MIDDLE_NAME: 'J',  has error: Column 'HAIR_COLOR' does not allow DBNull.Value.

If you're confused about the PKColumns section above - this prints out column names and values, and is not necessary, but adds helpful troubleshooting info for identifying which column values may be causing the issue. Removing this section and keeping the rest will still print the SQLite error being generated, which will note the column that has the problem.

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

jQuery get the location of an element relative to window

TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

Why does NULL = NULL evaluate to false in SQL server

At technet there is a good explanation for how null values work.

Null means unknown.

Therefore the Boolean expression

value=null

does not evaluate to false, it evaluates to null, but if that is the final result of a where clause, then nothing is returned. That is a practical way to do it, since returning null would be difficult to conceive.

It is interesting and very important to understand the following:

If in a query we have

where (value=@param Or @param is null) And id=@anotherParam

and

  • value=1
  • @param is null
  • id=123
  • @anotherParam=123

then

"value=@param" evaluates to null
"@param is null" evaluates to true
"id=@anotherParam" evaluates to true

So the expression to be evaluated becomes

(null Or true) And true

We might be tempted to think that here "null Or true" will be evaluated to null and thus the whole expression becomes null and the row will not be returned.

This is not so. Why?

Because "null Or true" evaluates to true, which is very logical, since if one operand is true with the Or-operator, then no matter the value of the other operand, the operation will return true. Thus it does not matter that the other operand is unknown (null).

So we finally have true=true and thus the row will be returned.

Note: with the same crystal clear logic that "null Or true" evaluates to true, "null And true" evaluates to null.

Update:
Ok, just to make it complete I want to add the rest here too which turns out quite fun in relation to the above.

"null Or false" evaluates to null, "null And false" evaluates to false. :)

The logic is of course still as self-evident as before.

Passing command line arguments from Maven as properties in pom.xml

Inside pom.xml

<project>

.....

<profiles>
    <profile>
        <id>linux64</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build_os>linux</build_os>
            <build_ws>gtk</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>

    <profile>
        <id>win64</id>
        <activation>
            <property>
                <name>env</name>
                <value>win64</value>
            </property>
        </activation>
        <properties>
            <build_os>win32</build_os>
            <build_ws>win32</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>
</profiles>

.....

<plugin>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>target-platform-configuration</artifactId>
    <version>${tycho.version}</version>
    <configuration>
        <environments>
            <environment>
                <os>${build_os}</os>
                <ws>${build_ws}</ws>
                <arch>${build_arch}</arch>
            </environment>
        </environments>
    </configuration>
</plugin>

.....

In this example when you run the pom without any argument mvn clean install default profile will execute.

When executed with mvn -Denv=win64 clean install

win64 profile will executed.

Please refer http://maven.apache.org/guides/introduction/introduction-to-profiles.html

PHP Call to undefined function

How to reproduce the error, and how to fix it:

  1. Put this code in a file called p.php:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    ?>
    
  2. Run it like this:

    php p.php
    
  3. We get error:

    PHP Fatal error:  Call to undefined function salt() in 
    /home/el/foo/p.php on line 6
    
  4. Solution: use $this->salt(); instead of salt();

    So do it like this instead:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            $this->salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    
    ?>
    

If someone could post a link to why $this has to be used before PHP functions within classes, yeah, that would be great.

The ScriptManager must appear before any controls that need it

You can add your Script Manager tags just below the <Form> tag of your page. Here is how you can place your Script Manager tag.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

If you are using Master Pages, its recommended to use your Script Manager in your Master page so that you do not have to write it again and again on every page that contains AJAX controls.

How to initialize a vector with fixed length in R

Just for the sake of completeness you can just take the wanted data type and add brackets with the number of elements like so:

x <- character(10)

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

How to get page content using cURL?

this is how:

   /**
     * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
     * array containing the HTTP server response header fields and content.
     */
    function get_web_page( $url )
    {
        $user_agent='Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0';

        $options = array(

            CURLOPT_CUSTOMREQUEST  =>"GET",        //set request type post or get
            CURLOPT_POST           =>false,        //set to GET
            CURLOPT_USERAGENT      => $user_agent, //set user agent
            CURLOPT_COOKIEFILE     =>"cookie.txt", //set cookie file
            CURLOPT_COOKIEJAR      =>"cookie.txt", //set cookie jar
            CURLOPT_RETURNTRANSFER => true,     // return web page
            CURLOPT_HEADER         => false,    // don't return headers
            CURLOPT_FOLLOWLOCATION => true,     // follow redirects
            CURLOPT_ENCODING       => "",       // handle all encodings
            CURLOPT_AUTOREFERER    => true,     // set referer on redirect
            CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
            CURLOPT_TIMEOUT        => 120,      // timeout on response
            CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        );

        $ch      = curl_init( $url );
        curl_setopt_array( $ch, $options );
        $content = curl_exec( $ch );
        $err     = curl_errno( $ch );
        $errmsg  = curl_error( $ch );
        $header  = curl_getinfo( $ch );
        curl_close( $ch );

        $header['errno']   = $err;
        $header['errmsg']  = $errmsg;
        $header['content'] = $content;
        return $header;
    }

Example

//Read a web page and check for errors:

$result = get_web_page( $url );

if ( $result['errno'] != 0 )
    ... error: bad url, timeout, redirect loop ...

if ( $result['http_code'] != 200 )
    ... error: no page, no permissions, no service ...

$page = $result['content'];

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

How to Call Controller Actions using JQuery in ASP.NET MVC

In response to the above post I think it needs this line instead of your line:-

var strMethodUrl = '@Url.Action("SubMenu_Click", "Logging")?param1='+value1+' &param2='+value2

Or else you send the actual strings value1 and value2 to the controller.

However, for me, it only calls the controller once. It seems to hit 'receieveResponse' each time, but a break point on the controller method shows it is only hit 1st time until a page refresh.


Here is a working solution. For the cshtml page:-

   <button type="button" onclick="ButtonClick();"> Call &raquo;</button>

<script>
    function ButtonClick()
    {
        callControllerMethod2("1", "2");
    }
    function callControllerMethod2(value1, value2)
    {
        var response = null;
        $.ajax({
            async: true,
            url: "Logging/SubMenu_Click?param1=" + value1 + " &param2=" + value2,
            cache: false,
            dataType: "json",
            success: function (data) { receiveResponse(data); }
        });
    }
    function receiveResponse(response)
    {
        if (response != null)
        {
            for (var i = 0; i < response.length; i++)
            {
                alert(response[i].Data);
            }
        }
    }
</script>

And for the controller:-

public class A
{
    public string Id { get; set; }
    public string Data { get; set; }

}
public JsonResult SubMenu_Click(string param1, string param2)
{
    A[] arr = new A[] {new A(){ Id = "1", Data = DateTime.Now.Millisecond.ToString() } };
    return Json(arr , JsonRequestBehavior.AllowGet);
}

You can see the time changing each time it is called, so there is no caching of the values...

How do you Programmatically Download a Webpage in Java

Here's some tested code using Java's URL class. I'd recommend do a better job than I do here of handling the exceptions or passing them up the call stack, though.

public static void main(String[] args) {
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        url = new URL("http://stackoverflow.com/");
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
         mue.printStackTrace();
    } catch (IOException ioe) {
         ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

Is a URL allowed to contain a space?

Firefox 3 will display %20s in URLs as spaces in the address bar.

git checkout master error: the following untracked working tree files would be overwritten by checkout

do a :

git branch

if git show you something like :

* (no branch)
master
Dbranch

You have a "detached HEAD". If you have modify some files on this branch you, commit them, then return to master with

git checkout master 

Now you should be able to delete the Dbranch.

Check if a folder exist in a directory and create them using C#

    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

How to replace an entire line in a text file by line number

I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:

#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file

This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/ and placing a wildcard in place of the_original_line.

Double free or corruption after queue::push

You need to define a copy constructor, assignment, operator.

class Test {
   Test(const Test &that); //Copy constructor
   Test& operator= (const Test &rhs); //assignment operator
}

Your copy that is pushed on the queue is pointing to the same memory your original is. When the first is destructed, it deletes the memory. The second destructs and tries to delete the same memory.

How to create web service (server & Client) in Visual Studio 2012?

When creating a New Project, under the language of your choice, select Web and then change to .NET Framework 3.5 and you will get the option of creating an ASP.NET WEB Service Application.

enter image description here

Chrome Dev Tools - Modify javascript and reload

This is a bit of a work around, but one way you can achieve this is by adding a breakpoint at the start of the javascript file or block you want to manipulate.

Then when you reload, the debugger will pause on that breakpoint, and you can make any changes you want to the source, save the file and then run the debugger through the modified code.

But as everyone has said, next reload the changes will be gone - at least it let's you run some slightly modified JS client side.

What is the difference between HTTP and REST?

Not quite...

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

REST was initially described in the context of HTTP, but is not limited to that protocol. RESTful architectures can be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state. RESTful applications maximise the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimise the addition of new application-specific features on top of it.

http://www.looselycoupled.com/glossary/SOAP

(Simple Object Access Protocol) The standard for web services messages. Based on XML, SOAP defines an envelope format and various rules for describing its contents. Seen (with WSDL and UDDI) as one of the three foundation standards of web services, it is the preferred protocol for exchanging web services, but by no means the only one; proponents of REST say that it adds unnecessary complexity.

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

How do I read input character-by-character in Java?

This will print 1 character per line from the file.

    try {

        FileInputStream inputStream = new FileInputStream(theFile);
        while (inputStream.available() > 0) {
            inputData = inputStream.read();
            System.out.println((char) inputData);

        }
        inputStream.close();
    } catch (IOException ioe) {
        System.out.println("Trouble reading from the file: " + ioe.getMessage());
    }

How to center the elements in ConstraintLayout

The solution with guideline works only for this particular case with single line EditText. To make it work for multiline EditText you should use "packed" chain.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/client_id_input_layout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/authenticate"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed">

        <android.support.design.widget.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/login_client_id"
            android:inputType="textEmailAddress" />

    </android.support.design.widget.TextInputLayout>

    <android.support.v7.widget.AppCompatButton
        android:id="@+id/authenticate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/login_auth"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="@id/client_id_input_layout"
        app:layout_constraintRight_toRightOf="@id/client_id_input_layout"
        app:layout_constraintTop_toBottomOf="@id/client_id_input_layout" />

</android.support.constraint.ConstraintLayout>

Here's how it looks:

View on Nexus 5

You can read more about using chains in following posts:

POI setting Cell Background to a Custom Color

See http://poi.apache.org/spreadsheet/quick-guide.html#CustomColors.

Custom colors

HSSF:

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow row = sheet.createRow((short) 0);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue("Default Palette");

//apply some colors from the standard palette,
// as in the previous examples.
//we'll use red text on a lime background

HSSFCellStyle style = wb.createCellStyle();
style.setFillForegroundColor(HSSFColor.LIME.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFFont font = wb.createFont();
font.setColor(HSSFColor.RED.index);
style.setFont(font);

cell.setCellStyle(style);

//save with the default palette
FileOutputStream out = new FileOutputStream("default_palette.xls");
wb.write(out);
out.close();

//now, let's replace RED and LIME in the palette
// with a more attractive combination
// (lovingly borrowed from freebsd.org)

cell.setCellValue("Modified Palette");

//creating a custom palette for the workbook
HSSFPalette palette = wb.getCustomPalette();

//replacing the standard red with freebsd.org red
palette.setColorAtIndex(HSSFColor.RED.index,
        (byte) 153,  //RGB red (0-255)
        (byte) 0,    //RGB green
        (byte) 0     //RGB blue
);
//replacing lime with freebsd.org gold
palette.setColorAtIndex(HSSFColor.LIME.index, (byte) 255, (byte) 204, (byte) 102);

//save with the modified palette
// note that wherever we have previously used RED or LIME, the
// new colors magically appear
out = new FileOutputStream("modified_palette.xls");
wb.write(out);
out.close();

XSSF:

XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet();
XSSFRow row = sheet.createRow(0);
XSSFCell cell = row.createCell( 0);
cell.setCellValue("custom XSSF colors");

XSSFCellStyle style1 = wb.createCellStyle();
style1.setFillForegroundColor(new XSSFColor(new java.awt.Color(128, 0, 128)));
style1.setFillPattern(CellStyle.SOLID_FOREGROUND);

Unable to establish SSL connection, how do I fix my SSL cert?

In my case I had not enabled the site 'default-ssl'. Only '000-default' was listed in the /etc/apache2/sites-enabled folder.

Enable SSL site on Ubuntu 14 LTS, Apache 2.4.7:

a2ensite default-ssl
service apache2 reload

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

It seems it is enough to restart the windows explorer service:

  1. Open task manager
  2. Find the Windows Explorer proces
  3. Select it. After selection, the "Restart" button will appear in the bottom right corner.
  4. Click the "restart" button. Windows explorer will be reloaded.

It helped in my case.

Determine if map contains a value for a key?

You can create your getValue function with the following code:

bool getValue(const std::map<int, Bar>& input, int key, Bar& out)
{
   std::map<int, Bar>::iterator foundIter = input.find(key);
   if (foundIter != input.end())
   {
      out = foundIter->second;
      return true;
   }
   return false;
}

Java Webservice Client (Best way)

You can find some resources related to developing web services client using Apache axis2 here.

http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html

Below posts gives good explanations about developing web services using Apache axis2.

http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/

http://wso2.org/library/136

What are the JavaScript KeyCodes?

keyCodes are different from the ASCII values. For a complete keyCode reference, see http://unixpapa.com/js/key.html

For example, Numpad numbers have keyCodes 96 - 105, which corresponds to the beginning of lowercase alphabet in ASCII. This could lead to problems in validating numeric input.

How to join entries in a set into one string?

I think you just have it backwards.

print ", ".join(set_3)

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

std::unique_lock<std::mutex> or std::lock_guard<std::mutex>?

As has been mentioned by others, std::unique_lock tracks the locked status of the mutex, so you can defer locking until after construction of the lock, and unlock before destruction of the lock. std::lock_guard does not permit this.

There seems no reason why the std::condition_variable wait functions should not take a lock_guard as well as a unique_lock, because whenever a wait ends (for whatever reason) the mutex is automatically reacquired so that would not cause any semantic violation. However according to the standard, to use a std::lock_guard with a condition variable you have to use a std::condition_variable_any instead of std::condition_variable.

Edit: deleted "Using the pthreads interface std::condition_variable and std::condition_variable_any should be identical". On looking at gcc's implementation:

  • std::condition_variable::wait(std::unique_lock&) just calls pthread_cond_wait() on the underlying pthread condition variable with respect to the mutex held by unique_lock (and so could equally do the same for lock_guard, but doesn't because the standard doesn't provide for that)
  • std::condition_variable_any can work with any lockable object, including one which is not a mutex lock at all (it could therefore even work with an inter-process semaphore)

matplotlib savefig in jpeg format

You can save an image as 'png' and use the python imaging library (PIL) to convert this file to 'jpg':

import Image
import matplotlib.pyplot as plt

plt.plot(range(10))
plt.savefig('testplot.png')
Image.open('testplot.png').save('testplot.jpg','JPEG')

The original:

enter image description here

The JPEG image:

enter image description here

Improve INSERT-per-second performance of SQLite

I coudn't get any gain from transactions until I raised cache_size to a higher value i.e. PRAGMA cache_size=10000;

How to access the content of an iframe with jQuery?

<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">

$(function() {

    //here you have the control over the body of the iframe document
    var iBody = $("#iView").contents().find("body");

    //here you have the control over any element (#myContent)
    var myContent = iBody.find("#myContent");

});

</script>
</head>
<body>
  <iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>

Is there a way to get a list of all current temporary tables in SQL Server?

You can get list of temp tables by following query :

select left(name, charindex('_',name)-1) 
from tempdb..sysobjects
where charindex('_',name) > 0 and
xtype = 'u' and not object_id('tempdb..'+name) is null

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

How to print spaces in Python?

Any of the following will work:

print 'Hello\nWorld'

print 'Hello'
print 'World'

Additionally, if you want to print a blank line (not make a new line), print or print() will work.

How to get relative path of a file in visual studio?

In Visual Studio please click 'Folder.ico' file in the Solution Explorer pane. Then you will see Properties pane. Change 'Copy to Output Directory' behavior to 'Copy if newer'. This will make Visual Studio copy the file to the output bin directory.

Now to get the file path using relative path just type:

string pathToIcoFile = AppDomain.CurrentDomain.BaseDirectory + "//FolderIcon//Folder.ico";

Hope that helped.

Automatic HTTPS connection/redirect with node.js/express

var express = require('express');
var app = express();

app.get('*',function (req, res) {
    res.redirect('https://<domain>' + req.url);
});

app.listen(80);

This is what we use and it works great!

How to find serial number of Android device?

Yes. It is a device hardware serial number and it is unique. So on api level 2.3 and above you can use android.os.Build.ANDROID_ID to get it. For below 2.3 API level use TelephonyManager.getDeviceID().

you can read this http://android-developers.blogspot.in/2011/03/identifying-app-installations.html

How do I check out a remote Git branch?

This will DWIM for a remote not named origin (documentation):

$ git checkout -t remote_name/remote_branch

To add a new remote, you will need to do the following first:

$ git remote add remote_name location_of_remote
$ git fetch remote_name

The first tells Git the remote exists, the second gets the commits.

ReactJS lifecycle method inside a function Component

You can use react-pure-lifecycle to add lifecycle functions to functional components.

Example:

import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
  componentDidMount(props) {
    console.log('I mounted! Here are my props: ', props);
  }
};

const Channels = props => (
<h1>Hello</h1>
)

export default lifecycle(methods)(Channels);

jQuery How to Get Element's Margin and Padding?

According to the jQuery documentation, shorthand CSS properties are not supported.

Depending on what you mean by "total padding", you may be able to do something like this:

var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');

How to connect android wifi to adhoc wifi?

If you have a Microsoft Virtual WiFi Miniport Adapter as one of the available network adapters, you may do the following:

  • Run Windows Command Processor (cmd) as Administrator
  • Type: netsh wlan set hostednetwork mode=allow ssid=NAME key=PASSWORD
  • Then: netsh wlan start hostednetwork
  • Open "Control Panel\Network and Internet\Network Connections"
  • Right-click on your active network adapter (the one that you use to connect on the internet) and then click Properties
  • Then open Sharing tab
  • Check "Allow other network users to connect..." and select your WiFi Miniport Adapter
  • Once finished, type: netsh wlan stop hostednetwork

That's it!

Source: How to connect android phone to an ad-hoc network without softwares.

Best way to define error codes/strings in Java?

As far as I am concerned, I prefer to externalize the error messages in a properties files. This will be really helpful in case of internationalization of your application (one properties file per language). It is also easier to modify an error message, and it won't need any re-compilation of the Java sources.

On my projects, generally I have an interface that contains errors codes (String or integer, it doesn't care much), which contains the key in the properties files for this error:

public interface ErrorCodes {
    String DATABASE_ERROR = "DATABASE_ERROR";
    String DUPLICATE_USER = "DUPLICATE_USER";
    ...
}

in the properties file:

DATABASE_ERROR=An error occurred in the database.
DUPLICATE_USER=The user already exists.
...

Another problem with your solution is the maintenability: you have only 2 errors, and already 12 lines of code. So imagine your Enumeration file when you will have hundreds of errors to manage!

Check whether a string is not null and not empty

What about isEmpty() ?

if(str != null && !str.isEmpty())

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.


To ignore whitespace as well:

if(str != null && !str.trim().isEmpty())

(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)

Wrapped in a handy function:

public static boolean empty( final String s ) {
  // Null-safe, short-circuit evaluation.
  return s == null || s.trim().isEmpty();
}

Becomes:

if( !empty( str ) )

How to find whether MySQL is installed in Red Hat?

If you're looking for the RPM.

rpm -qa | grep MySQL

Most of it's data is stored in /var/lib/mysql so that's another good place to look.

If it is installed

which mysql

will give you the location of the binary.

You could also do an

updatedb

and a

locate mysql

to find any mysql files.

Is there a way to avoid null check before the for-each loop iteration starts?

Null check in an enhanced for loop

public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
    return iterable == null ? Collections.<T>emptyList() : iterable;
}

Then use:

for (Object object : emptyIfNull(someList)) { ... }

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Requires PHP5.3:

$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("l Y-m-d H:i:s\n");
}

This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod.

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

Passing null arguments to C# methods

From C# 2.0:

private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

HTML input arrays

Follow it...

<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3];  // Displaying Selected array Value
foreach ($a as $v) {
    print_r($v); //print all array element.
}
?>

How do I convert a string to enum in TypeScript?

I got it working using the following code.

var green= "Green";
var color : Color= <Color>Color[green];

How to calculate percentage with a SQL statement

This one is working well in MS SQL. It transforms varchar to the result of two-decimal-places-limited float.

Select field1, cast(Try_convert(float,(Count(field2)* 100) / 
Try_convert(float, (Select Count(*) From table1))) as decimal(10,2)) as new_field_name 
From table1 
Group By field1, field2;

How to enable directory listing in apache web server

This one solved my issue which is SELinux setting:

chcon -R -t httpd_sys_content_t /home/*

Regular expression: find spaces (tabs/space) but not newlines

As @Eiríkr Útlendi noted, the accepted solution only considers two white space characters: the horizontal tab (U+0009), and a breaking space (U+0020). It does not consider other whitespace characters such as non-breaking spaces (which happen to be in the text I am trying to deal with). A more complete whitespace character listing is included on Wikipedia and also referenced in the linked Perl answer. A simple C# solution that accounts for these other characters can be built using character class subtraction

[\s-[\r\n]]

or, including Eiríkr Útlendi's solution, you get

[\s\u3000-[\r\n]]

Cannot install Aptana Studio 3.6 on Windows

Right click the installer and choose "Run as administrator". I suspect it needs administrator account to download and install Node JS during installation.

Python way to clone a git repository

With Dulwich tip you should be able to do:

from dulwich.repo import Repo
Repo("/path/to/source").clone("/path/to/target")

This is still very basic - it copies across the objects and the refs, but it doesn't yet create the contents of the working tree if you create a non-bare repository.

Make xargs handle filenames that contain spaces

Given the specific title of this post, here's my suggestion:

ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'

The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:

ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo

The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.

Select info from table where row has max date

SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group

That works to get the max date..join it back to your data to get the other columns:

Select group,max_date,checks
from table t
inner join 
(SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group)a
on a.group = t.group and a.max_date = date

Inner join functions as the filter to get the max record only.

FYI, your column names are horrid, don't use reserved words for columns (group, date, table).

Load a UIView from nib in Swift

let subviewArray = NSBundle.mainBundle().loadNibNamed("myXib", owner: self, options: nil)
return subviewArray[0]

iOS8 Beta Ad-Hoc App Download (itms-services)

I was struggling with this, my app was installing but not complete (almost 60% I can say) in iOS8, but in iOS7.1 it was working as expected. The error message popped was:

"Cannot install at this time". 

Finally Zillan's link helped me to get apple documentation. So, check:

  1. make sure the internet reachability in your device as you will be in local network/ intranet.
  2. Also make sure the address ax.init.itunes.apple.com is not getting blocked by your firewall/proxy (Just type this address in safari, a blank page must load).

As soon as I changed the proxy it installed completely. Hope it will help someone.

simple HTTP server in Java using only Java SE API

Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

Here's a kickoff example copypasted from their docs (to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source). You can just copy'n'paste'n'run it on Java 6+.

package com.stackoverflow.q3732109;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

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

public class Test {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}

Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.

Execute it and go to http://localhost:8000/test and you'll see the following response:

This is the response


As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.

multiple prints on the same line in Python

Use sys.stdout.write('Installing XXX... ') and sys.stdout.write('Done'). In this way, you have to add the new line by hand with "\n" if you want to recreate the print functionality. I think that it might be unnecessary to use curses just for this.

Android: How to detect double-tap?

combining "Bughi" "DoubleClickListner" and "Jayant Arora" Timer in one contained class:

public abstract class DoubleClickListener implements OnClickListener {

    private Timer timer = null;  //at class level;
    private int DELAY   = 400;

    private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds

    long lastClickTime = 0;

    @Override
    public void onClick(View v) {
        long clickTime = System.currentTimeMillis();
        if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
            processDoubleClickEvent(v);
        } else {
            processSingleClickEvent(v);
        }
        lastClickTime = clickTime;
    }



    public void processSingleClickEvent(final View v){

        final Handler handler=new Handler();
        final Runnable mRunnable=new Runnable(){
            public void run(){
                onSingleClick(v); //Do what ever u want on single click

            }
        };

        TimerTask timertask=new TimerTask(){
            @Override
            public void run(){
                handler.post(mRunnable);
            }
        };
        timer=new Timer();
        timer.schedule(timertask,DELAY);

    }

    public void processDoubleClickEvent(View v){
        if(timer!=null)
        {
            timer.cancel(); //Cancels Running Tasks or Waiting Tasks.
            timer.purge();  //Frees Memory by erasing cancelled Tasks.
        }
        onDoubleClick(v);//Do what ever u want on Double Click
    }

    public abstract void onSingleClick(View v);

    public abstract void onDoubleClick(View v);
}

and can be called as :

view.setOnClickListener(new DoubleClickListener() {

            @Override
            public void onSingleClick(View v) {

            }

            @Override
            public void onDoubleClick(View v) {

            }
        });

Javascript: best Singleton pattern

(1) UPDATE 2019: ES7 Version

class Singleton {
    static instance;

    constructor() {
        if (instance) {
            return instance;
        }

        this.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

(2) ES6 Version

class Singleton {
    constructor() {
        const instance = this.constructor.instance;
        if (instance) {
            return instance;
        }

        this.constructor.instance = this;
    }

    foo() {
        // ...
    }
}

console.log(new Singleton() === new Singleton());

Best solution found: http://code.google.com/p/jslibs/wiki/JavascriptTips#Singleton_pattern

function MySingletonClass () {

  if (arguments.callee._singletonInstance) {
    return arguments.callee._singletonInstance;
  }

  arguments.callee._singletonInstance = this;

  this.Foo = function () {
    // ...
  };
}

var a = new MySingletonClass();
var b = MySingletonClass();
console.log( a === b ); // prints: true

For those who want the strict version:

(function (global) {
  "use strict";
  var MySingletonClass = function () {

    if (MySingletonClass.prototype._singletonInstance) {
      return MySingletonClass.prototype._singletonInstance;
    }

    MySingletonClass.prototype._singletonInstance = this;

    this.Foo = function() {
      // ...
    };
  };

var a = new MySingletonClass();
var b = MySingletonClass();
global.result = a === b;

} (window));

console.log(result);

CSS to prevent child element from inheriting parent styles

Can't you style the forms themselves? Then, style the divs accordingly.

form
{
    /* styles */
}

You can always overrule inherited styles by making it important:

form
{
    /* styles */ !important
}

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

How to write subquery inside the OUTER JOIN Statement

I think you don't have to use sub query in this scenario.You can directly left outer join the DEPRMNT table .

While using Left Outer Join ,don't use columns in the RHS table of the join in the where condition, you ll get wrong output

List<T> OrderBy Alphabetical Order

You can also use

model.People = model.People.OrderBy(x => x.Name).ToList();

Does Django scale?

Today we use many web apps and sites for our needs. Most of them are highly useful. I will show you some of them used by python or django.

Washington Post

The Washington Post’s website is a hugely popular online news source to accompany their daily paper. Its’ huge amount of views and traffic can be easily handled by the Django web framework. Washington Post - 52.2 million unique visitors (March, 2015)

NASA

The National Aeronautics and Space Administration’s official website is the place to find news, pictures, and videos about their ongoing space exploration. This Django website can easily handle huge amounts of views and traffic. 2 million visitors monthly

The Guardian

The Guardian is a British news and media website owned by the Guardian Media Group. It contains nearly all of the content of the newspapers The Guardian and The Observer. This huge data is handled by Django. The Guardian (commenting system) - 41,6 million unique visitors (October, 2014)

YouTube

We all know YouTube as the place to upload cat videos and fails. As one of the most popular websites in existence, it provides us with endless hours of video entertainment. The Python programming language powers it and the features we love.

DropBox

DropBox started the online document storing revolution that has become part of daily life. We now store almost everything in the cloud. Dropbox allows us to store, sync, and share almost anything using the power of Python.

Survey Monkey

Survey Monkey is the largest online survey company. They can handle over one million responses every day on their rewritten Python website.

Quora

Quora is the number one place online to ask a question and receive answers from a community of individuals. On their Python website relevant results are answered, edited, and organized by these community members.

Bitly

A majority of the code for Bitly URL shortening services and analytics are all built with Python. Their service can handle hundreds of millions of events per day.

Reddit

Reddit is known as the front page of the internet. It is the place online to find information or entertainment based on thousands of different categories. Posts and links are user generated and are promoted to the top through votes. Many of Reddit’s capabilities rely on Python for their functionality.

Hipmunk

Hipmunk is an online consumer travel site that compares the top travel sites to find you the best deals. This Python website’s tools allow you to find the cheapest hotels and flights for your destination.

Click here for more: 25-of-the-most-popular-python-and-django-websites, What-are-some-well-known-sites-running-on-Django

MongoDB: Combine data from multiple collections into one..how?

Doing unions in MongoDB in a 'SQL UNION' fashion is possible using aggregations along with lookups, in a single query. Here is an example I have tested that works with MongoDB 4.0:

// Create employees data for testing the union.
db.getCollection('employees').insert({ name: "John", type: "employee", department: "sales" });
db.getCollection('employees').insert({ name: "Martha", type: "employee", department: "accounting" });
db.getCollection('employees').insert({ name: "Amy", type: "employee", department: "warehouse" });
db.getCollection('employees').insert({ name: "Mike", type: "employee", department: "warehouse"  });

// Create freelancers data for testing the union.
db.getCollection('freelancers').insert({ name: "Stephany", type: "freelancer", department: "accounting" });
db.getCollection('freelancers').insert({ name: "Martin", type: "freelancer", department: "sales" });
db.getCollection('freelancers').insert({ name: "Doug", type: "freelancer", department: "warehouse"  });
db.getCollection('freelancers').insert({ name: "Brenda", type: "freelancer", department: "sales"  });

// Here we do a union of the employees and freelancers using a single aggregation query.
db.getCollection('freelancers').aggregate( // 1. Use any collection containing at least one document.
  [
    { $limit: 1 }, // 2. Keep only one document of the collection.
    { $project: { _id: '$$REMOVE' } }, // 3. Remove everything from the document.

    // 4. Lookup collections to union together.
    { $lookup: { from: 'employees', pipeline: [{ $match: { department: 'sales' } }], as: 'employees' } },
    { $lookup: { from: 'freelancers', pipeline: [{ $match: { department: 'sales' } }], as: 'freelancers' } },

    // 5. Union the collections together with a projection.
    { $project: { union: { $concatArrays: ["$employees", "$freelancers"] } } },

    // 6. Unwind and replace root so you end up with a result set.
    { $unwind: '$union' },
    { $replaceRoot: { newRoot: '$union' } }
  ]);

Here is the explanation of how it works:

  1. Instantiate an aggregate out of any collection of your database that has at least one document in it. If you can't guarantee any collection of your database will not be empty, you can workaround this issue by creating in your database some sort of 'dummy' collection containing a single empty document in it that will be there specifically for doing union queries.

  2. Make the first stage of your pipeline to be { $limit: 1 }. This will strip all the documents of the collection except the first one.

  3. Strip all the fields of the remaining document by using a $project stage:

    { $project: { _id: '$$REMOVE' } }
    
  4. Your aggregate now contains a single, empty document. It's time to add lookups for each collection you want to union together. You may use the pipeline field to do some specific filtering, or leave localField and foreignField as null to match the whole collection.

    { $lookup: { from: 'collectionToUnion1', pipeline: [...], as: 'Collection1' } },
    { $lookup: { from: 'collectionToUnion2', pipeline: [...], as: 'Collection2' } },
    { $lookup: { from: 'collectionToUnion3', pipeline: [...], as: 'Collection3' } }
    
  5. You now have an aggregate containing a single document that contains 3 arrays like this:

    {
        Collection1: [...],
        Collection2: [...],
        Collection3: [...]
    }
    

    You can then merge them together into a single array using a $project stage along with the $concatArrays aggregation operator:

    {
      "$project" :
      {
        "Union" : { $concatArrays: ["$Collection1", "$Collection2", "$Collection3"] }
      }
    }
    
  6. You now have an aggregate containing a single document, into which is located an array that contains your union of collections. What remains to be done is to add an $unwind and a $replaceRoot stage to split your array into separate documents:

    { $unwind: "$Union" },
    { $replaceRoot: { newRoot: "$Union" } }
    
  7. Voilà. You now have a result set containing the collections you wanted to union together. You can then add more stages to filter it further, sort it, apply skip() and limit(). Pretty much anything you want.

Setting Windows PowerShell environment variables

Most answers aren't addressing UAC. This covers UAC issues.

First install PowerShell Community Extensions: choco install pscx via http://chocolatey.org/ (you may have to restart your shell environment).

Then enable pscx

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser #allows scripts to run from the interwebs, such as pcsx

Then use Invoke-Elevated

Invoke-Elevated {Add-PathVariable $args[0] -Target Machine} -ArgumentList $MY_NEW_DIR

HTML Image not displaying, while the src url works

You can try just putting the image in the source directory. You'd link it by replacing the file path with src="../imagenamehere.fileextension In your case, j3evn.jpg.

TypeScript static classes

This is one way:

class SomeClass {
    private static myStaticVariable = "whatever";
    private static __static_ctor = (() => { /* do static constructor stuff :) */ })();
}

__static_ctor here is an immediately invoked function expression. Typescript will output code to call it at the end of the generated class.

Update: For generic types in static constructors, which are no longer allowed to be referenced by static members, you will need an extra step now:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private ___static_ctor = (() => { var someClass:SomeClass<T> ; /* do static constructor stuff :) */ })();
    private static __static_ctor = SomeClass.prototype.___static_ctor();
}

In any case, of course, you could just call the generic type static constructor after the class, such as:

class SomeClass<T> {
    static myStaticVariable = "whatever";
    private __static_ctor = (() => { var example: SomeClass<T>; /* do static constructor stuff :) */ })();
}
SomeClass.prototype.__static_ctor();

Just remember to NEVER use this in __static_ctor above (obviously).

How to update SQLAlchemy row entry?

user.no_of_logins += 1
session.commit()

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

In response to the "when to use it?" question:

I often use a static (class) variable to assign a unique instance ID to every instance of a class. I use the same code in every class, it is very simple:

//Instance ID ----------------------------------------
    // Class variable holding the last assigned IID
    private static int xID = 0;
    // Lock to make threadsafe (can omit if single-threaded)
    private static object xIDLock = new object();
    // Private class method to return the next unique IID 
    //  - accessible only to instances of the class
    private static int NextIID()                    
    {
        lock (xIDLock) { return ++xID; }
    }
    // Public class method to report the last IID used 
    // (i.e. the number of instances created)
    public static int LastIID() { return xID; }
    // Instance readonly property containing the unique instance ID
    public readonly int IID = NextIID();
//-----------------------------------------------------

This illustrates a couple of points about static variables and methods:

  1. Static variables and methods are associated with the class, not any specific instance of the class.
  2. A static method can be called in the constructor of an instance - in this case, the static method NextIID is used to initialize the readonly property IID, which is the unique ID for this instance.

I find this useful because I develop applications in which swarms of objects are used and it is good to be able to track how many have been created, and to track/query individual instances.

I also use class variables to track things like totals and averages of properties of the instances which can be reported in real time. I think the class is a good place to keep summary information about all the instances of the class.

XSS prevention in JSP/Servlet web application

Managing XSS requires multiple validations, data from the client side.

  1. Input Validations (form validation) on the Server side. There are multiple ways of going about it. You can try JSR 303 bean validation(hibernate validator), or ESAPI Input Validation framework. Though I've not tried it myself (yet), there is an annotation that checks for safe html (@SafeHtml). You could in fact use Hibernate validator with Spring MVC for bean validations -> Ref
  2. Escaping URL requests - For all your HTTP requests, use some sort of XSS filter. I've used the following for our web app and it takes care of cleaning up the HTTP URL request - http://www.servletsuite.com/servlets/xssflt.htm
  3. Escaping data/html returned to the client (look above at @BalusC explanation).

Semaphore vs. Monitors - what's the difference?

A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal() on the semaphore when a file is downloaded. The consumer calls wait() on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.

A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait() can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.

A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.

A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized keyword. The synchronized keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.

Best way to compare 2 XML documents in Java

Xom has a Canonicalizer utility which turns your DOMs into a regular form, which you can then stringify and compare. So regardless of whitespace irregularities or attribute ordering, you can get regular, predictable comparisons of your documents.

This works especially well in IDEs that have dedicated visual String comparators, like Eclipse. You get a visual representation of the semantic differences between the documents.

How do I get only directories using Get-ChildItem?

Use

Get-ChildItem -dir #lists only directories
Get-ChildItem -file #lists only files

If you prefer aliases, use

ls -dir #lists only directories
ls -file #lists only files

or

dir -dir #lists only directories
dir -file #lists only files

To recurse subdirectories as well, add -r option.

ls -dir -r #lists only directories recursively
ls -file -r #lists only files recursively 

Tested on PowerShell 4.0, PowerShell 5.0 (Windows 10), PowerShell Core 6.0 (Windows 10, Mac, and Linux), and PowerShell 7.0 (Windows 10, Mac, and Linux).

Note: On PowerShell Core, symlinks are not followed when you specify the -r switch. To follow symlinks, specify the -FollowSymlink switch with -r.

Note 2: PowerShell is now cross-platform, since version 6.0. The cross-platform version was originally called PowerShell Core, but the the word "Core" has been dropped since PowerShell 7.0+.

Get-ChildItem documentation: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem

how to use DEXtoJar

The below url is doing same as above answers. Instead of downloading some jar files and doing much activities, you can try to decompile by:

http://apk-deguard.com/

"getaddrinfo failed", what does that mean?

The problem, in my case, was that some install at some point defined an environment variable http_proxy on my machine when I had no proxy.

Removing the http_proxy environment variable fixed the problem.

Detect Route Change with react-router

If you want to listen to the history object globally, you'll have to create it yourself and pass it to the Router. Then you can listen to it with its listen() method:

// Use Router from react-router, not BrowserRouter.
import { Router } from 'react-router';

// Create history object.
import createHistory from 'history/createBrowserHistory';
const history = createHistory();

// Listen to history changes.
// You can unlisten by calling the constant (`unlisten()`).
const unlisten = history.listen((location, action) => {
  console.log(action, location.pathname, location.state);
});

// Pass history to Router.
<Router history={history}>
   ...
</Router>

Even better if you create the history object as a module, so you can easily import it anywhere you may need it (e.g. import history from './history';

Escaping single quote in PHP when inserting into MySQL

You can do the following which escapes both PHP and MySQL.

<?
$text = '<a href="javascript:window.open(\\\'http://www.google.com\\\');"></a>';
?> 

This will reflect MySQL as

<a href="javascript:window.open('http://www.google.com');"></a>

How does it work?

We know that both PHP and MySQL apostrophes can be escaped with backslash and then apostrophe.

\'

Because we are using PHP to insert into MySQL, we need PHP to still write the backslash to MySQL so it too can escape it. So we use the PHP escape character of backslash-backslash together with backslash-apostrophe to achieve this.

\\\'

Compare object instances for equality by their attributes

If you want to get an attribute-by-attribute comparison, and see if and where it fails, you can use the following list comprehension:

[i for i,j in 
 zip([getattr(obj_1, attr) for attr in dir(obj_1)],
     [getattr(obj_2, attr) for attr in dir(obj_2)]) 
 if not i==j]

The extra advantage here is that you can squeeze it one line and enter in the "Evaluate Expression" window when debugging in PyCharm.

Signed to unsigned conversion in C - is it always safe?

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

So it is safe in the sense of that the result might be huge and wrong, but it will never crash.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use in Eloquent. Add on top of your model

protected $table = 'table_name as alias'

//table_name should be exact as in your database

..then use in your query like

ModelName::query()->select(alias.id, alias.name)

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

How to show/hide JPanels in a JFrame?

You can hide a JPanel by calling setVisible(false). For example:

public static void main(String args[]){
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    final JPanel p = new JPanel();
    p.add(new JLabel("A Panel"));
    f.add(p, BorderLayout.CENTER);

    //create a button which will hide the panel when clicked.
    JButton b = new JButton("HIDE");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
                p.setVisible(false);
        }
    });

    f.add(b,BorderLayout.SOUTH);
    f.pack();
    f.setVisible(true);
}

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.

enter image description here

So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.

In the below picture I highlighted the input boxes that I've modified: enter image description here

Multiple line code example in Javadoc comment

/**
 * <blockquote><pre>
 * {@code
 * public Foo(final Class<?> klass) {
 *     super();
 *     this.klass = klass;
 * }
 * }
 * </pre></blockquote>
 **/
  • <pre/> is required for preserving lines.
  • {@code must has its own line
  • <blockquote/> is just for indentation.
public Foo(final Class<?> klass) {
    super();
    this.klass = klass;
}


UPDATE with JDK8

The minimum requirements for proper codes are <pre/> and {@code}.

/**
 * test.
 *
 * <pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre>
 */

yields

 <T> void test(Class<? super T> type) {
     System.out.printf("hello, world\n");
 }

And an optional surrounding <blockquote/> inserts an indentation.

/**
 * test.
 *
 * <blockquote><pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre></blockquote>
 */

yields

     <T> void test(Class<? super T> type) {
         System.out.printf("hello, world\n");
     }

Inserting <p> or surrounding with <p> and </p> yields warnings.

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

Unsuccessful append to an empty NumPy array

numpy.append is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:

import numpy

old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]

I think you might be able to achieve your goal by doing something like:

result = numpy.zeros((10,))
result[0:2] = [1, 2]

# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]

Update:

If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:

import numpy as np

a = np.array([0., 1.])
b = np.array([2., 3.])

temp = []
while True:
    rnd = random.randint(0, 100)
    if rnd > 50:
        temp.append(a)
    else:
        temp.append(b)
    if rnd == 0:
         break

 result = np.array(temp)

In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.

new update

The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b) the shapes of a and b need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.

How to properly create composite primary keys - MYSQL

@AlexCuse I wanted to add this as comment to your answer but gave up after making multiple failed attempt to add newlines in comments.

That said, t1ID is unique in table_1 but that doesn't makes it unique in INFO table as well.

For example:

Table_1 has:
Id Field
1 A
2 B

Table_2 has:
Id Field
1 X
2 Y

INFO then can have:
t1ID t2ID field
1 1 some
1 2 data
2 1 in-each
2 2 row

So in INFO table to uniquely identify a row you need both t1ID and t2ID

/bin/sh: pushd: not found

sudo dpkg-reconfigure dash 

Then select no.

SQL Server 2008 - Help writing simple INSERT Trigger

check this code:

CREATE TRIGGER trig_Update_Employee ON [EmployeeResult] FOR INSERT AS Begin   
    Insert into Employee (Name, Department)  
    Select Distinct i.Name, i.Department   
        from Inserted i
        Left Join Employee e on i.Name = e.Name and i.Department = e.Department
        where e.Name is null
End

How to decrease prod bundle size?

The following solution assumes you are serving your dist/ folder using nodejs. Please use the following app.js in root level

const express = require('express'),http = require('http'),path = require('path'),compression = require('compression');

const app = express();

app.use(express.static(path.join(__dirname, 'dist')));
app.use(compression()) //compressing dist folder 
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
})

const port = process.env.PORT || '4201';
app.set('port', port);

const server = http.createServer(app);
server.listen(port, () => console.log('Running at port ' + port))

Make sure you install dependencies;

npm install compression --save
npm install express --save;

Now build the app

ng build --prod --build-optimizer

If you want to further compress the build say reduce 300kb(approx) from , then follow the below process;

Create a folder called vendor inside the src folder and inside vendor folder create a file rxjs.ts and paste the below code in it;

export {Subject} from 'rxjs/Subject';
export {Observable} from 'rxjs/Observable';
export {Subscription} from 'rxjs/Subscription';

And then add the follwing in the tsconfig.json file in your angular-cli application. Then in the compilerOptions , add the following json;

"paths": {
      "rxjs": [
        "./vendor/rxjs.ts"
      ]
    }

This will make your build size way too smaller. In my project I reduced the size from 11mb to 1mb. Hope it helps

Char array declaration and initialization in C

This is another C example of where the same syntax has different meanings (in different places). While one might be able to argue that the syntax should be different for these two cases, it is what it is. The idea is that not that it is "not allowed" but that the second thing means something different (it means "pointer assignment").

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

You need to add JQuery before adding bootstrap-

<!-- JQuery Core JavaScript -->
<script src="lib/js/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="lib/js/bootstrap.min.js"></script>

How can I transform string to UTF-8 in C#?

As you know the string is coming in as Encoding.Default you could simply use:

byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);

Another thing you may have to remember: If you are using Console.WriteLine to output some strings, then you should also write Console.OutputEncoding = System.Text.Encoding.UTF8;!!! Or all utf8 strings will be outputed as gbk...

How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Default argument values in JavaScript functions

You have to check if the argument is undefined:

function func(a, b) {
    if (a === undefined) a = "default value";
    if (b === undefined) b = "default value";
}

Also note that this question has been answered before.

Can I have an onclick effect in CSS?

How about a pure CSS solution without being (that) hacky?

enter image description here

_x000D_
_x000D_
.page {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  background-color: #121519;_x000D_
  color: whitesmoke;_x000D_
}_x000D_
_x000D_
.controls {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.arrow {_x000D_
  cursor: pointer;_x000D_
  transition: filter 0.3s ease 0.3s;_x000D_
}_x000D_
_x000D_
.arrow:active {_x000D_
  filter: drop-shadow(0 0 0 steelblue);_x000D_
  transition: filter 0s;_x000D_
}
_x000D_
<body class="page">_x000D_
  <div class="controls">_x000D_
    <div class="arrow">_x000D_
      <img src="https://i.imgur.com/JGUoNfS.png" />_x000D_
    </div>_x000D_
  </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

@TylerH has a great response but its a pretty complex solution. I have a solution for those of you that just want a simple "onclick" effect with pure css without a bunch of extra elements.

We will simply use css transitions. You could probably do similar with animations.

The trick is to change the delay for the transition so that it will last when the user clicks.

.arrowDownContainer:active,
.arrowDownContainer.clicked {
  filter: drop-shadow(0px 0px 0px steelblue);
  transition: filter 0s;
}

Here I add the "clicked" class as well so that javascript can also provide the effect if it needs to. I use 0px drop-shadow filter because it will highlight the given transparent graphic blue this way for my case.

I have a filter at 0s here so that it wont take effect. When the effect is released I can then add the transition with a delay so that it will provide a nice "clicked" effect.

.arrowDownContainer {
  cursor: pointer;
  position: absolute;
  bottom: 0px;
  top: 490px;
  left: 108px;
  height: 222px;
  width: 495px;
  z-index: 3;
  transition: filter 0.3s ease 0.3s;
}

This allows me to set it up so that when the user clicks the button, it highlights blue then fades out slowly (you could, of course, use other effects as well).

While you are limited here in the sense that the animation to highlight is instant, it does still provide the desired effect. You could likely use this trick with animation to produce a smoother overall transition.

enter image description here

enter image description here

Can't create handler inside thread that has not called Looper.prepare()

that's what i did.

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        Toast(...);
    }
});

Visual components are "locked" to changes from outside threads. So, since the toast shows stuff on the main screen that is managed by the main thread, you need to run this code on that thread. Hope that helps:)

How to get time difference in minutes in PHP

It worked on my programs, i'am using date_diff, you can check date_diff manual on here.

$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);

You get results what do you want.

Exercises to improve my Java programming skills

If you wanted to learn some GUI, may be tic tac toe is good. Even for console, I still find that is a fun problem. Not challenging but a little bit fun. Later you can advance some other games or port that game to GUI, client server or java applet for the web. I think if you want to learn something and get fun as well, game is a good choice:)

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

Here is my solution, but in python (I tried and failed to find any post on the topic related to python):

# modify table for legacy version which did not have leave type and leave time columns of rings3 table.
sql = 'PRAGMA table_info(rings3)' # get table info. returns an array of columns.
result = inquire (sql) # call homemade function to execute the inquiry
if len(result)<= 6: # if there are not enough columns add the leave type and leave time columns
    sql = 'ALTER table rings3 ADD COLUMN leave_type varchar'
    commit(sql) # call homemade function to execute sql
    sql = 'ALTER table rings3 ADD COLUMN leave_time varchar'
    commit(sql)

I used PRAGMA to get the table information. It returns a multidimensional array full of information about columns - one array per column. I count the number of arrays to get the number of columns. If there are not enough columns, then I add the columns using the ALTER TABLE command.

How to check if directory exists in %PATH%?

I took your implementation using the for loop and extended it into something that iterates through all elements of the path. Each iteration of the for loop removes the first element of the path (%p) from the entire path (held in %q and %r).

@echo off
SET MYPATHCOPY=%PATH%

:search
for /f "delims=; tokens=1,2*" %%p in ("%MYPATHCOPY%") do (
   @echo %%~p
   SET MYPATHCOPY=%%~q;%%~r
)

if "%MYPATHCOPY%"==";" goto done;
goto search;

:done

Sample output:

Z:\>path.bat
C:\Program Files\Microsoft DirectX SDK (November 2007)\Utilities\Bin\x86
c:\program files\imagemagick-6.3.4-q16
C:\WINDOWS\system32
C:\WINDOWS
C:\SFU\common\
c:\Program Files\Debugging Tools for Windows
C:\Program Files\Nmap

Easiest way to ignore blank lines when reading a file in Python

If you want you can just put what you had in a list comprehension:

names_list = [line for line in open("names.txt", "r").read().splitlines() if line]

or

all_lines = open("names.txt", "r").read().splitlines()
names_list = [name for name in all_lines if name]

splitlines() has already removed the line endings.

I don't think those are as clear as just looping explicitly though:

names_list = []
with open('names.txt', 'r') as _:
    for line in _:
        line = line.strip()
        if line:
            names_list.append(line)

Edit:

Although, filter looks quite readable and concise:

names_list = filter(None, open("names.txt", "r").read().splitlines())

Where is Python language used?

Your categorization is not correct:

php, asp and ColdFusion are mostly used for websites, that is correct, but .net is definetly much more than asp you can build desktop applications, too (Paint.NET). I don't know about ColdFusion, but PHP can also be used to write desktop applications.

On the other hand C,C++ are not really often used for web programming, But it can be used for web programming (cgit). Java is definetly a language to develop web applications (spring and much more).

Python is a scripting language like PHP, Perl, Ruby and so much more. It can be used for web programming (django, Zope, Google App Engine, and much more). But it also can be used for desktop applications (Blender 3D, or even for games pygame).

Python can also be translated into binary code like java.

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

Check that you have a proper JVM SDK setting in IntelliJ Properties. If invalidate-cache-and-restart isn't enough, check that your are using the proper JVM SDK, such as Java 1.7.

Look in: Preferences -> IDE Settings -> Scala -> JVM SDK

Or right click your project -> Open Module Settings -> Project Settings -> Project -> Project SDK -> (Set to Java 1.7)

Open Module Settings -> Platform Settings -> SDKs -> (Ensure that there is a Java 1.7, otherwise you'll need to add it)

If you've made a change, then it's probably best to re-run Invalidate Cache & Restart.

Check existence of input argument in a Bash shell script

It is:

if [ $# -eq 0 ]
  then
    echo "No arguments supplied"
fi

The $# variable will tell you the number of input arguments the script was passed.

Or you can check if an argument is an empty string or not like:

if [ -z "$1" ]
  then
    echo "No argument supplied"
fi

The -z switch will test if the expansion of "$1" is a null string or not. If it is a null string then the body is executed.

What are the ways to make an html link open a folder

A bit late to the party, but I had to solve this for myself recently, though slightly different, it might still help someone with similar circumstances to my own.

I'm using xampp on a laptop to run a purely local website app on windows. (A very specific environment I know). In this instance, I use a html link to a php file and run:

shell_exec('cd C:\path\to\file');
shell_exec('start .');

This opens a local Windows explorer window.

How can I format DateTime to web UTC format?

The best format to use is "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK".

The last K on string will be changed to 'Z' if the date is UTC or with timezone (+-hh:mm) if is local. (http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)

As LukeH said, is good to use the ToUniversalTime if you want that all the dates will be UTC.

The final code is:

string foo = yourDateTime.ToUniversalTime()
                         .ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK");

JavaScript array to CSV

The following code were written in ES6 and it will work in most of the browsers without an issue.

_x000D_
_x000D_
var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];_x000D_
_x000D_
// Construct the comma seperated string_x000D_
// If a column values contains a comma then surround the column value by double quotes_x000D_
const csv = test_array.map(row => row.map(item => (typeof item === 'string' && item.indexOf(',') >= 0) ? `"${item}"`: String(item)).join(',')).join('\n');_x000D_
_x000D_
// Format the CSV string_x000D_
const data = encodeURI('data:text/csv;charset=utf-8,' + csv);_x000D_
_x000D_
// Create a virtual Anchor tag_x000D_
const link = document.createElement('a');_x000D_
link.setAttribute('href', data);_x000D_
link.setAttribute('download', 'export.csv');_x000D_
_x000D_
// Append the Anchor tag in the actual web page or application_x000D_
document.body.appendChild(link);_x000D_
_x000D_
// Trigger the click event of the Anchor link_x000D_
link.click();_x000D_
_x000D_
// Remove the Anchor link form the web page or application_x000D_
document.body.removeChild(link);
_x000D_
_x000D_
_x000D_

Check if a varchar is a number (TSQL)

DECLARE @A nvarchar(100) = '12'
IF(ISNUMERIC(@A) = 1)
BEGIN
    PRINT 'YES NUMERIC'
END

The OutputPath property is not set for this project

I had exact same error after adding a new configuration via ConfigurationManager in Visual Studio.

It turned out when the 'Production' configuration was added for the whole solution (and each project) the OutputPath element was not added to the .csproj files.

To fix, I went to the Build tab in project properties, changed OutputPath from \bin\Production\ to \bin\Production (deleted trailing \) and saved changes. This forced creation of the OutputPath element in the .csproj file and the project has built successfully.

Sounds like a glitch to me.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

Files "LICENSE.txt" and "NOTICE.txt" are case sensitive. So for SPring android library I had to add

android {
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/notice.txt'
    }
}

NuGet behind a proxy

The solution for me was to include

<configuration>
  <config>
    <add key="http_proxy" value="http://<IP>:<Port>" />
    <add key="http_proxy.user" value="<user>" />
    <add key="http_proxy.password" value="<password>" />
  </config>
</configuration>

In the nuget.config file.

Add quotation at the start and end of each line in Notepad++

  • Place your cursor at the end of the text.
  • Press SHIFT and ->. The cursor will move to the next line.
  • Press CTRL-F and type , in "Replace with:" and press ENTER.

You will need to put a quote at the beginning of your first text and the end of your last.

'node' is not recognized as an internal or an external command, operable program or batch file while using phonegap/cordova

In Windows, you need to set node.js folder path into system variables or user variables.

1) open Control Panel -> System and Security -> System -> Advanced System Settings -> Environment Variables

2) in "User variables" or "System variables" find variable PATH and add node.js folder path as value. Usually it is C:\Program Files\nodejs;. If variable doesn't exists, create it.

3) Restart your IDE or computer.

It is useful add also "npm" and "Git" paths as variable, separated by semicolon.

What is the most effective way to get the index of an iterator of an std::vector?

Beside int float string etc., you can put extra data to .second when using diff. types like:

std::map<unsigned long long int, glm::ivec2> voxels_corners;
std::map<unsigned long long int, glm::ivec2>::iterator it_corners;

or

struct voxel_map {
    int x,i;
};

std::map<unsigned long long int, voxel_map> voxels_corners;
std::map<unsigned long long int, voxel_map>::iterator it_corners;

when

long long unsigned int index_first=some_key; // llu in this case...
int i=0;
voxels_corners.insert(std::make_pair(index_first,glm::ivec2(1,i++)));

or

long long unsigned int index_first=some_key;
int index_counter=0;
voxel_map one;
one.x=1;
one.i=index_counter++;

voxels_corners.insert(std::make_pair(index_first,one));

with right type || structure you can put anything in the .second including a index number that is incremented when doing an insert.

instead of

it_corners - _corners.begin()

or

std::distance(it_corners.begin(), it_corners)

after

it_corners = voxels_corners.find(index_first+bdif_x+x_z);

the index is simply:

int vertice_index = it_corners->second.y;

when using the glm::ivec2 type

or

int vertice_index = it_corners->second.i;

in case of the structure data type

How do I set a program to launch at startup

It`s a so easy solution:

To Add

Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.SetValue("Your Application Name", Application.ExecutablePath);

To Remove

Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
key.DeleteValue("Your Application Name", false);

How to send an email using PHP?

If you are interested in html formatted email, make sure to pass Content-type: text/html; in the header. Example:

// multiple recipients
$to  = '[email protected]' . ', '; // note the comma
$to .= '[email protected]';

// subject
$subject = 'Birthday Reminders for August';

// message
$message = '
<html>
<head>
  <title>Birthday Reminders for August</title>
</head>
<body>
  <p>Here are the birthdays upcoming in August!</p>
  <table>
    <tr>
      <th>Person</th><th>Day</th><th>Month</th><th>Year</th>
    </tr>
    <tr>
      <td>Joe</td><td>3rd</td><td>August</td><td>1970</td>
    </tr>
    <tr>
      <td>Sally</td><td>17th</td><td>August</td><td>1973</td>
    </tr>
  </table>
</body>
</html>
';

// To send HTML mail, the Content-type header must be set
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Additional headers
$headers .= 'To: Mary <[email protected]>, Kelly <[email protected]>' . "\r\n";
$headers .= 'From: Birthday Reminder <[email protected]>' . "\r\n";
$headers .= 'Cc: [email protected]' . "\r\n";
$headers .= 'Bcc: [email protected]' . "\r\n";

// Mail it
mail($to, $subject, $message, $headers);

For more details, check php mail function.

Excel Date Conversion from yyyymmdd to mm/dd/yyyy

for converting dd/mm/yyyy to mm/dd/yyyy

=DATE(RIGHT(a1,4),MID(a1,4,2),LEFT(a1,2))

How to take keyboard input in JavaScript?

You should register an event handler on the window or any element that you want to observe keystrokes on, and use the standard key values instead of keyCode. This modified code from MDN will respond to keydown when the left, right, up, or down arrow keys are pressed:

_x000D_
_x000D_
window.addEventListener("keydown", function (event) {_x000D_
  if (event.defaultPrevented) {_x000D_
    return; // Do nothing if the event was already processed_x000D_
  }_x000D_
_x000D_
  switch (event.key) {_x000D_
    case "ArrowDown":_x000D_
      // code for "down arrow" key press._x000D_
      break;_x000D_
    case "ArrowUp":_x000D_
      // code for "up arrow" key press._x000D_
      break;_x000D_
    case "ArrowLeft":_x000D_
      // code for "left arrow" key press._x000D_
      break;_x000D_
    case "ArrowRight":_x000D_
      // code for "right arrow" key press._x000D_
      break;_x000D_
    default:_x000D_
      return; // Quit when this doesn't handle the key event._x000D_
  }_x000D_
_x000D_
  // Cancel the default action to avoid it being handled twice_x000D_
  event.preventDefault();_x000D_
}, true);_x000D_
// the last option dispatches the event to the listener first,_x000D_
// then dispatches event to window
_x000D_
_x000D_
_x000D_

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

babel-loader jsx SyntaxError: Unexpected token

Add "babel-preset-react"

npm install babel-preset-react

and add "presets" option to babel-loader in your webpack.config.js

(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)

Here is an example webpack.config.js:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
      {
        presets:['react']
      }
}

Recently Babel 6 was released and there was a major change: https://babeljs.io/blog/2015/10/29/6.0.0

If you are using react 0.14, you should use ReactDOM.render() (from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog

UPDATE 2018

Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:

npm install babel-loader babel-preset-react

Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['react']
        }
      }
    ],
  }

Truncate (not round off) decimal numbers in javascript

I thought I'd throw in an answer using | since it is simple and works well.

truncate = function(number, places) {
  var shift = Math.pow(10, places);

  return ((number * shift) | 0) / shift;
};

What's the difference between ".equals" and "=="?

== is an operator. equals is a method defined in the Object class

== checks if two objects have the same address in the memory and for primitive it checks if they have the same value.equals method on the other hand checks if the two objects which are being compared have an equal value(depending on how ofcourse the equals method has been implemented for the objects. equals method cannot be applied on primitives(which means that if a is a primitive a.equals(someobject) is not allowed, however someobject.equals(a) is allowed).

What is a smart pointer and when should I use one?

Most kinds of smart pointers handle disposing of the pointer-to object for you. It's very handy because you don't have to think about disposing of objects manually anymore.

The most commonly-used smart pointers are std::tr1::shared_ptr (or boost::shared_ptr), and, less commonly, std::auto_ptr. I recommend regular use of shared_ptr.

shared_ptr is very versatile and deals with a large variety of disposal scenarios, including cases where objects need to be "passed across DLL boundaries" (the common nightmare case if different libcs are used between your code and the DLLs).

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

Get an array of list element contents in jQuery

var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });

...should do the trick. To get the final output you're looking for, join() plus some concatenation will do nicely:

var quotedCSV = '"' + optionTexts.join('", "') + '"';

How do I wait for an asynchronously dispatched block to finish?

Here is an alternative from one of my tests:

__block BOOL success;
NSCondition *completed = NSCondition.new;
[completed lock];

STAssertNoThrow([self.client asyncSomethingWithCompletionHandler:^(id value) {
    success = value != nil;
    [completed lock];
    [completed signal];
    [completed unlock];
}], nil);    
[completed waitUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
[completed unlock];
STAssertTrue(success, nil);

remove borders around html input

Try this

#generic_search_button
{
    float: left;
    width: 24px; /*new width*/
    height: 24px; /*new width*/
    border: none !important; /* no border and override any inline styles*/
    margin-top: 7px;
    cursor: pointer;
    background-color: White;
    background-image: url(/Images/search.png);
    background-repeat: no-repeat;
    background-position: center center;
}

I think the image size might be wrong

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

You don't need to downgrade your gulp from gulp 4. Use gulp.series() to combine multiple tasks. At first install gulp globally with

npm install --global gulp-cli

and then install locally on your working directory with

npm install --save-dev gulp

see details here

Example:

package.json

{
  "name": "gulp-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.26.3",
    "gulp": "^4.0.0",
    "gulp-sass": "^4.0.2"
  },
  "dependencies": {
    "bootstrap": "^4.3.1",
    "jquery": "^3.3.1",
    "popper.js": "^1.14.7"
  }
}

gulpfile.js

var gulp = require("gulp");
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();

// Specific Task
function js() {
    return gulp
    .src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/umd/popper.min.js'])
    .pipe(gulp.dest('src/js'))
    .pipe(browserSync.stream());
}
gulp.task(js);

// Specific Task
function gulpSass() {
    return gulp
    .src(['src/scss/*.scss'])
    .pipe(sass())
    .pipe(gulp.dest('src/css'))
    .pipe(browserSync.stream());
}
gulp.task(gulpSass);

// Run multiple tasks
gulp.task('start', gulp.series(js, gulpSass));

Run gulp start to fire multiple tasks & run gulp js or gulp gulpSass for specific task.

I want to remove double quotes from a String

str = str.replace(/^"(.*)"$/, '$1');

This regexp will only remove the quotes if they are the first and last characters of the string. F.ex:

"I am here"  => I am here (replaced)
I "am" here  => I "am" here (untouched)
I am here"   => I am here" (untouched)

Bootstrap 4 Dropdown Menu not working?

You need to enqueue the script bootstrap.js or bootstrap.min.js. I had the same problem with bootstrap 4.5.3 and the menu worked when I enqueued one of the above scripts. It can be either.

compareTo() vs. equals()

compareTo has do do more work if the strings have different lengths. equals can just return false, while compareTo must always examine enough characters to find the sorting order.

How to echo text during SQL script execution in SQLPLUS

The prompt command will echo text to the output:

prompt A useful comment.
select(*) from TableA;

Will be displayed as:

SQL> A useful comment.
SQL> 
  COUNT(*)
----------
     0

JQUERY: Uncaught Error: Syntax error, unrecognized expression

try

console.log($("#"+d));

your solution is passing the double quotes as part of the string.

setContentView(R.layout.main); error

Just take 2 steps and problem would be more likely to get solved:

Step 1: Clean your project by clicking Project -> Clean.

Step 2: Rebuild your project by clicking Project -> Build All.

Also make sure that your layout xml files are syntax error free and you don't have any image which has non-acceptable names (such as a "-" between image name).

Also I request you to have a look at problems window and let me know what errors are being shown there.

Get specific line from text file using just shell script

If for example you want to get the lines 10 to 20 of a file you can use each of these two methods:

head -n 20 york.txt | tail -11

or

sed -n '10,20p' york.txt 

p in above command stands for printing.

Here's what you'll see: enter image description here

JavaScript getElementByID() not working

Because when the script executes the browser has not yet parsed the <body>, so it does not know that there is an element with the specified id.

Try this instead:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = (function () {
            var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('Dhoor shala!');
            };
        });
    </script>
    </head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
</form>
</body>
</html>

Note that you may as well use addEventListener instead of window.onload = ... to make that function only execute after the whole document has been parsed.

<> And Not In VB.NET

I'm a total noob, I came here to figure out VB's 'not equal to' syntax, so I figured I'd throw it in here in case someone else needed it:

<%If Not boolean_variable%>Do this if boolean_variable is false<%End If%>

How can I flush GPU memory using CUDA (physical reset is unavailable)

check what is using your GPU memory with

sudo fuser -v /dev/nvidia*

Your output will look something like this:

                     USER        PID  ACCESS COMMAND
/dev/nvidia0:        root       1256  F...m  Xorg
                     username   2057  F...m  compiz
                     username   2759  F...m  chrome
                     username   2777  F...m  chrome
                     username   20450 F...m  python
                     username   20699 F...m  python

Then kill the PID that you no longer need on htop or with

sudo kill -9 PID.

In the example above, Pycharm was eating a lot of memory so I killed 20450 and 20699.

Importing CSV with line breaks in Excel 2007

Replace the separator with TAB(\t) instead of comma(,). Then open the file in your editor (Notepad etc.), copy the content from there, then paste it in the Excel file.

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

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

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Select From all tables - MySQL

Improve to @inno answer

delimiter //

DROP PROCEDURE IF EXISTS get_product;  
CREATE PROCEDURE get_product()
BEGIN
   DECLARE i VARCHAR(100); 
   DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
   OPEN cur1;

   read_loop: LOOP
       FETCH cur1 INTO i;
    
       SELECT i; -- printing table name
    
       SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%'); 
       PREPARE stmt1 FROM @s;
       EXECUTE stmt1;
       DEALLOCATE PREPARE stmt1;

   END LOOP read_loop;

   CLOSE cur1;
END//

delimiter ;

call get_product();

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

Skip first entry in for loop in python?

The more_itertools project extends itertools.islice to handle negative indices.

Example

import more_itertools as mit

iterable = 'ABCDEFGH'
list(mit.islice_extended(iterable, 1, -1))
# Out: ['B', 'C', 'D', 'E', 'F', 'G']

Therefore, you can elegantly apply it slice elements between the first and last items of an iterable:

for car in mit.islice_extended(cars, 1, -1):
    # do something

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

Then apart from these 4, we have

foldByKey which is same as reduceByKey but with a user defined Zero Value.

AggregateByKey takes 3 parameters as input and uses 2 functions for merging(one for merging on same partitions and another to merge values across partition. The first parameter is ZeroValue)

whereas

ReduceBykey takes 1 parameter only which is a function for merging.

CombineByKey takes 3 parameter and all 3 are functions. Similar to aggregateBykey except it can have a function for ZeroValue.

GroupByKey takes no parameter and groups everything. Also, it is an overhead for data transfer across partitions.

Using union and count(*) together in SQL query

SELECT tem.name, COUNT(*) 
FROM (
  SELECT name FROM results
  UNION ALL
  SELECT name FROM archive_results
) AS tem
GROUP BY name
ORDER BY name

fatal: could not read Username for 'https://github.com': No such file or directory

If you want to continue use https instead ssh, and avoid type into your username and password for security reason.

You can also try Github OAuth token, then you can do git config remote.origin.url 'https://{token}@github.com/{username}/{project}.git' or git remote add origin 'https://{token}@github.com/{username}/{project}.git'

This works for me!

How to determine the IP address of a Solaris system

/usr/sbin/ifconfig -a | awk 'BEGIN { count=0; } { if ( $1 ~ /inet/ ) { count++; if( count==2 ) { print $2; } } }'

This will list down the exact ip address for the machine

What is the (function() { } )() construct in JavaScript?

That is saying execute immediately.

so if I do:

var val = (function(){
     var a = 0;  // in the scope of this function
     return function(x){
         a += x;
         return a;
     };
})();

alert(val(10)); //10
alert(val(11)); //21

Fiddle: http://jsfiddle.net/maniator/LqvpQ/


Second Example:

var val = (function(){
     return 13 + 5;
})();

alert(val); //18

Using Enum values as String literals

As far as I know, the only way to get the name would be

Mode.mode1.name();

If you really need it this way, however, you could do:

public enum Modes {
    mode1 ("Mode1"),
    mode2 ("Mode2"),
    mode3 ("Mode3");

    private String name;       

    private Modes(String s) {
        name = s;
    }
}

CSS3 transition events

In Opera 12 when you bind using the plain JavaScript, 'oTransitionEnd' will work:

document.addEventListener("oTransitionEnd", function(){
    alert("Transition Ended");
});

however if you bind through jQuery, you need to use 'otransitionend'

$(document).bind("otransitionend", function(){
    alert("Transition Ended");
});

In case you are using Modernizr or bootstrap-transition.js you can simply do a change:

var transEndEventNames = {
    'WebkitTransition' : 'webkitTransitionEnd',
    'MozTransition'    : 'transitionend',
    'OTransition'      : 'oTransitionEnd otransitionend',
    'msTransition'     : 'MSTransitionEnd',
    'transition'       : 'transitionend'
},
transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];

You can find some info here as well http://www.ianlunn.co.uk/blog/articles/opera-12-otransitionend-bugs-and-workarounds/

How to execute a stored procedure within C# program

SqlConnection conn = null;
SqlDataReader rdr  = null;
conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

// 1.  create a command object identifying
//     the stored procedure
SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

// 2. set the command object so it knows
//    to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which
//    will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

// execute the command
rdr = cmd.ExecuteReader();

// iterate through results, printing each to console
while (rdr.Read())
{
    Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
}

Magento Product Attribute Get Value

A way that I know of:

$product->getResource()->getAttribute($attribute_code)
        ->getFrontend()->getValue($product)

How can I specify system properties in Tomcat configuration on startup?

(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).

You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:

http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.

Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:

<env-entry>
    <env-entry-name>SMTP_PASSWORD</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>abc123ftw</env-entry-value>
</env-entry>

Can't connect to MySQL server error 111

It probably means that your MySQL server is only listening the localhost interface.

If you have lines like this :

bind-address = 127.0.0.1

In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

sudo service mysql restart

Of course, to do this, you must be the administrator of the server.

How to vertically center content with variable height within a div?

Using the child selector, I've taken Fadi's incredible answer above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the contentCentered class name to elements I want to center:

_x000D_
_x000D_
.contentCentered {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.contentCentered::before {_x000D_
  content: '';_x000D_
  display: inline-block;_x000D_
  height: 100%; _x000D_
  vertical-align: middle;_x000D_
  margin-right: -.25em; /* Adjusts for spacing */_x000D_
}_x000D_
_x000D_
.contentCentered > * {_x000D_
  display: inline-block;_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<div class="contentCentered">_x000D_
  <div>_x000D_
    <h1>Some text</h1>_x000D_
    <p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
      shoulder, said&mdash;"Did ye see anything looking like men going_x000D_
      towards that ship a while ago?"</p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Forked CodePen: http://codepen.io/dougli/pen/Eeysg

How to use Git Revert

Use git revert like so:

git revert <insert bad commit hash here>

git revert creates a new commit with the changes that are rolled back. git reset erases your git history instead of making a new commit.

The steps after are the same as any other commit.

Animate the transition between fragments

For anyone else who gets caught, ensure setCustomAnimations is called before the call to replace/add when building the transaction.

How to extract elements from a list using indices in Python?

Use Numpy direct array indexing, as in MATLAB, Julia, ...

a = [10, 11, 12, 13, 14, 15];
s = [1, 2, 5] ;

import numpy as np
list(np.array(a)[s])
# [11, 12, 15]

Better yet, just stay with Numpy arrays

a = np.array([10, 11, 12, 13, 14, 15])
a[s]
#array([11, 12, 15])

How to convert a string Date to long millseconds

using simpledateformat you can easily achieve it.

1) First convert string to java.Date using simpledateformatter.

2) Use getTime method to obtain count of millisecs from date

 public class test {
      public static void main(String[] args) {
      String currentDate = "01-March-2016";
      SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
     Date parseDate = f.parse(currentDate);
     long milliseconds = parseDate.getTime();
  }
        }

more Example click here

Delete all the queues from RabbitMQ?

In case you only want to purge the queues which are not empty (a lot faster):

rabbitmqctl list_queues | awk '$2!=0 { print $1 }' | sed 's/Listing//' | xargs -L1 rabbitmqctl purge_queue

For me, it takes 2-3 seconds to purge a queue (both empty and non-empty ones), so iterating through 50 queues is such a pain while I just need to purge 10 of them (40/50 are empty).

Styling JQuery UI Autocomplete

You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.

.ui-corner-all
{
border-radius: 0px !important;
}

login to remote using "mstsc /admin" with password

to be secured, you should execute 3 commands :

cmdkey /generic:"server-address" /user:"username" /pass:"password"
mstsc /v:server-address
cmdkey /delete:server-address

first command to save the credential

second command to open remote desktop

and the third command to delete the credential

all of these commands can be saved in a batch file(bat).

ValueError: could not convert string to float: id

Your data may not be what you expect -- it seems you're expecting, but not getting, floats.

A simple solution to figuring out where this occurs would be to add a try/except to the for-loop:

for i in range(0,N):
    w=f[i].split()
    l1=w[1:8]
    l2=w[8:15]
    try:
      list1=[float(x) for x in l1]
      list2=[float(x) for x in l2]
    except ValueError, e:
      # report the error in some way that is helpful -- maybe print out i
    result=stats.ttest_ind(list1,list2)
    print result[1]

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

What is the difference between SAX and DOM?

Here in simpler words:

DOM

  • Tree model parser (Object based) (Tree of nodes).

  • DOM loads the file into the memory and then parse- the file.

  • Has memory constraints since it loads the whole XML file before parsing.

  • DOM is read and write (can insert or delete nodes).

  • If the XML content is small, then prefer DOM parser.

  • Backward and forward search is possible for searching the tags and evaluation of the information inside the tags. So this gives the ease of navigation.

  • Slower at run time.

SAX

  • Event based parser (Sequence of events).

  • SAX parses the file as it reads it, i.e. parses node by node.

  • No memory constraints as it does not store the XML content in the memory.

  • SAX is read only i.e. can’t insert or delete the node.

  • Use SAX parser when memory content is large.

  • SAX reads the XML file from top to bottom and backward navigation is not possible.

  • Faster at run time.

HTML input type=file, get the image before submitting the form

Here is the complete example for previewing image before it gets upload.

HTML :

<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>

JavaScript :

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#blah')
        .attr('src', e.target.result)
        .width(150)
        .height(200);
    };
    reader.readAsDataURL(input.files[0]);
  }
}

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

As mentioned this occurs when using RubyGems 1.6.0 with Ruby on Rails version earlier than version 3. My app is using Ruby on Rails 2.3.3 vendored into the /vendor of the project.

No doubt an upgrade of Ruby on Rails to a newer 2.3.X version may also fix this issue. However, this problem prevents you running Rake to unvendor Ruby on Rails and upgrade it.

Adding require 'thread' to the top of environment.rb did not fix the issue for me. Adding require 'thread' to /vendor/rails/activesupport/lib/active_support.rb did fix the problem.

Should I use alias or alias_method?

Apart from the syntax, the main difference is in the scoping:

# scoping with alias_method
class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias_method :name, :full_name
  end

end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Geeky geek'

In the above case method “name” picks the method “full_name” defined in “Developer” class. Now lets try with alias.

class User

  def full_name
    puts "Johnnie Walker"
  end

  def self.add_rename
    alias name full_name
  end
end

class Developer < User
  def full_name
    puts "Geeky geek"
  end
  add_rename
end

Developer.new.name #=> 'Johnnie Walker'

With the usage of alias the method “name” is not able to pick the method “full_name” defined in Developer.

This is because alias is a keyword and it is lexically scoped. It means it treats self as the value of self at the time the source code was read . In contrast alias_method treats self as the value determined at the run time.

Source: http://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html