Programs & Examples On #Static resource

Spring 3 MVC resources and tag <mvc:resources />

You can keep rsouces directory in Directory NetBeans: Web Pages Eclipse: webapps

File: dispatcher-servlet.xml

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="controller" />

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <mvc:resources location="/resources/theme_name/" mapping="/resources/**"  cache-period="10000"/>
    <mvc:annotation-driven/>

</beans>

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
        <url-pattern>*.css</url-pattern>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

In JSP File

<link href="<c:url value="/resources/css/default.css"/>" rel="stylesheet" type="text/css"/>

How to increase the max upload file size in ASP.NET?

This setting goes in your web.config file. It affects the entire application, though... I don't think you can set it per page.

<configuration>
  <system.web>
    <httpRuntime maxRequestLength="xxx" />
  </system.web>
</configuration>

"xxx" is in KB. The default is 4096 (= 4 MB).

Getting HTML elements by their attribute names

Just another answer

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    function(el) {return el.getAttribute('property') == 'v.name';}
);

In future

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    (el) => el.getAttribute('property') == 'v.name'
)

3rd party edit

Intro

  • The call() method calls a function with a given this value and arguments provided individually.

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Given this html markup

<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>

you can use this javascript

function findSpan(){

    var spans = document.getElementsByTagName('span');
    var spansV = Array.prototype.filter.call(
         spans,
         function(el) {return el.getAttribute('property') == 'v:name';}
    );
    return spansV;
}

See demo

How to run Gulp tasks sequentially one after the other

It's not an official release yet, but the coming up Gulp 4.0 lets you easily do synchronous tasks with gulp.series. You can simply do it like this:

gulp.task('develop', gulp.series('clean', 'coffee'))

I found a good blog post introducing how to upgrade and make a use of those neat features: migrating to gulp 4 by example

How to use Class<T> in Java?

From the Java Documentation:

[...] More surprisingly, class Class has been generified. Class literals now function as type tokens, providing both run-time and compile-time type information. This enables a style of static factories exemplified by the getAnnotation method in the new AnnotatedElement interface:

<T extends Annotation> T getAnnotation(Class<T> annotationType); 

This is a generic method. It infers the value of its type parameter T from its argument, and returns an appropriate instance of T, as illustrated by the following snippet:

Author a = Othello.class.getAnnotation(Author.class);

Prior to generics, you would have had to cast the result to Author. Also you would have had no way to make the compiler check that the actual parameter represented a subclass of Annotation. [...]

Well, I never had to use this kind of stuff. Anyone?

Creating a class object in c++

1)What is the difference between both the way of creating class objects.

First one is a pointer to a constructed object in heap (by new). Second one is an object that implicitly constructed. (Default constructor)

2)If i am creating object like Example example; how to use that in an singleton class.

It depends on your goals, easiest is put it as a member in class simply.

A sample of a singleton class which has an object from Example class:

class Sample
{

    Example example;

public:

    static inline Sample *getInstance()
    {
        if (!uniqeInstance)
        {
            uniqeInstance = new Sample;
        }
        return uniqeInstance;
    }
private:
    Sample();
    virtual ~Sample();
    Sample(const Sample&);
    Sample &operator=(const Sample &);
    static Sample *uniqeInstance;
};

How do I run a single test using Jest?

Full command to run a single Jest test

Command:

node <path-to-jest> -i <you-test-file> -c <jest-config> -t "<test-block-name>"

  • <path-to-jest>:
    • Windows: node_modules\jest\bin\jest.js
    • Others: node_modules/.bin/jest
  • -i <you-test-file>: path to the file with tests (js or ts)
  • -c <jest-config>: path to a separate Jest config file (JSON), if you keep your Jest configuration in package.json, you don't have to specify this parameter (Jest will find it without your help)
  • -t <the-name-of-test-block>: actually it's a name (the first parameter) of describe(...), it(...), or test(...) block.

Example:

describe("math tests", () => {

  it("1 + 1 = 2", () => {
    expect(1 + 1).toBe(2);
  });

  it("-1 * -1 !== -1", () => {
    expect(-1 * -1).not.toBe(-1);
  });

});

So, the command

node node_modules/jest/bin/jest.js -i test/math-tests.js -c test/tests-config.json -t "1 + 1 = 2"

will test it("1 + 1 = 2", ...), but if you change the -t parameter to "math tests" then it will run both tests from the describe("math tests",...) block.

Remarks:

  1. For Windows, replace node_modules/.bin/jest with node_modules\jest\bin\jest.js.
  2. This approach allows you to debug the running script. To enable debugging add '--inspect-brk' parameter to the command.

Running a single Jest test via NPM scripts in 'package.json'

Having Jest installed, you can simplify the syntax of this command (above) by using NPM scripts. In "package.json" add a new script to the "scripts" section:

"scripts": {
  "test:math": "jest -i test/my-tests.js -t \"math tests\"",
}

In this case, we use an alias 'jest' instead of writing the full path to it. Also, we don't specify the configuration file path since we can place it in "package.json" as well and Jest will look into it by default. Now you can run the command:

npm run test:math

And the "math tests" block with two tests will be executed. Or, of course, you can specify one particular test by its name.

Another option would be to pull the <the-name-of-test-block> parameter outside the "test:math" script and pass it from the NPM command:

package.json:

"scripts": {
  "test:math": "jest -i test/my-tests.js -t",
}

Command:

npm run test:math "math tests"

Now you can manage the name of the run test(s) with a much shorter command.

Remarks:

  1. The 'jest' command will work with NPM scripts because

npm makes "./node_modules/.bin" the first entry in the PATH environment variable when running any lifecycle scripts, so this will work fine, even if your program is not globally installed (NPM blog) 2. This approach doesn't seem to allow debugging because Jest is run via its binary/CLI, not via node.


Running a selected Jest test in Visual Studio Code

If you are using Visual Studio Code you can take advantage of it and run the currently selected test (in the code editor) by pressing the F5 button. To do this, we will need to create a new launch configuration block in the ".vscode/launch.json" file. In that configuration, we will use predefined variables which are substituted with the appropriate (unfortunately not always) values when running. Of all available we are only interested in these:

  • ${relativeFile} - the current opened file relative to ${workspaceFolder}
  • ${selectedText} - the current selected text in the active file

But before writing out the launch configuration we should add the 'test' script in our 'package.json' (if we haven't done it yet).

File package.json:

"scripts": {
  "test": "jest"
}

Then we can use it in our launch configuration.

Launch configuration:

{
  "type": "node",
  "request": "launch",
  "name": "Run selected Jest test",
  "runtimeExecutable": "npm",
  "runtimeArgs": [
    "run-script",
    "test"
  ],
  "args": [
    "--",
    "-i",
    "${relativeFile}",
    "-t",
    "${selectedText}"
  ],
  "console": "integratedTerminal",
}

It actually does the same as the commands described earlier in this answer. Now that everything is ready, we can run any test we want without having to rewrite the command parameters manually.

Here's all you need to do:

  1. Select currently created launch config in the debug panel:

    Select launch config in the Visual Studio Code debug panel

  2. Open the file with tests in the code editor and select the name of the test you want to test (without quotation marks):

    Select test name

  3. Press F5 button.

And voilà!

Now to run any test you want. Just open it in the editor, select its name, and press F5.

Unfortunately, it won't be "voilà" on a Windows machines because they substitute (who knows why) the ${relativeFile} variable with the path having reversed slashes and Jest wouldn't understand such a path.

Remarks:

  1. To run under the debugger, don't forget to add the '--inspect-brk' parameter.
  2. In this configuration example, we don't have the Jest configuration parameter assuming that it's included in 'package.json'.

Set margins in a LinearLayout programmatically

Try this:

MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;

How can I set the form action through JavaScript?

Plain JavaScript:

document.getElementById('form_id').action; //Will retrieve it

document.getElementById('form_id').action = "script.php"; //Will set it

Using jQuery...

$("#form_id").attr("action"); //Will retrieve it

$("#form_id").attr("action", "/script.php"); //Will set it

What does "The APR based Apache Tomcat Native library was not found" mean?

If you don't have Tomcat Native library install it with:

sudo apt-get install libtcnative-1

and if it's still there an old version upgrade it with:

sudo apt-get upgrade libtcnative-1

How to append rows to an R data frame

Let's benchmark the three solutions proposed:

# use rbind
f1 <- function(n){
  df <- data.frame(x = numeric(), y = character())
  for(i in 1:n){
    df <- rbind(df, data.frame(x = i, y = toString(i)))
  }
  df
}
# use list
f2 <- function(n){
  df <- data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)
  for(i in 1:n){
    df[i,] <- list(i, toString(i))
  }
  df
}
# pre-allocate space
f3 <- function(n){
  df <- data.frame(x = numeric(1000), y = character(1000), stringsAsFactors = FALSE)
  for(i in 1:n){
    df$x[i] <- i
    df$y[i] <- toString(i)
  }
  df
}
system.time(f1(1000))
#   user  system elapsed 
#   1.33    0.00    1.32 
system.time(f2(1000))
#   user  system elapsed 
#   0.19    0.00    0.19 
system.time(f3(1000))
#   user  system elapsed 
#   0.14    0.00    0.14

The best solution is to pre-allocate space (as intended in R). The next-best solution is to use list, and the worst solution (at least based on these timing results) appears to be rbind.

Selected tab's color in Bottom Navigation View

1. Inside res create folder with name color (like drawable)

2. Right click on color folder. Select new-> color resource file-> create color.xml file (bnv_tab_item_foreground) (Figure 1: File Structure)

3. Copy and paste bnv_tab_item_foreground

<android.support.design.widget.BottomNavigationView
            android:id="@+id/navigation"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="0dp"
            android:layout_marginStart="0dp"
            app:itemBackground="@color/appcolor"//diffrent color
            app:itemIconTint="@color/bnv_tab_item_foreground" //inside folder 2 diff colors
            app:itemTextColor="@color/bnv_tab_item_foreground"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation" />

bnv_tab_item_foreground:

 <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_checked="true" android:color="@color/white" />
        <item android:color="@android:color/darker_gray"  />
    </selector>

Figure 1: File Structure:

Figure 1: File Structure

How to Find Item in Dictionary Collection?

Of course, if you want to make sure it's in there otherwise fail then this works:

thisTag = _tags[key];

NOTE: This will fail if the key,value pair does not exists but sometimes that is exactly what you want. This way you can catch it and do something about the error. I would only do this if I am certain that the key,value pair is or should be in the dictionary and if not I want it to know about it via the throw.

Import .bak file to a database in SQL server

You can use node package, if you often need to restore databases in development process.

Install:

npm install -g sql-bak-restore

Usage:

sql-bak-restore <bakPath> <dbName> <oldDbName> <owner>

Arguments:

  • bakpath, relative or absolute path to file
  • dbName, to which database to restore (!! database with this name will be deleted if exists !!)
  • oldDbName, database name (if you don't know, specify something and run, you will see available databases after run.)
  • owner, userName to make and give him db_owner privileges (password "1")

!! sqlcmd command line utility should be in your PATH variable.

https://github.com/vladimirbuskin/sql-bak-restore/

What's the CMake syntax to set and use variables?

Here are a couple basic examples to get started quick and dirty.

One item variable

Set variable:

SET(INSTALL_ETC_DIR "etc")

Use variable:

SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")

Multi-item variable (ie. list)

Set variable:

SET(PROGRAM_SRCS
        program.c
        program_utils.c
        a_lib.c
        b_lib.c
        config.c
        )

Use variable:

add_executable(program "${PROGRAM_SRCS}")

CMake docs on variables

how to set JAVA_OPTS for Tomcat in Windows?

Try

set JAVA_OPTS=%JAVA_OPTS% -Xms512M -Xmx1024M

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

The time complexity of ArrayList.clear() is O(n) and of removeAll is O(n^2).

So yes, ArrayList.clear is much faster.

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

How to parse a text file with C#

Like it's already mentioned, I would highly recommend using regular expression (in System.Text) to get this kind of job done.

In combo with a solid tool like RegexBuddy, you are looking at handling any complex text record parsing situations, as well as getting results quickly. The tool makes it real easy.

Hope that helps.

How to open the terminal in Atom?

There are a number of Atom packages which give you access to the terminal from within Atom. Try a few out to find the best option for you.

Some recommendations which work in Ubuntu (with their primary keyboard shortcuts):

Open a terminal in Atom:

Edit: recommended plugin changed as terminal-plus is no longer maintained. Thanks for the head's-up, @MorganRodgers.

If you want to open a terminal panel in Atom, try atom-ide-terminal. Use the keyboard shortcut ctrl-` to open a new terminal instance.

Open an external terminal from Atom:

If you just want a shortcut to open your external terminal from within Atom, try atom-terminal (this is what I use). You can use ctrl-shift-t to open your external terminal in the current file's directory, or alt-shift-t to open the terminal in the project's root directory.

converting drawable resource image into bitmap

In res/drawable folder,

1. Create a new Drawable Resources.

2. Input file name.

A new file will be created inside the res/drawable folder.

Replace this code inside the newly created file and replace ic_action_back with your drawable file name.

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_action_back"
    android:tint="@color/color_primary_text" />

Now, you can use it with Resource ID, R.id.filename.

How to map calculated properties with JPA and Hibernate

Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.

Here is an example mapping

@EntityView(Order.class)
interface OrderSummary {
  Integer getId();
  @Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
  BigDecimal getOrderAmount();
  @Mapping("COUNT(orderPositions)")
  Long getItemCount();
}

Fetching this will generate a JPQL/HQL query similar to this

SELECT
  o.id,
  SUM(p.price * p.amount * p.tax),
  COUNT(p.id)
FROM
  Order o
LEFT JOIN
  o.orderPositions p
GROUP BY
  o.id

Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.

Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"

In your spring config,class

@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

What's the -practical- difference between a Bare and non-Bare repository?

A non-bare repository simply has a checked-out working tree. The working tree does not store any information about the state of the repository (branches, tags, etc.); rather, the working tree is just a representation of the actual files in the repo, which allows you to work on (edit, etc.) the files.

How to Remove Line Break in String

I had the exact same issue. I made a separate function I can call easily when needed:

Function removeLineBreakIfAtEnd(s As String) As String
    If Right(s, 1) = vbLf Then s = Left(s, Len(s) - 2)
    removeLineBreakIfAtEnd = s
End Function

I found that I needed to check the last character only and do -2 to remove the line break. I also found that checking for vbLf was the ONLY way to detect the line break. The function can be called like this:

Sub MainSub()
    Dim myString As String
    myString = "Hello" & vbCrLf
    myString = removeLineBreakIfAtEnd(myString)
    MsgBox ("Here is the resulting string: '" & myString & "'")
End Sub

In .NET, which loop runs faster, 'for' or 'foreach'?

First, a counter-claim to Dmitry's (now deleted) answer. For arrays, the C# compiler emits largely the same code for foreach as it would for an equivalent for loop. That explains why for this benchmark, the results are basically the same:

using System;
using System.Diagnostics;
using System.Linq;

class Test
{
    const int Size = 1000000;
    const int Iterations = 10000;

    static void Main()
    {
        double[] data = new double[Size];
        Random rng = new Random();
        for (int i=0; i < data.Length; i++)
        {
            data[i] = rng.NextDouble();
        }

        double correctSum = data.Sum();

        Stopwatch sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            for (int j=0; j < data.Length; j++)
            {
                sum += data[j];
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("For loop: {0}", sw.ElapsedMilliseconds);

        sw = Stopwatch.StartNew();
        for (int i=0; i < Iterations; i++)
        {
            double sum = 0;
            foreach (double d in data)
            {
                sum += d;
            }
            if (Math.Abs(sum-correctSum) > 0.1)
            {
                Console.WriteLine("Summation failed");
                return;
            }
        }
        sw.Stop();
        Console.WriteLine("Foreach loop: {0}", sw.ElapsedMilliseconds);
    }
}

Results:

For loop: 16638
Foreach loop: 16529

Next, validation that Greg's point about the collection type being important - change the array to a List<double> in the above, and you get radically different results. Not only is it significantly slower in general, but foreach becomes significantly slower than accessing by index. Having said that, I would still almost always prefer foreach to a for loop where it makes the code simpler - because readability is almost always important, whereas micro-optimisation rarely is.

jQuery UI Sortable, then write order into a database

The jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.

$('#element').sortable({
    axis: 'y',
    update: function (event, ui) {
        var data = $(this).sortable('serialize');

        // POST to server using $.post or $.ajax
        $.ajax({
            data: data,
            type: 'POST',
            url: '/your/url/here'
        });
    }
});

What this does is that it creates an array of the elements using the elements id. So, I usually do something like this:

<ul id="sortable">
   <li id="item-1"></li>
   <li id="item-2"></li>
   ...
</ul>

When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc. So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.

For example, in PHP:

$i = 0;

foreach ($_POST['item'] as $value) {
    // Execute statement:
    // UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
    $i++;
}

Example on jsFiddle.

'dependencies.dependency.version' is missing error, but version is managed in parent

If anyone finds their way here with the same problem I was having, my problem was that I was missing the <dependencyManagement> tags around dependencies I had copied from the child pom.

Using python's eval() vs. ast.literal_eval()?

Python's eager in its evaluation, so eval(input(...)) (Python 3) will evaluate the user's input as soon as it hits the eval, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval user input.

Use ast.literal_eval.


As an example, entering this at the prompt could be very bad for you:

__import__('os').system('rm -rf /a-path-you-really-care-about')

Python webbrowser.open() to open Chrome browser

In Selenium to get the URL of the active tab try,

from selenium import webdriver

driver = webdriver.Firefox()
print driver.current_url # This will print the URL of the Active link

Sending a signal to change the tab

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

and again use

print driver.current_url

I am here just providing a pseudo code for you.

You can put this in a loop and create your own flow.

I new to Stackoverflow so still learning how to write proper answers.

How do I empty an array in JavaScript?

There is a lot of confusion and misinformation regarding the while;pop/shift performance both in answers and comments. The while/pop solution has (as expected) the worst performance. What's actually happening is that setup runs only once for each sample that runs the snippet in a loop. eg:

var arr = [];

for (var i = 0; i < 100; i++) { 
    arr.push(Math.random()); 
}

for (var j = 0; j < 1000; j++) {
    while (arr.length > 0) {
        arr.pop(); // this executes 100 times, not 100000
    }
}

I have created a new test that works correctly :

http://jsperf.com/empty-javascript-array-redux

Warning: even in this version of the test you can't actually see the real difference because cloning the array takes up most of the test time. It still shows that splice is the fastest way to clear the array (not taking [] into consideration because while it is the fastest it's not actually clearing the existing array).

SVG fill color transparency / alpha?

As a not yet fully standardized solution (though in alignment with the color syntax in CSS3) you can use e.g fill="rgba(124,240,10,0.5)". Works fine in Firefox, Opera, Chrome.

Here's an example.

How to pass values between Fragments

From Developers website:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

You can communicate among fragments with the help of its Activity. You can communicate among activity and fragment using this approach.

Please check this link also.

Basic calculator in Java

maybe its better using the case instead of if dunno if this eliminates the error, but its cleaner i think.. switch (operation){case +: System.out.println("your answer is" + (num1 + num2));break;case -: System.out.println("your answer is" - (num1 - num2));break; ...

Count the occurrences of DISTINCT values

I have resolved the same problem using the below code:

String query = "SELECT violationDate, COUNT(*) as date " +
            "FROM challan " +
            "WHERE challanType = '" + type + "' GROUP BY violationDate";
    

Here violationDate and date are two columns of the result table. date column will return occurrence.

cr.getInt(1)

iPhone UIView Animation Best Practice

Anyway the "Block" method is preffered now-a-days. I will explain the simple block below.

Consider the snipped below. bug2 and bug 3 are imageViews. The below animation describes an animation with 1 second duration after a delay of 1 second. The bug3 is moved from its center to bug2's center. Once the animation is completed it will be logged "Center Animation Done!".

-(void)centerAnimation:(id)sender
{
NSLog(@"Center animation triggered!");
CGPoint bug2Center = bug2.center;

[UIView animateWithDuration:1
                      delay:1.0
                    options: UIViewAnimationCurveEaseOut
                 animations:^{
                     bug3.center = bug2Center;
                 } 
                 completion:^(BOOL finished){
                     NSLog(@"Center Animation Done!");
                 }];
}

Hope that's clean!!!

Differences between strong and weak in Objective-C

To understand Strong and Weak reference consider below example, suppose we have method named as displayLocalVariable.

 -(void)displayLocalVariable
  {
     UIView* myView = [[UIView alloc] init];
     NSLog(@"myView tag is = %ld", myView.tag);
  }

In above method scope of myView variable is limited to displayLocalVariable method, once the method gets finished myView variable which is holding the UIView object will get deallocated from the memory.

Now what if we want to hold the myView variable throughout our view controller's life cycle. For this we can create the property named as usernameView which will have Strong reference to the variable myView(see @property(nonatomic,strong) UIView* usernameView; and self.usernameView = myView; in below code), as below,

@interface LoginViewController ()

@property(nonatomic,strong) UIView* usernameView;
@property(nonatomic,weak) UIView* dummyNameView;

- (void)displayLocalVariable;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

}

-(void)viewWillAppear:(BOOL)animated
{
     [self displayLocalVariable];
}

- (void)displayLocalVariable
{
   UIView* myView = [[UIView alloc] init];
   NSLog(@"myView tag is = %ld", myView.tag);
   self.usernameView = myView;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}


@end

Now in above code you can see myView has been assigned to self.usernameView and self.usernameView is having a strong reference(as we declared in interface using @property) to myView. Hence myView will not get deallocated from memory till self.usernameView is alive.

  • Weak reference

Now consider assigning myName to dummyNameView which is a Weak reference, self.dummyNameView = myView; Unlike Strong reference Weak will hold the myView only till there is Strong reference to myView. See below code to understand Weak reference,

-(void)displayLocalVariable
  {
     UIView* myView = [[UIView alloc] init];
     NSLog(@"myView tag is = %ld", myView.tag);
     self.dummyNameView = myView;
  }

In above code there is Weak reference to myView(i.e. self.dummyNameView is having Weak reference to myView) but there is no Strong reference to myView, hence self.dummyNameView will not be able to hold the myView value.

Now again consider the below code,

-(void)displayLocalVariable
      {
         UIView* myView = [[UIView alloc] init];
         NSLog(@"myView tag is = %ld", myView.tag);
         self.usernameView = myView;
         self.dummyNameView = myView;
      } 

In above code self.usernameView has a Strong reference to myView, hence self.dummyNameView will now have a value of myView even after method ends since myView has a Strong reference associated with it.

Now whenever we make a Strong reference to a variable it's retain count get increased by one and the variable will not get deallocated till it's retain count reaches to 0.

Hope this helps.

jQuery - Call ajax every 10 seconds

Are you going to want to do a setInterval()?

setInterval(function(){get_fb();}, 10000);

Or:

setInterval(get_fb, 10000);

Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).success(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Or use .ajax().complete() if you want it to run regardless of result:

function get_fb(){
    var feedback = $.ajax({
        type: "POST",
        url: "feedback.php",
        async: false
    }).complete(function(){
        setTimeout(function(){get_fb();}, 10000);
    }).responseText;

    $('div.feedback-box').html(feedback);
}

Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.

http://jsfiddle.net/YXMPn/

Python strftime - date without leading 0?

quite late to the party but %-d works on my end.

datetime.now().strftime('%B %-d, %Y') produces something like "November 5, 2014"

cheers :)

how to redirect to home page

maybe

var re = /^https?:\/\/[^/]+/i;
window.location.href = re.exec(window.location.href)[0];

is what you're looking for?

Use a LIKE statement on SQL Server XML Datatype

You should be able to do this quite easily:

SELECT * 
FROM WebPageContent 
WHERE data.value('(/PageContent/Text)[1]', 'varchar(100)') LIKE 'XYZ%'

The .value method gives you the actual value, and you can define that to be returned as a VARCHAR(), which you can then check with a LIKE statement.

Mind you, this isn't going to be awfully fast. So if you have certain fields in your XML that you need to inspect a lot, you could:

  • create a stored function which gets the XML and returns the value you're looking for as a VARCHAR()
  • define a new computed field on your table which calls this function, and make it a PERSISTED column

With this, you'd basically "extract" a certain portion of the XML into a computed field, make it persisted, and then you can search very efficiently on it (heck: you can even INDEX that field!).

Marc

Using Enum values as String literals

This method should work with any enum:

public enum MyEnum {
    VALUE1,
    VALUE2,
    VALUE3;

    public int getValue() {
        return this.ordinal();
    }

    public static DataType forValue(int value) {
        return values()[value];
    }

    public String toString() {
        return forValue(getValue()).name();
    }
}

How to force IE10 to render page in IE9 document mode

You should be able to do it using the X-UA meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

However, if you find yourself having to do this, you're probably doing something wrong and should take a look at what you're doing and see if you can do it a different/better way.

Does PHP have threading?

Here is an example of what Wilco suggested:

$cmd = 'nohup nice -n 10 /usr/bin/php -c /path/to/php.ini -f /path/to/php/file.php action=generate var1_id=23 var2_id=35 gen_id=535 > /path/to/log/file.log & echo $!';
$pid = shell_exec($cmd);

Basically this executes the PHP script at the command line, but immediately returns the PID and then runs in the background. (The echo $! ensures nothing else is returned other than the PID.) This allows your PHP script to continue or quit if you want. When I have used this, I have redirected the user to another page, where every 5 to 60 seconds an AJAX call is made to check if the report is still running. (I have a table to store the gen_id and the user it's related to.) The check script runs the following:

exec('ps ' . $pid , $processState);
if (count($processState) < 2) {
     // less than 2 rows in the ps, therefore report is complete
}

There is a short post on this technique here: http://nsaunders.wordpress.com/2007/01/12/running-a-background-process-in-php/

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

echo stat | nc localhost 2181 | grep Mode
echo srvr | nc localhost 2181 | grep Mode #(From 3.3.0 onwards)

Above will work in whichever modes Zookeeper is running (standalone or embedded).

Another way

If zookeeper is running in standalone mode, its a JVM process. so -

jps | grep Quorum

will display list of jvm processes; something like this for zookeeper with process ID

HQuorumPeer

Add timer to a Windows Forms application

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

How to give a time delay of less than one second in excel vba?

To pause for 0.8 of a second:

Sub main()
    startTime = Timer
    Do
    Loop Until Timer - startTime >= 0.8
End Sub

Is Eclipse the best IDE for Java?

I gave Eclipse a 3 months ride at my new work, but after that I found out that normal Maven project can be run in IntelliJ IDEA too (unless it's Eclipse plugin/EMF/something of course ;-)). 3 months are not enough to compare it with 8+ years with IDEA, but it's enough to claim I gave it a fair try. I decided to live with its perspectives (other IDEs don't need them), with its poor debugger (doesn't show date values unless you click on them! etc.), with its comparatively worse completion than IDEA has.

Now after all those years IDEA is also free (community edition) and I use it without much trouble. Of course I miss some of those "Ultimate" features of paid version, but it's far better than Eclipse. Biggest difference is the whole mindset needed for both of these IDEs. But after you master the mindset of either I can't understand what can anyone hold to Eclipse - unless you need its plugin ecosystem or you have some serious investments there.

Example of "mindset" differences: You have to save in Eclipse, not in IDEA, and I don't care what is better or worse - but you have to save in Eclipse to let him clean up underlined errors that are not errors anymore, etc. ;-) You have to save there in order to get rid of errors in other files too, because other file doesn't see the changes otherwise.

I blogged much more about this topic - and yes, I'm biased, though I tried to be as little as possible. But after some time it wasn't simply possible: :-)

And no, not even IDEA is perfect, I know it. Because I use it a lot. But it is the best Java IDE if you ask me. Even the Community edition.

How to remove entry from $PATH on mac

If you're removing the path for Python 3 specifically, I found it in ~/.zprofile and ~/.zshrc.

Lowercase and Uppercase with jQuery

If it's just for display purposes, you can render the text as upper or lower case in pure CSS, without any Javascript using the text-transform property:

.myclass {
    text-transform: lowercase;
}

See https://developer.mozilla.org/en/CSS/text-transform for more info.

However, note that this doesn't actually change the value to lower case; it just displays it that way. This means that if you examine the contents of the element (ie using Javascript), it will still be in its original format.

How to trigger Jenkins builds remotely and to pass parameters

To pass/use the variables, first create parameters in the configure section of Jenkins. Parameters that you use can be of type text, String, file, etc.

After creating them, use the variable reference in the fields you want to.

For example: I have configured/created two variables for Email-subject and Email-recipentList, and I have used their reference in the EMail-ext plugin (attached screenshot).

Enter image description here

String formatting in Python 3

I like this approach

my_hash = {}
my_hash["goals"] = 3 #to show number
my_hash["penalties"] = "5" #to show string
print("I scored %(goals)d goals and took %(penalties)s penalties" % my_hash)

Note the appended d and s to the brackets respectively.

output will be:

I scored 3 goals and took 5 penalties

Change the current directory from a Bash script

I've made a script to change directory. take a look: https://github.com/ygpark/dj

javascript cell number validation

Mobile number Validation using Java Script, This link will provide demo and more information.

_x000D_
_x000D_
function isNumber(evt) {_x000D_
  evt = (evt) ? evt : window.event;_x000D_
  var charCode = (evt.which) ? evt.which : evt.keyCode;_x000D_
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {_x000D_
    alert("Please enter only Numbers.");_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  return true;_x000D_
}_x000D_
_x000D_
function ValidateNo() {_x000D_
  var phoneNo = document.getElementById('txtPhoneNo');_x000D_
_x000D_
  if (phoneNo.value == "" || phoneNo.value == null) {_x000D_
    alert("Please enter your Mobile No.");_x000D_
    return false;_x000D_
  }_x000D_
  if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {_x000D_
    alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  alert("Success ");_x000D_
  return true;_x000D_
}
_x000D_
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />_x000D_
<input type="button" value="Submit" onclick="ValidateNo();">
_x000D_
_x000D_
_x000D_

Case insensitive searching in Oracle

select user_name
from my_table
where nlssort(user_name, 'NLS_SORT = Latin_CI') = nlssort('%AbC%', 'NLS_SORT = Latin_CI')

How do I get the RootViewController from a pushed controller?

Swift version :

var rootViewController = self.navigationController?.viewControllers.first

ObjectiveC version :

UIViewController *rootViewController = [self.navigationController.viewControllers firstObject];

Where self is an instance of a UIViewController embedded in a UINavigationController.

Server Discovery And Monitoring engine is deprecated

This will work:

// Connect to Mongo
mongoose.set("useNewUrlParser", true);
mongoose.set("useUnifiedTopology", true);

mongoose
  .connect(db) // Connection String here
  .then(() => console.log("MongoDB Connected..."))
  .catch(() => console.log(err));

Recommended Fonts for Programming?

I like ProFont TT >tweaked< It's clean and there is a clear difference between 1, l and I and 0 and O.It works best at 9pt. It doesn't scale up very well.

ProFont Windows 9pt

A good Sorted List for Java

Phuong:

Sorting 40,000 random numbers:

0.022 seconds

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;


public class test
{
    public static void main(String[] args)
    {
        List<Integer> nums = new ArrayList<Integer>();
        Random rand = new Random();
        for( int i = 0; i < 40000; i++ )
        {
            nums.add( rand.nextInt(Integer.MAX_VALUE) );
        }

        long start = System.nanoTime();
        Collections.sort(nums);
        long end = System.nanoTime();

        System.out.println((end-start)/1e9);
    }
}   

Since you rarely need sorting, as per your problem statement, this is probably more efficient than it needs to be.

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

jQuery: outer html()

No siblings solution:

var x = $('#xxx').parent().html();
alert(x);

Universal solution:

// no cloning necessary    
var x = $('#xxx').wrapAll('<div>').parent().html(); 
alert(x);

Fiddle here: http://jsfiddle.net/ezmilhouse/Mv76a/

How to get the last day of the month?

If you want to make your own small function, this is a good starting point:

def eomday(year, month):
    """returns the number of days in a given month"""
    days_per_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    d = days_per_month[month - 1]
    if month == 2 and (year % 4 == 0 and year % 100 != 0 or year % 400 == 0):
        d = 29
    return d

For this you have to know the rules for the leap years:

  • every fourth year
  • with the exception of every 100 year
  • but again every 400 years

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

How do you display code snippets in MS Word preserving format and syntax highlighting?

Try defining a style called 'code' and make it use a small fixed width font, it should look better then.

Use CTRL+SPACEBAR to reset style.

Java : Comparable vs Comparator

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

Comparable allows you to specify how objects that you are implementing get compared.

Obviously, if you don't have control over a class (or you want to provide multiple ways to compare objects that you do have control over) then use Comparator.

Otherwise you can use Comparable.

Referencing value in a closed Excel workbook using INDIRECT?

If you know the number of sheet you want to reference you can use below function to find out the name. Than you can use it in INDIRECT funcion.

Public Function GETSHEETNAME(address As String, Optional SheetNumber As Integer = 1) As String

    Set WS = GetObject(address).Worksheets
    GETSHEETNAME = WS(SheetNumber).Name

End Function

This solution doesn't require referenced workbook to be open - Excel gonna open it by itself (but it's gonna be hidden).

Postgresql Select rows where column = array

SELECT  *
FROM    table
WHERE   some_id = ANY(ARRAY[1, 2])

or ANSI-compatible:

SELECT  *
FROM    table
WHERE   some_id IN (1, 2)

The ANY syntax is preferred because the array as a whole can be passed in a bound variable:

SELECT  *
FROM    table
WHERE   some_id = ANY(?::INT[])

You would need to pass a string representation of the array: {1,2}

Using Chrome, how to find to which events are bound to an element

Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)

Google Chromes developer tools has a search function built into the scripts section

If you are unfamiliar with this tool: (just in case)

  • right click anywhere on a page (in chrome)
  • click 'Inspect Element'
  • click the 'Scripts' tab
  • Search bar in the top right

Doing a quick search for the #ID should take you to the binding function eventually.

Ex: searching for #foo would take you to

$('#foo').click(function(){ alert('bar'); })

enter image description here

How to use vagrant in a proxy environment?

Auto detect your proxy settings and inject them in all your vagrant VM

install the proxy plugin

vagrant plugin install vagrant-proxyconf

add this conf to you private/user VagrantFile (it will be executed for all your projects) :

vi $HOME/.vagrant.d/Vagrantfile

Vagrant.configure("2") do |config|
  puts "proxyconf..."
  if Vagrant.has_plugin?("vagrant-proxyconf")
    puts "find proxyconf plugin !"
    if ENV["http_proxy"]
      puts "http_proxy: " + ENV["http_proxy"]
      config.proxy.http     = ENV["http_proxy"]
    end
    if ENV["https_proxy"]
      puts "https_proxy: " + ENV["https_proxy"]
      config.proxy.https    = ENV["https_proxy"]
    end
    if ENV["no_proxy"]
      config.proxy.no_proxy = ENV["no_proxy"]
    end
  end
end

now up your VM !

in a "using" block is a SqlConnection closed on return or exception?

Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.

From MSDN:

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):

s[s.str.contains('og|at')]

Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)
df[s.str.contains('og|at')] 

Output:

0 cat
1 hat
2 dog
3 fog 

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

consider changing host entry 127.0.0.1 to localhost or even the IP address of the server.

$cfg['Servers'][$i]['host']

When is a language considered a scripting language?

First point, a programming language isn't a "scripting language" or a something else. It can be a "scripting language" and something else.

Second point, the implementer of the language will tell you if it's a scripting language.

Your question should read "In what implementations would a programming language be considered a scripting language?", not "What is the difference between a scripting language and a programming language?". There is no between.

Yet, I will consider a language a scripting language if it is used to provide some type of middle ware. For example, I would consider most implementations of JavaScript a scripting language. If JavaScript were run in the OS, not the browser, then it would not be a scripting language. If PHP runs inside of Apache, it's a scripting language. If it's run from the command line, it's not.

How to check date of last change in stored procedure or function in SQL server

For SQL 2000 I would use:

SELECT name, crdate, refdate 
FROM sysobjects
WHERE type = 'P' 
ORDER BY refdate desc

Local and global temporary tables in SQL Server

I find this explanation quite clear (it's pure copy from Technet):

There are two types of temporary tables: local and global. Local temporary tables are visible only to their creators during the same connection to an instance of SQL Server as when the tables were first created or referenced. Local temporary tables are deleted after the user disconnects from the instance of SQL Server. Global temporary tables are visible to any user and any connection after they are created, and are deleted when all users that are referencing the table disconnect from the instance of SQL Server.

MySQL/Writing file error (Errcode 28)

Run the following code:

du -sh /var/log/mysql

Perhaps mysql binary logs filled the memory, If so, follow the removal of old logs and restart the server. Also add in my.cnf:

expire_logs_days = 3

How to get input text value from inside td

Maybe this will help.

var inputVal = $(this).closest('tr').find("td:eq(x) input").val();

Google Maps how to Show city or an Area outline

so I have a solution that isn't perfect but it worked for me. Use the polygon example from Google, and use the pinpoint on Google Maps to get lat & long locations.

Calgary pinpoint

I used what I call "ocular copy & paste" where you look at the screen and then write in the numbers you want ;-)

<style>
  #map {
    height: 500px;
  }
</style>
<script>

// This example creates a simple polygon representing the host city of the 
// Greatest Outdoor Show On Earth.

 function initMap() {
   var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 9,
      center: {lat: 51.039, lng: -114.204},
      mapTypeId: 'terrain'
    });

    // Define the LatLng coordinates for the polygon's path.
    var triangleCoords = [
      {lat: 51.183, lng: -114.234},
      {lat: 51.154, lng: -114.235},
      {lat: 51.156, lng: -114.261},
      {lat: 51.104, lng: -114.259},
      {lat: 51.106, lng: -114.261},
      {lat: 51.102, lng: -114.272},
      {lat: 51.081, lng: -114.271},
      {lat: 51.081, lng: -114.234},
      {lat: 51.009, lng: -114.236},
      {lat: 51.008, lng: -114.141},
      {lat: 50.995, lng: -114.142},
      {lat: 50.998, lng: -114.160},
      {lat: 50.984, lng: -114.163},
      {lat: 50.987, lng: -114.141},
      {lat: 50.979, lng: -114.141},
      {lat: 50.921, lng: -114.141},
      {lat: 50.921, lng: -114.210},
      {lat: 50.893, lng: -114.210},
      {lat: 50.892, lng: -114.140},
      {lat: 50.888, lng: -114.139},
      {lat: 50.878, lng: -114.094},
      {lat: 50.878, lng: -113.994},
      {lat: 50.840, lng: -113.954},
      {lat: 50.854, lng: -113.905},
      {lat: 50.922, lng: -113.906},
      {lat: 50.935, lng: -113.877},
      {lat: 50.943, lng: -113.877},
      {lat: 50.955, lng: -113.912},
      {lat: 51.183, lng: -113.910}
    ];

    // Construct the polygon.
    var bermudaTriangle = new google.maps.Polygon({
      paths: triangleCoords,
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    bermudaTriangle.setMap(map);
  }
</script>


<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/jskey=YOUR_API_KEY&callback=initMap">
</script>

This gets you the outline for Calgary. I've attached an image here.

Submit form using <a> tag

Try this:

Suppose HTML like this :

   <form id="myform" name="myform" method="POST" action="process_edit_questionnaire.php?project=<?php echo $project_id; ?>">
      <div id="question_block">
            testing form
        </div>
     <a href="javascript: submit();">Submit</a>
        </form>

JS :

   <script type='text/javascript'>
     function submit()
      {
         document.forms["myform"].submit();
      }
   </script>

you can check it out here : http://jsfiddle.net/Zm426/7/

React passing parameter via onclick event using ES6 syntax

Remember that in onClick={ ... }, the ... is a JavaScript expression. So

... onClick={this.handleRemove(id)}

is the same as

var val = this.handleRemove(id);
... onClick={val}

In other words, you call this.handleRemove(id) immediately, and pass that value to onClick, which isn't what you want.

Instead, you want to create a new function with one of the arguments already prefilled; essentially, you want the following:

var newFn = function() {
  var args = Array.prototype.slice.call(arguments);

  // args[0] contains the event object
  this.handleRemove.apply(this, [id].concat(args));
}
... onClick={newFn}

There is a way to express this in ES5 JavaScript: Function.prototype.bind.

... onClick={this.handleRemove.bind(this, id)}

If you use React.createClass, React automatically binds this for you on instance methods, and it may complain unless you change it to this.handleRemove.bind(null, id).

You can also simply define the function inline; this is made shorter with arrow functions if your environment or transpiler supports them:

... onClick={() => this.handleRemove(id)}

If you need access to the event, you can just pass it along:

... onClick={(evt) => this.handleRemove(id, evt)}

Java how to sort a Linked List?

In java8 you no longer need to use Collections.sort method as LinkedList inherits the method sort from java.util.List, so adapting Fido's answer to Java8:

    LinkedList<String>list = new LinkedList<String>();
    list.add("abc");
    list.add("Bcd");
    list.add("aAb");

    list.sort( new Comparator<String>(){
    @Override
        public int compare(String o1,String o2){
            return Collator.getInstance().compare(o1,o2);
        }
    });

References:

http://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html

http://docs.oracle.com/javase/7/docs/api/java/util/List.html

Clear the entire history stack and start a new activity on Android

Sometimes your android emulator might fails to connect eclipse DDMS tool and ask for adb to start manually. In that case you can start or stop the adb using the command prompt.

Laravel Controller Subfolder routing

php artisan make:controller admin/CategoryController

Here admin is sub directory under app/Http/Controllers and CategoryController is controller you want to create inside directory

Detect IF hovering over element with jQuery

The accepted answer didn't work for me on JQuery 2.x .is(":hover") returns false on every call.

I ended up with a pretty simple solution that works:

function isHovered(selector) {

    return $(selector+":hover").length > 0

}

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/rootLayout">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

Remove duplicated rows using dplyr

If you want to find the rows that are duplicated you can use find_duplicates from hablar:

library(dplyr)
library(hablar)

df <- tibble(a = c(1, 2, 2, 4),
             b = c(5, 2, 2, 8))

df %>% find_duplicates()

How to serialize Joda DateTime with Jackson JSON processor?

For those with Spring Boot you have to add the module to your context and it will be added to your configuration like this.

@Bean
public Module jodaTimeModule() {
    return new JodaModule();
}

And if you want to use the new java8 time module jsr-310.

@Bean
public Module jodaTimeModule() {
    return new JavaTimeModule();
}

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

How to transfer paid android apps from one google account to another google account

It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en

How to enable support of CPU virtualization on Macbook Pro?

CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

Faster way to zero memory than with memset?

x86 is rather broad range of devices.

For totally generic x86 target, an assembly block with "rep movsd" could blast out zeros to memory 32-bits at time. Try to make sure the bulk of this work is DWORD aligned.

For chips with mmx, an assembly loop with movq could hit 64bits at a time.

You might be able to get a C/C++ compiler to use a 64-bit write with a pointer to a long long or _m64. Target must be 8 byte aligned for the best performance.

for chips with sse, movaps is fast, but only if the address is 16 byte aligned, so use a movsb until aligned, and then complete your clear with a loop of movaps

Win32 has "ZeroMemory()", but I forget if thats a macro to memset, or an actual 'good' implementation.

List all liquibase sql types

Well, since liquibase is open source there's always the source code which you could check.

Some of the data type classes seem to have a method toDatabaseDataType() which should give you information about what type works (is used) on a specific data base.

Stop all active ajax requests in jQuery

Here's what I'm currently using to accomplish that.

$.xhrPool = [];
$.xhrPool.abortAll = function() {
  _.each(this, function(jqXHR) {
    jqXHR.abort();
  });
};
$.ajaxSetup({
  beforeSend: function(jqXHR) {
    $.xhrPool.push(jqXHR);
  }
});

Note: _.each of underscore.js is present, but obviously not necessary. I'm just lazy and I don't want to change it to $.each(). 8P

Android Crop Center of Bitmap

Here a more complete snippet that crops out the center of an [bitmap] of arbitrary dimensions and scales the result to your desired [IMAGE_SIZE]. So you will always get a [croppedBitmap] scaled square of the image center with a fixed size. ideal for thumbnailing and such.

Its a more complete combination of the other solutions.

final int IMAGE_SIZE = 255;
boolean landscape = bitmap.getWidth() > bitmap.getHeight();

float scale_factor;
if (landscape) scale_factor = (float)IMAGE_SIZE / bitmap.getHeight();
else scale_factor = (float)IMAGE_SIZE / bitmap.getWidth();
Matrix matrix = new Matrix();
matrix.postScale(scale_factor, scale_factor);

Bitmap croppedBitmap;
if (landscape){
    int start = (tempBitmap.getWidth() - tempBitmap.getHeight()) / 2;
    croppedBitmap = Bitmap.createBitmap(tempBitmap, start, 0, tempBitmap.getHeight(), tempBitmap.getHeight(), matrix, true);
} else {
    int start = (tempBitmap.getHeight() - tempBitmap.getWidth()) / 2;
    croppedBitmap = Bitmap.createBitmap(tempBitmap, 0, start, tempBitmap.getWidth(), tempBitmap.getWidth(), matrix, true);
}

C# windows application Event: CLR20r3 on application start

Have been fighting this all morning and now have it solved and why it happened. Posting with the hope it helps others

I installed the Krypton.Toolkit which added the tools to the Visual studio toolbox automatically. I then added the tools to the designer, which automatically added the dll to the projrect references, however the toolkit was marked as CopyLocal=false

I built an installer, using all dlls in the release build folder (of course the above dll wasn't there).

Setting copylocal=true, then rebuilding the installer, everything worked fine.

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

How to draw an overlay on a SurfaceView used by Camera on Android?

SurfaceView probably does not work like a regular View in this regard.

Instead, do the following:

  1. Put your SurfaceView inside of a FrameLayout or RelativeLayout in your layout XML file, since both of those allow stacking of widgets on the Z-axis
  2. Move your drawing logic into a separate custom View class
  3. Add an instance of the custom View class to the layout XML file as a child of the FrameLayout or RelativeLayout, but have it appear after the SurfaceView

This will cause your custom View class to appear to float above the SurfaceView.

See here for a sample project that layers popup panels above a SurfaceView used for video playback.

How to decode encrypted wordpress admin password?

You can't easily decrypt the password from the hash string that you see. You should rather replace the hash string with a new one from a password that you do know.

There's a good howto here:

https://jakebillo.com/wordpress-phpass-generator-resetting-or-creating-a-new-admin-user/

Basically:

  1. generate a new hash from a known password using e.g. http://scriptserver.mainframe8.com/wordpress_password_hasher.php, as described in the above link, or any other product that uses the phpass library,
  2. use your DB interface (e.g. phpMyAdmin) to update the user_pass field with the new hash string.

If you have more users in this WordPress installation, you can also copy the hash string from one user whose password you know, to the other user (admin).

javascript: get a function's variable's value within another function

Your nameContent variable is inside the function scope and not visible outside that function so if you want to use the nameContent outside of the function then declare it global inside the <script> tag and use inside functions without the var keyword as follows

<script language="javascript" type="text/javascript">
    var nameContent; // In the global scope
    function first(){
        nameContent=document.getElementById('full_name').value;
    }

    function second() {
        first();
        y=nameContent; 
        alert(y);
    }
    second();
</script>

JavaScript push to array

object["property"] = value;

or

object.property = value;

Object and Array in JavaScript are different in terms of usage. Its best if you understand them:

Object vs Array: JavaScript

How to use Visual Studio Code as Default Editor for Git

Just want to add these back slashes to previous answers, I am on Windows 10 CMD, and it doesn't work without back slashes before the spaces.

git config --global core.editor "C:\\Users\\your_user_name\\AppData\\Local\\Programs\\Microsoft\ VS\ Code\\Code.exe"

Error: allowDefinition='MachineToApplication' beyond application level

If you have MVC project with enabled views build, one of the solution is to delete obj folder before build. Add to project file:

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

Here is article: How to remove bin and/or obj folder before the build or deploy

Loop through all the rows of a temp table and call a stored procedure for each row

You always don't need a cursor for this. You can do it with a while loop. You should avoid cursors whenever possible. While loop is faster than cursors.

How do I center an anchor element in CSS?

<span style="text-align:center; display:block;">
<a href="http://news.awaissoft.com">Awaissoft</a>
</span>

How to hide a status bar in iOS?

add this key key from dropdownlist in "info.plist" and voila you will no more see top bar that includes elements something like GSM,wifi icon etc.
enter image description here

Entity Framework Core: A second operation started on this context before a previous operation completed

I have a background service that performs an action for each entry in a table. The problem is, that if I iterate over and modify some data all on the same instance of the DbContext this error occurs.

One solution, as mentioned in this thread is to change the DbContext's lifetime to transient by defining it like

services.AddDbContext<DbContext>(ServiceLifetime.Transient);

but because I do changes in multiple different services and commit them at once using the SaveChanges() method this solution doesnt work in my case.

Because my code runs in a service, I was doing something like

using (var scope = Services.CreateScope())
{
   var entities = scope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = scope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)
   {
       writeService.DoSomething(entity);
   } 
}

to be able to use the service like if it was a simple request. So to solve the issue i just split the single scope into two, one for the query and the other for the write operations like so:

using (var readScope = Services.CreateScope())
using (var writeScope = Services.CreateScope())
{
   var entities = readScope.ServiceProvider.GetRequiredService<IReadService>().GetEntities();
   var writeService = writeScope.ServiceProvider.GetRequiredService<IWriteService>();
   foreach (Entity entity in entities)
   {
       writeService.DoSomething(entity);
   } 
}

Like that, there are effevtively two different instances of the DbContext being used.

Another possible solution would be to make sure, that the read operation has terminated before starting the iteration. That is not very pratical in my case because there could be a lot of results that would all need to be loaded into memory for the operation which I tried to avoid by using a Queryable in the first place.

Android: No Activity found to handle Intent error? How it will resolve

Add the below to your manifest:

  <activity   android:name=".AppPreferenceActivity" android:label="@string/app_name">  
     <intent-filter> 
       <action android:name="com.scytec.datamobile.vd.gui.android.AppPreferenceActivity" />  
       <category android:name="android.intent.category.DEFAULT" />  
     </intent-filter>   
  </activity>

Use CSS to make a span not clickable

Actually, you can achieve this via CSS. There's an almost unknown css rule named pointer-events. The a element will still be clickable but your description span won't.

a span.description {
    pointer-events: none;
}

there are other values like: all, stroke, painted, etc.

ref: http://robertnyman.com/2010/03/22/css-pointer-events-to-allow-clicks-on-underlying-elements/

UPDATE: As of 2016, all browsers now accept it: http://caniuse.com/#search=pointer-events

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

In ASP.NET Core MVC.

    public IActionResult Foo()
    {
        var data = GetData();

        var settings = new JsonSerializerSettings 
        { 
            ContractResolver = new CamelCasePropertyNamesContractResolver() 
        });

        return Json(data, settings);
    }

How can my iphone app detect its own version number?

A succinct way to obtain a version string in X.Y.Z format is:

[NSBundle mainBundle].infoDictionary[@"CFBundleVersion"]

Or, for just X.Y:

[NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"]

Both of these snippets returns strings that you would assign to your label object's text property, e.g.

myLabel.text = [NSBundle mainBundle].infoDictionary[@"CFBundleVersion"];

Integer to IP Address - C

You actually can use an inet function. Observe.

main.c:

#include <arpa/inet.h>

main() {
    uint32_t ip = 2110443574;
    struct in_addr ip_addr;
    ip_addr.s_addr = ip;
    printf("The IP address is %s\n", inet_ntoa(ip_addr));
}

The results of gcc main.c -ansi; ./a.out is

The IP address is 54.208.202.125

Note that a commenter said this does not work on Windows.

How can I Insert data into SQL Server using VBNet

Function ExtSql(ByVal sql As String) As Boolean
    Dim cnn As SqlConnection
    Dim cmd As SqlCommand
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        cmd = New SqlCommand
        cmd.Connection = cnn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cnn.Close()
        cmd.Dispose()
    Catch ex As Exception
        cnn.Close()
        Return False
    End Try
    Return True
End Function

jQuery issue - #<an Object> has no method

For anyone else arriving at this question:

I was performing the most simple jQuery, trying to hide an element:

('#fileselection').hide();

and I was getting the same type of error, "Uncaught TypeError: Object #fileselection has no method 'hide'

Of course, now it is obvious, but I just left off the jQuery indicator '$'. The code should have been:

$('#fileselection').hide();

This fixes the no-brainer problem. I hope this helps someone save a few minutes debugging!

Using BigDecimal to work with currencies

I would be radical. No BigDecimal.

Here is a great article https://lemnik.wordpress.com/2011/03/25/bigdecimal-and-your-money/

Ideas from here.

import java.math.BigDecimal;

public class Main {

    public static void main(String[] args) {
        testConstructors();
        testEqualsAndCompare();
        testArithmetic();
    }

    private static void testEqualsAndCompare() {
        final BigDecimal zero = new BigDecimal("0.0");
        final BigDecimal zerozero = new BigDecimal("0.00");

        boolean zerosAreEqual = zero.equals(zerozero);
        boolean zerosAreEqual2 = zerozero.equals(zero);

        System.out.println("zerosAreEqual: " + zerosAreEqual + " " + zerosAreEqual2);

        int zerosCompare = zero.compareTo(zerozero);
        int zerosCompare2 = zerozero.compareTo(zero);
        System.out.println("zerosCompare: " + zerosCompare + " " + zerosCompare2);
    }

    private static void testArithmetic() {
        try {
            BigDecimal value = new BigDecimal(1);
            value = value.divide(new BigDecimal(3));
            System.out.println(value);
        } catch (ArithmeticException e) {
            System.out.println("Failed to devide. " + e.getMessage());
        }
    }

    private static void testConstructors() {
        double doubleValue = 35.7;
        BigDecimal fromDouble = new BigDecimal(doubleValue);
        BigDecimal fromString = new BigDecimal("35.7");

        boolean decimalsEqual = fromDouble.equals(fromString);
        boolean decimalsEqual2 = fromString.equals(fromDouble);

        System.out.println("From double: " + fromDouble);
        System.out.println("decimalsEqual: " + decimalsEqual + " " + decimalsEqual2);
    }
}

It prints

From double: 35.7000000000000028421709430404007434844970703125
decimalsEqual: false false
zerosAreEqual: false false
zerosCompare: 0 0
Failed to devide. Non-terminating decimal expansion; no exact representable decimal result.

How about storing BigDecimal into a database? Hell, it also stores as a double value??? At least, if I use mongoDb without any advanced configuration it will store BigDecimal.TEN as 1E1.

Possible solutions?

I came with one - use String to store BigDecimal in Java as a String into the database. You have validation, for example @NotNull, @Min(10), etc... Then you can use a trigger on update or save to check if current string is a number you need. There are no triggers for mongo though. Is there a built-in way for Mongodb trigger function calls?

There is one drawback I am having fun around - BigDecimal as String in Swagger defenition

I need to generate swagger, so our front-end team understands that I pass them a number presented as a String. DateTime for example presented as a String.

There is another cool solution I read in the article above... Use long to store precise numbers.

A standard long value can store the current value of the Unites States national debt (as cents, not dollars) 6477 times without any overflow. Whats more: it’s an integer type, not a floating point. This makes it easier and accurate to work with, and a guaranteed behavior.


Update

https://stackoverflow.com/a/27978223/4587961

Maybe in the future MongoDb will add support for BigDecimal. https://jira.mongodb.org/browse/SERVER-1393 3.3.8 seems to have this done.

It is an example of the second approach. Use scaling. http://www.technology-ebay.de/the-teams/mobile-de/blog/mapping-bigdecimals-with-morphia-for-mongodb.html

List all indexes on ElasticSearch server?

For Elasticsearch 6.X, I found the following the most helpful. Each provide different data in the response.

# more verbose
curl -sS 'localhost:9200/_stats' | jq -C ".indices" | less

# less verbose, summary
curl -sS 'localhost:9200/_cluster/health?level=indices' | jq -C ".indices" | less

MySQL combine two columns into one column

I have used this way and Its a best forever. In this code null also handled

SELECT Title,
FirstName,
lastName, 
ISNULL(Title,'') + ' ' + ISNULL(FirstName,'') + ' ' + ISNULL(LastName,'') as FullName 
FROM Customer

Try this...

Numpy first occurrence of value greater than existing value

I'd like to propose

np.min(np.append(np.where(aa>5)[0],np.inf))

This will return the smallest index where the condition is met, while returning infinity if the condition is never met (and where returns an empty array).

What is (x & 1) and (x >>= 1)?

In addition to the answer of "dasblinkenlight" I think an example could help. I will only use 8 bits for a better understanding.

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

This is because 1 will be represented in bits as 00000001. Only the last bit is set to 1. Let's assume x is 185 which will be represented in bits as 10111001. If you apply a bitwise AND operation on x with 1 this will be the result:

00000001
10111001
--------
00000001

The first seven bits of the operation result will be 0 after the operation and will carry no information in this case (see Logical AND operation). Because whatever the first seven bits of the operand x were before, after the operation they will be 0. But the last bit of the operand 1 is 1 and it will reveal if the last bit of operand x was 0 or 1. So in this example the result of the bitwise AND operation will be 1 because our last bit of x is 1. If the last bit would have been 0, then the result would have been also 0, indicating that the last bit of operand x is 0:

00000001
10111000
--------
00000000

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift

Let's pick the example from above. For x >>= 1 this would be:

10111001
--------
01011100

And for left shift x <<= 1 it would be:

10111001
--------
01110010

Please pay attention to the note of user "dasblinkenlight" in regard to shifts.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I had the same issue however with doing an upload of a very large file using a python-requests client posting to a nginx+uwsgi backend.

What ended up being the cause was the the backend had a cap on the max file size for uploads lower than what the client was trying to send.

The error never showed up in our uwsgi logs since this limit was actually one imposed by nginx.

Upping the limit in nginx removed the error.

No ConcurrentList<T> in .Net 4.0?

ConcurrentList (as a resizeable array, not a linked list) is not easy to write with nonblocking operations. Its API doesn't translate well to a "concurrent" version.

Downloading jQuery UI CSS from Google's CDN

jQuery now has a CDN access:

code.jquery.com/ui/[version]/themes/[theme name]/jquery-ui.css


And to make this a little more easy, Here you go:

What is AndroidX?

androidx will replace support library after 28.0.0. You should migrate your project to use it. androidx uses Semantic Versioning. Using AndroidX will not be confused by version that is presented in library name and package name. Life becomes easier

[AndroidX and support compatibility]

Execute JavaScript using Selenium WebDriver in C#

the nuget package Selenium.Support already contains an extension method to help with this. Once it is included, one liner to executer script

  Driver.ExecuteJavaScript("console.clear()");

or

  string result = Driver.ExecuteJavaScript<string>("console.clear()");

How to assign text size in sp value using java code

Cleaner and more reusable approach is

define text size in dimens.xml file inside res/values/ directory:

</resources>
   <dimen name="text_medium">14sp</dimen>
</resources>

and then apply it to the TextView:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, context.getResources().getDimension(R.dimen.text_medium));

HTML5 Email Validation

In HTML5 you can do like this:

<form>
<input type="email" placeholder="Enter your email">
<input type="submit" value="Submit">
</form>

And when the user press submit, it automatically shows an error message like:

Error Message

Go test string contains substring

Use the function Contains from the strings package.

import (
    "strings"
)
strings.Contains("something", "some") // true

How to pass a textbox value from view to a controller in MVC 4?

When you want to pass new information to your application, you need to use POST form. In Razor you can use the following

View Code:

@* By default BeginForm use FormMethod.Post *@
@using(Html.BeginForm("Update")){
     @Html.Hidden("id", Model.Id)
     @Html.Hidden("productid", Model.ProductId)
     @Html.TextBox("qty", Model.Quantity)
     @Html.TextBox("unitrate", Model.UnitRate)
     <input type="submit" value="Update" />
}

Controller's actions

[HttpGet]
public ActionResult Update(){
     //[...] retrive your record object
     return View(objRecord);
}

[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
{
      if (ModelState.IsValid){
           int _records = UpdatePrice(id,productid,qty,unitrate);
           if (_records > 0){                    {
              return RedirectToAction("Index1", "Shopping");
           }else{                   
                ModelState.AddModelError("","Can Not Update");
           }
      }
      return View("Index1");
 }

Note that alternatively, if you want to use @Html.TextBoxFor(model => model.Quantity) you can either have an input with the name (respectecting case) "Quantity" or you can change your POST Update() to receive an object parameter, that would be the same type as your strictly typed view. Here's an example:

Model

public class Record {
    public string Id { get; set; }
    public string ProductId { get; set; }
    public string Quantity { get; set; }
    public decimal UnitRate { get; set; }
}

View

@using(Html.BeginForm("Update")){
     @Html.HiddenFor(model => model.Id)
     @Html.HiddenFor(model => model.ProductId)
     @Html.TextBoxFor(model=> model.Quantity)
     @Html.TextBoxFor(model => model.UnitRate)
     <input type="submit" value="Update" />
}

Post Action

[HttpPost]
public ActionResult Update(Record rec){ //Alternatively you can also use FormCollection object as well 
   if(TryValidateModel(rec)){
        //update code
   }
   return View("Index1");
}

How do I select elements of an array given condition?

Your expression works if you add parentheses:

>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'], 
      dtype='|S1')

Get all files modified in last 30 days in a directory

A couple of issues

  • You're not limiting it to files, so when it finds a matching directory it will list every file within it.
  • You can't use > in -exec without something like bash -c '... > ...'. Though the > will overwrite the file, so you want to redirect the entire find anyway rather than each -exec.
  • +30 is older than 30 days, -30 would be modified in last 30 days.
  • -exec really isn't needed, you could list everything with various -printf options.

Something like below should work

find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt

Example with -printf

find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt

This will list files in format "permissions owner group time date filename". -printf is generally preferable to -exec in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec. Depending on the version of find, you may also be able to use -ls, which has a similar format to above.

Java dynamic array sizes?

Arrays.copyOf() method has many options to fix the problem with Array length increasing dynamically.

Java API

intellij incorrectly saying no beans of type found for autowired repository

Sometimes you are required to indicate where @ComponentScan should scan for components. You can do so by passing the packages as parameter of this annotation, e.g:

@ComponentScan(basePackages={"path.to.my.components","path.to.my.othercomponents"})

However, as already mentioned, @SpringBootApplication annotation replaces @ComponentScan, hence in such cases you must do the same:

@SpringBootApplication(scanBasePackages={"path.to.my.components","path.to.my.othercomponents"})

At least in my case, Intellij stopped complaining.

Removing unwanted table cell borders with CSS

After trying the above suggestions, the only thing that worked for me was changing the border attribute to "0" in the following sections of a child theme's style.css (do a "Find" operation to locate each one -- the following are just snippets):

.comment-content table {
    border-bottom: 1px solid #ddd;

.comment-content td {
    border-top: 1px solid #ddd;
    padding: 6px 10px 6px 0;
}

Thus looking like this afterwards:

.comment-content table {
    border-bottom: 0;

.comment-content td {
    border-top: 0;
    padding: 6px 10px 6px 0;
}

Making an asynchronous task in Flask

I would use Celery to handle the asynchronous task for you. You'll need to install a broker to serve as your task queue (RabbitMQ and Redis are recommended).

app.py:

from flask import Flask
from celery import Celery

broker_url = 'amqp://guest@localhost'          # Broker URL for RabbitMQ task queue

app = Flask(__name__)    
celery = Celery(app.name, broker=broker_url)
celery.config_from_object('celeryconfig')      # Your celery configurations in a celeryconfig.py

@celery.task(bind=True)
def some_long_task(self, x, y):
    # Do some long task
    ...

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    data = json.loads(request.data)
    text_list = data.get('text_list')
    final_file = audio_class.render_audio(data=text_list)
    some_long_task.delay(x, y)                 # Call your async task and pass whatever necessary variables
    return Response(
        mimetype='application/json',
        status=200
    )

Run your Flask app, and start another process to run your celery worker.

$ celery worker -A app.celery --loglevel=debug

I would also refer to Miguel Gringberg's write up for a more in depth guide to using Celery with Flask.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

The github project JavaScript-Load-Image provides a complete solution to the EXIF orientation problem, correctly rotating/mirroring images for all 8 exif orientations. See the online demo of javascript exif orientation

The image is drawn onto an HTML5 canvas. Its correct rendering is implemented in js/load-image-orientation.js through canvas operations.

Hope this saves somebody else some time, and teaches the search engines about this open source gem :)

When should we use Observer and Observable?

Observer a.k.a callback is registered at Observable.

It is used for informing e.g. about events that happened at some point of time. It is widely used in Swing, Ajax, GWT for dispatching operations on e.g. UI events (button clicks, textfields changed etc).

In Swing you find methods like addXXXListener(Listener l), in GWT you have (Async)callbacks.

As list of observers is dynamic, observers can register and unregister during runtime. It is also a good way do decouple observable from observers, as interfaces are used.

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

How to manage a redirect request after a jQuery Ajax call

I was having this problem on a django app I'm tinkering with (disclaimer: I'm tinkering to learn, and am in no way an expert). What I wanted to do was use jQuery ajax to send a DELETE request to a resource, delete it on the server side, then send a redirect back to (basically) the homepage. When I sent HttpResponseRedirect('/the-redirect/') from the python script, jQuery's ajax method was receiving 200 instead of 302. So, what I did was to send a response of 300 with:

response = HttpResponse(status='300')
response['Location'] = '/the-redirect/' 
return  response

Then I sent/handled the request on the client with jQuery.ajax like so:

<button onclick="*the-jquery*">Delete</button>

where *the-jquery* =
$.ajax({ 
  type: 'DELETE', 
  url: '/resource-url/', 
  complete: function(jqxhr){ 
    window.location = jqxhr.getResponseHeader('Location'); 
  } 
});

Maybe using 300 isn't "right", but at least it worked just like I wanted it to.

PS :this was a huge pain to edit on the mobile version of SO. Stupid ISP put my service cancellation request through right when I was done with my answer!

Difference Between Select and SelectMany

Select is a simple one-to-one projection from source element to a result element. Select- Many is used when there are multiple from clauses in a query expression: each element in the original sequence is used to generate a new sequence.

Circle line-segment collision detection algorithm?

I have created this function for iOS following the answer given by chmike

+ (NSArray *)intersectionPointsOfCircleWithCenter:(CGPoint)center withRadius:(float)radius toLinePoint1:(CGPoint)p1 andLinePoint2:(CGPoint)p2
{
    NSMutableArray *intersectionPoints = [NSMutableArray array];

    float Ax = p1.x;
    float Ay = p1.y;
    float Bx = p2.x;
    float By = p2.y;
    float Cx = center.x;
    float Cy = center.y;
    float R = radius;


    // compute the euclidean distance between A and B
    float LAB = sqrt( pow(Bx-Ax, 2)+pow(By-Ay, 2) );

    // compute the direction vector D from A to B
    float Dx = (Bx-Ax)/LAB;
    float Dy = (By-Ay)/LAB;

    // Now the line equation is x = Dx*t + Ax, y = Dy*t + Ay with 0 <= t <= 1.

    // compute the value t of the closest point to the circle center (Cx, Cy)
    float t = Dx*(Cx-Ax) + Dy*(Cy-Ay);

    // This is the projection of C on the line from A to B.

    // compute the coordinates of the point E on line and closest to C
    float Ex = t*Dx+Ax;
    float Ey = t*Dy+Ay;

    // compute the euclidean distance from E to C
    float LEC = sqrt( pow(Ex-Cx, 2)+ pow(Ey-Cy, 2) );

    // test if the line intersects the circle
    if( LEC < R )
    {
        // compute distance from t to circle intersection point
        float dt = sqrt( pow(R, 2) - pow(LEC,2) );

        // compute first intersection point
        float Fx = (t-dt)*Dx + Ax;
        float Fy = (t-dt)*Dy + Ay;

        // compute second intersection point
        float Gx = (t+dt)*Dx + Ax;
        float Gy = (t+dt)*Dy + Ay;

        [intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Fx, Fy)]];
        [intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Gx, Gy)]];
    }

    // else test if the line is tangent to circle
    else if( LEC == R ) {
        // tangent point to circle is E
        [intersectionPoints addObject:[NSValue valueWithCGPoint:CGPointMake(Ex, Ey)]];
    }
    else {
        // line doesn't touch circle
    }

    return intersectionPoints;
}

Where is body in a nodejs http.get response?

A portion of Coffee here:

# My little helper
read_buffer = (buffer, callback) ->
  data = ''
  buffer.on 'readable', -> data += buffer.read().toString()
  buffer.on 'end', -> callback data

# So request looks like
http.get 'http://i.want.some/stuff', (res) ->
  read_buffer res, (response) ->
    # Do some things with your response
    # but don't do that exactly :D
    eval(CoffeeScript.compile response, bare: true)

And compiled

var read_buffer;

read_buffer = function(buffer, callback) {
  var data;
  data = '';
  buffer.on('readable', function() {
    return data += buffer.read().toString();
  });
  return buffer.on('end', function() {
    return callback(data);
  });
};

http.get('http://i.want.some/stuff', function(res) {
  return read_buffer(res, function(response) {
    return eval(CoffeeScript.compile(response, {
      bare: true
    }));
  });
});

jQuery count number of divs with a certain class?

You can use jQuery.children property.

var numItems = $('.wrapper').children('div').length;

for more information refer http://api.jquery.com/

How to escape regular expression special characters using javascript?

With \ you escape special characters

Escapes special characters to literal and literal characters to special.

E.g: /\(s\)/ matches '(s)' while /(\s)/ matches any whitespace and captures the match.

Source: http://www.javascriptkit.com/javatutors/redev2.shtml

ModuleNotFoundError: No module named 'sklearn'


Brief Introduction


When using Anaconda, one needs to be aware of the environment that one is working.

Then, in Anaconda Prompt (base) one needs to use the following code:

conda $command -n $ENVIRONMENT_NAME $IDE/package/module

$command - Command that I intend to use (consult documentation for general commands)

$ENVIRONMENT NAME - The name of your environment (if one is working in the root, conda $command $IDE/package/module is enough)

$IDE/package/module - The name of the IDE or package or module


Solution


If one wants to install it in the root and one follows the requirements - (Python (>= 2.7 or >= 3.4), NumPy (>= 1.8.2), SciPy (>= 0.13.3).) - the following will solve the problem:

conda install scikit-learn

Let's say that one is working in the environment with the name ML.

Then the following will solve one's problem:

conda install -n ML scikit-learn

Note: If one needs to install/update packages, the logic is the same as mentioned in the introduction. If you need more information on Anaconda Packages, check the documentation.


If the above doesn't work, on Anaconda Prompt one can also use pip (here's how to pip install scikit-learn) so the following may help

pip install scikit-learn

How to Apply Mask to Image in OpenCV?

Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:

import cv2

def apply_mask(frame, mask):
    """Apply binary mask to frame, return in-place masked image."""
    return cv2.bitwise_and(frame, frame, mask=mask)

Mask and frame must be the same size, so pixels remain as-is where mask is 1 and are set to zero where mask pixel is 0.

And for C++ it's a little bit different:

cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask

// ...

cv::Mat outFrame;  // Result output
inFrame.copyTo(outFrame, mask);

Accessing bash command line args $@ vs $*

$@ is same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

Of course, "$@" should be quoted.

http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

The annotation mappedBy ideally should always be used in the Parent side (Company class) of the bi directional relationship, in this case it should be in Company class pointing to the member variable 'company' of the Child class (Branch class)

The annotation @JoinColumn is used to specify a mapped column for joining an entity association, this annotation can be used in any class (Parent or Child) but it should ideally be used only in one side (either in parent class or in Child class not in both) here in this case i used it in the Child side (Branch class) of the bi directional relationship indicating the foreign key in the Branch class.

below is the working example :

parent class , Company

@Entity
public class Company {


    private int companyId;
    private String companyName;
    private List<Branch> branches;

    @Id
    @GeneratedValue
    @Column(name="COMPANY_ID")
    public int getCompanyId() {
        return companyId;
    }

    public void setCompanyId(int companyId) {
        this.companyId = companyId;
    }

    @Column(name="COMPANY_NAME")
    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    @OneToMany(fetch=FetchType.LAZY,cascade=CascadeType.ALL,mappedBy="company")
    public List<Branch> getBranches() {
        return branches;
    }

    public void setBranches(List<Branch> branches) {
        this.branches = branches;
    }


}

child class, Branch

@Entity
public class Branch {

    private int branchId;
    private String branchName;
    private Company company;

    @Id
    @GeneratedValue
    @Column(name="BRANCH_ID")
    public int getBranchId() {
        return branchId;
    }

    public void setBranchId(int branchId) {
        this.branchId = branchId;
    }

    @Column(name="BRANCH_NAME")
    public String getBranchName() {
        return branchName;
    }

    public void setBranchName(String branchName) {
        this.branchName = branchName;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="COMPANY_ID")
    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }


}

How to loop through an array containing objects and access their properties

myArray[j.x] is logically incorrect.

Use (myArray[j].x); instead

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}

Access denied for user 'root'@'localhost' with PHPMyAdmin

Here are few steps that must be followed carefully

  1. First of all make sure that the WAMP server is running if it is not running, start the server.
  2. Enter the URL http://localhost/phpmyadmin/setup in address bar of your browser.
  3. Create a folder named config inside C:\wamp\apps\phpmyadmin, the folder inside apps may have different name like phpmyadmin3.2.0.1

  4. Return to your browser in phpmyadmin setup tab, and click New server.New server

  5. Change the authentication type to ‘cookie’ and leave the username and password field empty but if you change the authentication type to ‘config’ enter the password for username root.

  6. Click save save

  7. Again click save in configuration file option.
  8. Now navigate to the config folder. Inside the folder there will be a file named config.inc.php. Copy the file and paste it out of the folder (if the file with same name is already there then override it) and finally delete the folder.
  9. Now you are done. Try to connect the mysql server again and this time you won’t get any error. --credits Bibek Subedi

Insert all data of a datagridview to database at once

You can do the same thing with the connection opened just once. Something like this.

for(int i=0; i< dataGridView1.Rows.Count;i++)
  {
    string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";

  try
  {
      SqlConnection conn = new SqlConnection();
      conn.Open();

          using (SqlCommand comm = new SqlCommand(StrQuery, conn))
          {
              comm.ExecuteNonQuery();
          }
      conn.Close();

  }

Also, depending on your specific scenario you may want to look into binding the grid to the database. That would reduce the amount of manual work greatly: http://www.switchonthecode.com/tutorials/csharp-tutorial-binding-a-datagridview-to-a-database

Set the maximum character length of a UITextField in Swift

Working In Swift4

// STEP 1 set UITextFieldDelegate

    class SignUPViewController: UIViewController , UITextFieldDelegate {

       @IBOutlet weak var userMobileNoTextFiled: UITextField!

        override func viewDidLoad() {
            super.viewDidLoad()

// STEP 2 set delegate
userMobileNoTextFiled.delegate = self //set delegate }

     func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    //        guard let text = userMobileNoTextFiled.text else { return true }
    //        let newLength = text.count + string.count - range.length
    //        return newLength <= 10
    //    }

// STEP 3 call func

        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            let maxLength = 10          // set your need
            let currentString: NSString = textField.text! as NSString
            let newString: NSString =
                currentString.replacingCharacters(in: range, with: string) as NSString
            return newString.length <= maxLength
        }
    }

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

What are the specific differences between .msi and setup.exe file?

MSI is basically an installer from Microsoft that is built into windows. It associates components with features and contains installation control information. It is not necessary that this file contains actual user required files i.e the application programs which user expects. MSI can contain another setup.exe inside it which the MSI wraps, which actually contains the user required files.

Hope this clears you doubt.

WAMP Cannot access on local network 403 Forbidden

For Apache 2.4.9

in addition, look at the httpd-vhosts.conf file in C:\wamp\bin\apache\apache2.4.9\conf\extra

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require local
</Directory>
</VirtualHost>

Change to:

<VirtualHost *:80>
ServerName localhost
ServerAlias localhost
DocumentRoot C:/wamp/www
<Directory "C:/wamp/www/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
</VirtualHost>

changing from "Require local" to "Require all granted" solved the error 403 in my local network

Find package name for Android apps to use Intent to launch Market app from web

Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >

Using Get-childitem to get a list of files modified in the last 3 days

I wanted to just add this as a comment to the previous answer, but I can't. I tried Dave Sexton's answer but had problems if the count was 1. This forces an array even if one object is returned.

([System.Object[]](gci c:\pstback\ -Filter *.pst | 
    ? { $_.LastWriteTime -gt (Get-Date).AddDays(-3)})).Count

It still doesn't return zero if empty, but testing '-lt 1' works.

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

Sorry, but I think the accepted answer is an overkill. All you need to do is this:

public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
    public void OnException (ExceptionContext context)
    {
        // Log only handled exceptions, because all other will be caught by ELMAH anyway.
        if (context.ExceptionHandled)
            ErrorSignal.FromCurrentContext().Raise(context.Exception);
    }
}

and then register it (order is important) in Global.asax.cs:

public static void RegisterGlobalFilters (GlobalFilterCollection filters)
{
    filters.Add(new ElmahHandledErrorLoggerFilter());
    filters.Add(new HandleErrorAttribute());
}

Image inside div has extra space below the image

One can also nullify parent's line height:

#wrapper {
  line-height: 0;
}

All fixes: http://jsfiddle.net/FaPFv/

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How to insert logo with the title of a HTML page?

Are you referring to the favicon?

Upload a 16x16px ico to your site, and link it in your head section.

<link rel="shortcut icon" href="/favicon.ico" />

There are a multitude of sites that help you convert images into .ico format too. This is just the first one I saw on Google. http://www.favicon.cc/

Run/install/debug Android applications over Wi-Fi?

Install plugin Android WiFi ADB

Download and install Android WiFi ADB directly from Android Studio:

File > Settings->Plugins->Browse Repositories-> Android WiFi ADB ->Install ->Connect with cable for first time -> Click on "Connect" -> Now remove cable and start doing debug/run.

Check ss for your reference :

Android WiFi ADB

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

How to add a default include path for GCC in Linux?

Create an alias for gcc with your favorite includes.

alias mygcc='gcc -I /whatever/'

How do I get textual contents from BLOB in Oracle SQL

Use TO_CHAR function.

select TO_CHAR(BLOB_FIELD) from TABLE_WITH_BLOB where ID = '<row id>'

Converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set. The value returned is always VARCHAR2.

How can I pause setInterval() functions?

The following code, provides a precision way to pause resume a timer.

How it works:

When the timer is resumed after a pause, it generates a correction cycle using a single timeout, that will consider the pause offset (exact time when the timer was paused between cycles). After the correction cycle finishes, it schedules the following cycles with a regular setInteval, and continues normally the cycle execution.

This allows to pause/resume the timer, without losing the sync.

Code :

_x000D_
_x000D_
function Timer(_fn_callback_ , _timer_freq_){_x000D_
    let RESUME_CORRECTION_RATE = 2;_x000D_
_x000D_
    let _timer_statusCode_;_x000D_
    let _timer_clockRef_;_x000D_
_x000D_
    let _time_ellapsed_;        // will store the total time ellapsed_x000D_
    let _time_pause_;           // stores the time when timer is paused_x000D_
    let _time_lastCycle_;       // stores the time of the last cycle_x000D_
_x000D_
    let _isCorrectionCycle_;_x000D_
 _x000D_
    /**_x000D_
     * execute in each clock cycle_x000D_
     */_x000D_
    const nextCycle = function(){_x000D_
        // calculate deltaTime_x000D_
        let _time_delta_        = new Date() - _time_lastCycle_;_x000D_
        _time_lastCycle_    = new Date();_x000D_
        _time_ellapsed_   += _time_delta_;_x000D_
_x000D_
        // if its a correction cicle (caused by a pause,_x000D_
        // destroy the temporary timeout and generate a definitive interval_x000D_
        if( _isCorrectionCycle_ ){_x000D_
            clearTimeout( _timer_clockRef_ );_x000D_
            clearInterval( _timer_clockRef_ );_x000D_
            _timer_clockRef_    = setInterval(  nextCycle , _timer_freq_  );_x000D_
            _isCorrectionCycle_ = false;_x000D_
        }_x000D_
        // execute callback_x000D_
        _fn_callback_.apply( timer, [ timer ] );_x000D_
    };_x000D_
_x000D_
    // initialize timer_x000D_
    _time_ellapsed_     = 0;_x000D_
    _time_lastCycle_     = new Date();_x000D_
    _timer_statusCode_   = 1;_x000D_
    _timer_clockRef_     = setInterval(  nextCycle , _timer_freq_  );_x000D_
_x000D_
_x000D_
    // timer public API_x000D_
    const timer = {_x000D_
        get statusCode(){ return _timer_statusCode_ },_x000D_
        get timestamp(){_x000D_
            let abstime;_x000D_
            if( _timer_statusCode_=== 1 ) abstime = _time_ellapsed_ + ( new Date() - _time_lastCycle_ );_x000D_
            else if( _timer_statusCode_=== 2 ) abstime = _time_ellapsed_ + ( _time_pause_ - _time_lastCycle_ );_x000D_
            return abstime || 0;_x000D_
        },_x000D_
_x000D_
        pause : function(){_x000D_
            if( _timer_statusCode_ !== 1 ) return this;_x000D_
            // stop timers_x000D_
            clearTimeout( _timer_clockRef_ );_x000D_
            clearInterval( _timer_clockRef_ );_x000D_
            // set new status and store current time, it will be used on_x000D_
            // resume to calculate how much time is left for next cycle_x000D_
            // to be triggered_x000D_
            _timer_statusCode_ = 2;_x000D_
            _time_pause_       = new Date();_x000D_
            return this;_x000D_
        },_x000D_
_x000D_
        resume: function(){_x000D_
            if( _timer_statusCode_ !== 2 ) return this;_x000D_
            _timer_statusCode_  = 1;_x000D_
            _isCorrectionCycle_ = true;_x000D_
            const delayEllapsedTime = _time_pause_ - _time_lastCycle_;_x000D_
            _time_lastCycle_    = new Date( new Date() - (_time_pause_ - _time_lastCycle_) );_x000D_
_x000D_
            _timer_clockRef_ = setTimeout(  nextCycle , _timer_freq_ - delayEllapsedTime - RESUME_CORRECTION_RATE);_x000D_
_x000D_
            return this;_x000D_
        } _x000D_
    };_x000D_
    return timer;_x000D_
};_x000D_
_x000D_
_x000D_
let myTimer = Timer( x=> console.log(x.timestamp), 1000);
_x000D_
<input type="button" onclick="myTimer.pause()" value="pause">_x000D_
<input type="button" onclick="myTimer.resume()" value="resume">
_x000D_
_x000D_
_x000D_

Code source :

This Timer is a modified and simplified version of advanced-timer, a js library created by myself, with many more functionalities.

The full library and documentation is available in NPM and GITHUB

How to show an alert box in PHP?

When I just run this as a page

<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
exit;

it works fine.

What version of PHP are you running?

Could you try echoing something else after: $testObject->split_for_sms($Chat);

Maybe it doesn't get to that part of the code? You could also try these with the other function calls to check where your program stops/is getting to.

Hope you get a bit further with this.

Concat scripts in order with Gulp

Apparently you can pass in the "nosort" option to gulp.src gulp.src.

How to divide flask app into multiple py files?

This task can be accomplished without blueprints and tricky imports using Centralized URL Map

app.py

import views
from flask import Flask

app = Flask(__name__)

app.add_url_rule('/', view_func=views.index)
app.add_url_rule('/other', view_func=views.other)

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)

views.py

from flask import render_template

def index():
    return render_template('index.html')

def other():
    return render_template('other.html')

How to get a random number in Ruby

range = 10..50

rand(range)

or

range.to_a.sample

or

range.to_a.shuffle(this will shuffle whole array and you can pick a random number by first or last or any from this array to pick random one)

Bootstrap 4 align navbar items to the right

use the flex-row-reverse class

<nav class="navbar navbar-toggleable-md navbar-light">
    <div class="container">
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false"
          aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="#">
            <i class="fa fa-hospital-o fa-2x" aria-hidden="true"></i>
        </a>
        <div class="collapse navbar-collapse flex-row-reverse" id="navbarNavAltMarkup">
            <ul class="navbar-nav">
                <li><a class="nav-item nav-link active" href="#" style="background-color:#666">Home <span class="sr-only">(current)</span></a</li>
                <li><a class="nav-item nav-link" href="#">Doctors</a></li>
                <li><a class="nav-item nav-link" href="#">Specialists</a></li>
                <li><a class="nav-item nav-link" href="#">About</a></li>
            </ul>
        </div>
    </div>
</nav>

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

There are a lot of good answers on the post, but I wanted the format to come out exactly as it does with JavaScript. This is what I'm using and it works well.

In [1]: import datetime

In [1]: now = datetime.datetime.utcnow()

In [1]: now.strftime('%Y-%m-%dT%H:%M:%S') + now.strftime('.%f')[:4] + 'Z'
Out[3]: '2018-10-16T13:18:34.856Z'

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Checking if a variable is initialized

Depending on your applications (and especially if you're already using boost), you might want to look into boost::optional.

(UPDATE: As of C++17, optional is now part of the standard library, as std::optional)

It has the property you are looking for, tracking whether the slot actually holds a value or not. By default it is constructed to not hold a value and evaluate to false, but if it evaluates to true you are allowed to dereference it and get the wrapped value.

class MyClass
{
    void SomeMethod();

    optional<char> mCharacter;
    optional<double> mDecimal;
};

void MyClass::SomeMethod()
{
    if ( mCharacter )
    {
        // do something with *mCharacter.
        // (note you must use the dereference operator)
    }

    if ( ! mDecimal )
    {
        // call mDecimal.reset(expression)
        // (this is how you assign an optional)
    }
}

More examples are in the Boost documentation.

Why is document.body null in my javascript?

The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head section that uses body. Not cool.

You want to wrap this code in a window.onload handler or place it after the <body> tag (as mentioned by e-bacho 2.0).

<head>
    <title>Javascript Tests</title>

    <script type="text/javascript">
      window.onload = function() {
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");
      }

    </script>
</head>

See demo.

Collections sort(List<T>,Comparator<? super T>) method example

To use Collections sort(List,Comparator) , you need to create a class that implements Comparator Interface, and code for the compare() in it, through Comparator Interface

You can do something like this:

class StudentComparator implements Comparator
{
    public int compare (Student s1 Student s2)
    {
        // code to compare 2 students
    }
}

To sort do this:

 Collections.sort(List,new StudentComparator())

How can I get zoom functionality for images?

I used a WebView and loaded the image from the memory via

webview.loadUrl("file://...")

The WebView handles all the panning zooming and scrolling. If you use wrap_content the webview won't be bigger then the image and no white areas are shown. The WebView is the better ImageView ;)

docker entrypoint running bash script gets "permission denied"

I faced same issue & it resolved by

ENTRYPOINT ["sh", "/docker-entrypoint.sh"]

For the Dockerfile in the original question it should be like:

ENTRYPOINT ["sh", "/usr/src/app/docker-entrypoint.sh"]

#if DEBUG vs. Conditional("DEBUG")

It really depends on what you're going for:

  • #if DEBUG: The code in here won't even reach the IL on release.
  • [Conditional("DEBUG")]: This code will reach the IL, however calls to the method will be omitted unless DEBUG is set when the caller is compiled.

Personally I use both depending on the situation:

Conditional("DEBUG") Example: I use this so that I don't have to go back and edit my code later during release, but during debugging I want to be sure I didn't make any typos. This function checks that I type a property name correctly when trying to use it in my INotifyPropertyChanged stuff.

[Conditional("DEBUG")]
[DebuggerStepThrough]
protected void VerifyPropertyName(String propertyName)
{
    if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        Debug.Fail(String.Format("Invalid property name. Type: {0}, Name: {1}",
            GetType(), propertyName));
}

You really don't want to create a function using #if DEBUG unless you are willing to wrap every call to that function with the same #if DEBUG:

#if DEBUG
    public void DoSomething() { }
#endif

    public void Foo()
    {
#if DEBUG
        DoSomething(); //This works, but looks FUGLY
#endif
    }

versus:

[Conditional("DEBUG")]
public void DoSomething() { }

public void Foo()
{
    DoSomething(); //Code compiles and is cleaner, DoSomething always
                   //exists, however this is only called during DEBUG.
}

#if DEBUG example: I use this when trying to setup different bindings for WCF communication.

#if DEBUG
        public const String ENDPOINT = "Localhost";
#else
        public const String ENDPOINT = "BasicHttpBinding";
#endif

In the first example, the code all exists, but is just ignored unless DEBUG is on. In the second example, the const ENDPOINT is set to "Localhost" or "BasicHttpBinding" depending on if DEBUG is set or not.


Update: I am updating this answer to clarify an important and tricky point. If you choose to use the ConditionalAttribute, keep in mind that calls are omitted during compilation, and not runtime. That is:

MyLibrary.dll

[Conditional("DEBUG")]
public void A()
{
    Console.WriteLine("A");
    B();
}

[Conditional("DEBUG")]
public void B()
{
    Console.WriteLine("B");
}

When the library is compiled against release mode (i.e. no DEBUG symbol), it will forever have the call to B() from within A() omitted, even if a call to A() is included because DEBUG is defined in the calling assembly.

program cant start because php5.dll is missing

In case this might help someone, after installing the thread safe version of PHP 5.5.1, everything was working under apache for my dev sites, but I ran into the same "php5.dll is missing" problem installing Composer using the Composer-Setup.exe - or, as I soon discovered, just running something as simple as php -v from the command line. I made a copy of php5ts.dll and named it php5.dll and everything worked. I assume the Composer installer was specifically looking for "php5.dll" and I knew that the thread safe code would be run by the renamed .dll. I also assume something is wrong with my setup to screw up the command line functionality, but with everything working, I have more important issues to deal with than to try and find the problem.

MySQL does not start when upgrading OSX to Yosemite or El Capitan

I’ve got a similar problem with MySQL on a Mac (Mac Os X Could not startup MySQL Server. Reason: 255 and also “ERROR! The server quit without updating PID file”). After a long trial and error process, finally in order to restore the file permissions, I’ve just do that:

* launch the Disk Utilities.app
* choose my drive on the left panel
* click on the “Repair disk permissions” button

This did the trick for me.

Hoping this can help someone else.

'this' implicitly has type 'any' because it does not have a type annotation

The error is indeed fixed by inserting this with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS

It should've been this:

foo.on('error', function(this: Foo, err: any) {

or this:

foo.on('error', function(this: typeof foo, err: any) {

A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

How to do an array of hashmaps?

You can't have an array of a generic type. Use List instead.

How to set DateTime to null

This line:

eventCustom.DateTimeEnd = dateTimeEndResult = true ? (DateTime?)null : dateTimeEndResult;

is same as:

eventCustom.DateTimeEnd = dateTimeEndResult = (true ? (DateTime?)null : dateTimeEndResult);

because the conditional operator ? has a higher precedence than the assignment operator =. That's why you always get null for eventCustom.DateTimeEnd. (MSDN Ref)

AngularJS resource promise

You could also do:

Regions.query({}, function(response) {
    $scope.regions = response;
    // Do stuff that depends on $scope.regions here
});

Repeat command automatically in Linux

You can run the following and filter the size only. If your file was called somefilename you can do the following

while :; do ls -lh | awk '/some*/{print $5}'; sleep 5; done

One of the many ideas.

Convert a dta file to csv without Stata software

StatTransfer is a program that moves data easily between Stata, Excel (or csv), SAS, etc. It is very user friendly (requires no programming skills). See www.stattransfer.com

If you use the program just note that you will have to choose "ASCII/Text - Delimited" to work with .csv files rather than .xls

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I followed the above (never a bad idea to keep up to date with brew anyhow) and still had the same exact issue:

LAPTOP:folder Username$ php -v
dyld: Library not loaded: /usr/local/lib/libpng15.15.dylib
  Referenced from: /usr/local/bin/php
  Reason: image not found
Trace/BPT trap: 5

Then figured out a simpler way:

Search for your libpng version(s) on your box:

# Requires locate & updatedb for mac os x
# See Link [1] 
LAPTOP:folder Username$ locate libpng15.15.dylib
/Applications/GIMP.app/Contents/Resources/lib/libpng15.15.dylib
/usr/X11/lib/libpng15.15.dylib
/usr/local/Cellar/libpng/1.5.14/lib/libpng15.15.dylib

Make a symlink:

LAPTOP:folder Username$ ln -s /usr/local/Cellar/libpng/1.5.14/lib/libpng15.15.dylib /usr/local/lib/libpng15.15.dylib

Try again:

LAPTOP:folder Username$ php -v
PHP 5.3.26 (cli) (built: Aug 25 2013 16:07:23) 
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2013 Zend Technologies
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans

1) Mac OS X equivalent of locate

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

The solution is to put the scripts in an outside js file (lets called 'yourDynamic.js') and re-register de file everytime you refresh the updatepanel.

I use this in the updatepanel_prerender event:

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, UpdatePanel1.GetType(), "UpdatePanel1_PreRender", _
                   "<script type='text/javascript' id='UpdatePanel1_PreRender'>" & _
                   "include('yourDynamic.js');" & _
                   "removeDuplicatedScript('UpdatePanel1_PreRender');</script>" _
                   , False)

In the page or in some other include you will need this javascript:

// Include a javascript file inside another one.
function include(filename)
{
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].getAttribute('src'))
        {
            if(scripts[x].getAttribute('src').indexOf(filename) != -1)
            {
                head.removeChild(scripts[x]);
                break;
            }
        }
    }

    script = document.createElement('script');
    script.src = filename;
    script.type = 'text/javascript';
    head.appendChild(script)
}

// Removes duplicated scripts.
function removeDuplicatedScript(id)
{
    var count = 0;
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    var firstScript;
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].getAttribute('id'))
        {
            if(scripts[x].getAttribute('id').indexOf(id) != -1)
            {
                if (count == 0)
                {
                    firstScript = scripts[x];
                    count++;
                }
                else
                {
                    head.removeChild(firstScript);
                    firstScript = scripts[x];
                    count = 1;
                }
            }
        }
    }
    clearAjaxNetJunk();
}
// Evoids the update panel auto generated scripts to grow to inifity. X-(
function clearAjaxNetJunk()
{
    var knowJunk = 'Sys.Application.add_init(function() {';
    var count = 0;
    var head = document.getElementsByTagName('head')[0];

    var scripts = document.getElementsByTagName('script');
    var firstScript;
    for(var x=0;x<scripts.length;>    {
        if (scripts[x].textContent)
        {
            if(scripts[x].textContent.indexOf(knowJunk) != -1)
            {
                if (count == 0)
                {
                    firstScript = scripts[x];
                    count++;
                }
                else
                {
                    head.removeChild(firstScript);
                    firstScript = scripts[x];
                    count = 1;
                }
            }
        }
    }
}

Pretty cool, ah...jejeje This part of what i posted some time ago here.

Hope this help... :)

(413) Request Entity Too Large | uploadReadAheadSize

In my case, I was getting this error message because I was changed the service's namespace and services tag was pointed to the older namespace. I refreshed the namespace and the error disapear:

<services>
  <service name="My.Namespace.ServiceName"> <!-- Updated name -->
    <endpoint address="" 
              binding="wsHttpBinding" 
              bindingConfiguration="MyBindingConfiguratioName" 
              contract="My.Namespace.Interface" <!-- Updated contract -->
    />
  </service>
</services>

What is __gxx_personality_v0 for?

The answers above are correct: it is used in exception handling. The manual for GCC version 6 has more information (which is no longer present in the version 7 manual). The error can arise when linking an external function that - unknown to GCC - throws Java exceptions.

Converting an object to a string

It appears JSON accept the second parameter that could help with functions - replacer, this solves the issue of converting in the most elegant way:

JSON.stringify(object, (key, val) => {
    if (typeof val === 'function') {
      return String(val);
    }
    return val;
  });

Null vs. False vs. 0 in PHP

Somebody can explain to me why 'NULL' is not just a string in a comparison instance?

$x = 0;
var_dump($x == 'NULL');  # TRUE   !!!WTF!!!

Detect click outside Angular component

ginalx's answer should be set as the default one imo: this method allows for many optimizations.

The problem

Say that we have a list of items and on every item we want to include a menu that needs to be toggled. We include a toggle on a button that listens for a click event on itself (click)="toggle()", but we also want to toggle the menu whenever the user clicks outside of it. If the list of items grows and we attach a @HostListener('document:click') on every menu, then every menu loaded within the item will start listening for the click on the entire document, even when the menu is toggled off. Besides the obvious performance issues, this is unnecessary.

You can, for example, subscribe whenever the popup gets toggled via a click and start listening for "outside clicks" only then.


isActive: boolean = false;

// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;

private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;


constructor(
 ...
 private _utilitiesService: UtilitiesService,
 private _elementRef: ElementRef,
){
 ...
 this._toggleMenuSubject$ = new BehaviorSubject(false);
 this._toggleMenu$ = this._toggleMenuSubject$.asObservable();

}

ngOnInit() {
 this._toggleMenuSub = this._toggleMenu$.pipe(
      tap(isActive => {
        logger.debug('Label Menu is active', isActive)
        this.isActive = isActive;

        // subscribe to the click event only if the menu is Active
        // otherwise unsubscribe and save memory
        if(isActive === true){
          this._clickSub = this._utilitiesService.documentClickedTarget
           .subscribe(target => this._documentClickListener(target));
        }else if(isActive === false && this._clickSub !== null){
          this._clickSub.unsubscribe();
        }

      }),
      // other observable logic
      ...
      ).subscribe();
}

toggle() {
    this._toggleMenuSubject$.next(!this.isActive);
}

private _documentClickListener(targetElement: HTMLElement): void {
    const clickedInside = this._elementRef.nativeElement.contains(targetElement);
    if (!clickedInside) {
      this._toggleMenuSubject$.next(false);
    }    
 }

ngOnDestroy(){
 this._toggleMenuSub.unsubscribe();
}

And, in *.component.html:


<button (click)="toggle()">Toggle the menu</button>

Why does "pip install" inside Python raise a SyntaxError?

Try upgrade pip with the below command and retry

python -m pip install -U pip

Uploading images using Node.js, Express, and Mongoose

Again if you don't want to use bodyParser, the following works:

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

app.use(express.static('./public'));


app.configure(function(){
    app.use(express.methodOverride());
    app.use(express.multipart({
        uploadDir: './uploads',
        keepExtensions: true
    }));
});


app.use(app.router);

app.get('/upload', function(req, res){
    // Render page with upload form
    res.render('upload');
});

app.post('/upload', function(req, res){
    // Returns json of uploaded file
    res.json(req.files);
});

http.createServer(app).listen(3000, function() {
    console.log('App started');
});