Programs & Examples On #Custom code

How to disable 'X-Frame-Options' response header in Spring Security?

If using XML configuration you can use

<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:security="http://www.springframework.org/schema/security"> 
<security:http>
    <security:headers>
         <security:frame-options disabled="true"></security:frame-options>
    </security:headers>
</security:http>
</beans>

Extract a single (unsigned) integer from a string

An alternative solution with sscanf:

$str = "In My Cart : 11 items";
list($count) = sscanf($str, 'In My Cart : %s items');

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

child: Container(
   child: isFile == true ? 
            Image.network(pathfile, width: 300, height: 200, fit: BoxFit.cover) : 
            Text(message.subject.toString(), style: TextStyle(color: Colors.white),
      ),
),

How do I change selected value of select2 dropdown with JqGrid?

For select2 version >= 4.0.0

The other solutions might not work, however the following examples should work.

Solution 1: Causes all attached change events to trigger, including select2

$('select').val('1').trigger('change');

Solution 2: Causes JUST select2 change event to trigger

$('select').val('1').trigger('change.select2');

See this jsfiddle for examples of these. Thanks to @minlare for Solution 2.

Explanation:

Say I have a best friend select with people's names. So Bob, Bill and John (in this example I assume the Value is the same as the name). First I initialize select2 on my select:

$('#my-best-friend').select2();

Now I manually select Bob in the browser. Next Bob does something naughty and I don't like him anymore. So the system unselects Bob for me:

$('#my-best-friend').val('').trigger('change');

Or say I make the system select the next in the list instead of Bob:

// I have assume you can write code to select the next guy in the list
$('#my-best-friend').val('Bill').trigger('change');  

Notes on Select 2 website (see Deprecated and removed methods) that might be useful for others:

.select2('val') The "val" method has been deprecated and will be removed in Select2 4.1. The deprecated method no longer includes the triggerChange parameter.

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

$('select').val('1').trigger('change'); // instead of $('select').select2('val', '1');

How can I represent a range in Java?

Apache Commons Lang has a Range class for doing arbitrary ranges.

Range<Integer> test = Range.between(1, 3);
System.out.println(test.contains(2));
System.out.println(test.contains(4));

Guava Range has similar API.

If you are just wanting to check if a number fits into a long value or an int value, you could try using it through BigDecimal. There are methods for longValueExact and intValueExact that throw exceptions if the value is too big for those precisions.

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

Form/JavaScript not working on IE 11 with error DOM7011

This error occurred for me when using window.location.reload(). Replacing with window.location = window.location.href solved the problem.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

How to plot ROC curve in Python

This is the simplest way to plot an ROC curve, given a set of ground truth labels and predicted probabilities. Best part is, it plots the ROC curve for ALL classes, so you get multiple neat-looking curves as well

import scikitplot as skplt
import matplotlib.pyplot as plt

y_true = # ground truth labels
y_probas = # predicted probabilities generated by sklearn classifier
skplt.metrics.plot_roc_curve(y_true, y_probas)
plt.show()

Here's a sample curve generated by plot_roc_curve. I used the sample digits dataset from scikit-learn so there are 10 classes. Notice that one ROC curve is plotted for each class.

ROC Curves

Disclaimer: Note that this uses the scikit-plot library, which I built.

What is an idempotent operation?

my 5c: In integration and networking the idempotency is very important. Several examples from real-life: Imagine, we deliver data to the target system. Data delivered by a sequence of messages. 1. What would happen if the sequence is mixed in channel? (As network packages always do :) ). If the target system is idempotent, the result will not be different. If the target system depends of the right order in the sequence, we have to implement resequencer on the target site, which would restore the right order. 2. What would happen if there are the message duplicates? If the channel of target system does not acknowledge timely, the source system (or channel itself) usually sends another copy of the message. As a result we can have duplicate message on the target system side. If the target system is idempotent, it takes care of it and result will not be different. If the target system is not idempotent, we have to implement deduplicator on the target system side of the channel.

What is a Python egg?

The .egg file is a distribution format for Python packages. It’s just an alternative to a source code distribution or Windows exe. But note that for pure Python, the .egg file is completely cross-platform.

The .egg file itself is essentially a .zip file. If you change the extension to “zip”, you can see that it will have folders inside the archive.

Also, if you have an .egg file, you can install it as a package using easy_install

Example: To create an .egg file for a directory say mymath which itself may have several python scripts, do the following step:

# setup.py
from setuptools import setup, find_packages
setup(
    name = "mymath",
    version = "0.1",
    packages = find_packages()
    )

Then, from the terminal do:

 $ python setup.py bdist_egg

This will generate lot of outputs, but when it’s completed you’ll see that you have three new folders: build, dist, and mymath.egg-info. The only folder that we care about is the dist folder where you'll find your .egg file, mymath-0.1-py3.5.egg with your default python (installation) version number(mine here: 3.5)

Source: Python library blog

File Upload in WebView

I found that I needed 3 interface definitions in order to handle various version of android.

public void openFileChooser(ValueCallback < Uri > uploadMsg) {
  mUploadMessage = uploadMsg;
  Intent i = new Intent(Intent.ACTION_GET_CONTENT);
  i.addCategory(Intent.CATEGORY_OPENABLE);
  i.setType("image/*");
  FreeHealthTrack.this.startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILECHOOSER_RESULTCODE);
}

public void openFileChooser(ValueCallback < Uri > uploadMsg, String acceptType) {
  openFileChooser(uploadMsg);
}

public void openFileChooser(ValueCallback < Uri > uploadMsg, String acceptType, String capture) {
  openFileChooser(uploadMsg);
}

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

Making a Simple Ajax call to controller in asp.net mvc

View;

 $.ajax({
        type: 'GET',
        cache: false,
        url: '/Login/Method',
        dataType: 'json',
        data: {  },
        error: function () {
        },
        success: function (result) {
            alert("success")
        }
    });

Controller Method;

 public JsonResult Method()
 {
   return Json(new JsonResult()
      {
         Data = "Result"
      }, JsonRequestBehavior.AllowGet);
 }

How do I declare and assign a variable on a single line in SQL

Here goes:

DECLARE @var nvarchar(max) = 'Man''s best friend';

You will note that the ' is escaped by doubling it to ''.

Since the string delimiter is ' and not ", there is no need to escape ":

DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';

The second example in the MSDN page on DECLARE shows the correct syntax.

Shortcut key for commenting out lines of Python code in Spyder

While the other answers got it right when it comes to add comments, in my case only the following worked.

  • Multi-line comment

    select the lines to be commented + Ctrl + 4

  • Multi-line uncomment

    select the lines to be uncommented + Ctrl + 1

Using @property versus getters and setters

Both @property and traditional getters and setters have their advantages. It depends on your use case.

Advantages of @property

  • You don't have to change the interface while changing the implementation of data access. When your project is small, you probably want to use direct attribute access to access a class member. For example, let's say you have an object foo of type Foo, which has a member num. Then you can simply get this member with num = foo.num. As your project grows, you may feel like there needs to be some checks or debugs on the simple attribute access. Then you can do that with a @property within the class. The data access interface remains the same so that there is no need to modify client code.

    Cited from PEP-8:

    For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.

  • Using @property for data access in Python is regarded as Pythonic:

    • It can strengthen your self-identification as a Python (not Java) programmer.

    • It can help your job interview if your interviewer thinks Java-style getters and setters are anti-patterns.

Advantages of traditional getters and setters

  • Traditional getters and setters allow for more complicated data access than simple attribute access. For example, when you are setting a class member, sometimes you need a flag indicating where you would like to force this operation even if something doesn't look perfect. While it is not obvious how to augment a direct member access like foo.num = num, You can easily augment your traditional setter with an additional force parameter:

    def Foo:
        def set_num(self, num, force=False):
            ...
    
  • Traditional getters and setters make it explicit that a class member access is through a method. This means:

    • What you get as the result may not be the same as what is exactly stored within that class.

    • Even if the access looks like a simple attribute access, the performance can vary greatly from that.

    Unless your class users expect a @property hiding behind every attribute access statement, making such things explicit can help minimize your class users surprises.

  • As mentioned by @NeilenMarais and in this post, extending traditional getters and setters in subclasses is easier than extending properties.

  • Traditional getters and setters have been widely used for a long time in different languages. If you have people from different backgrounds in your team, they look more familiar than @property. Also, as your project grows, if you may need to migrate from Python to another language that doesn't have @property, using traditional getters and setters would make the migration smoother.

Caveats

  • Neither @property nor traditional getters and setters makes the class member private, even if you use double underscore before its name:

    class Foo:
        def __init__(self):
            self.__num = 0
    
        @property
        def num(self):
            return self.__num
    
        @num.setter
        def num(self, num):
            self.__num = num
    
        def get_num(self):
            return self.__num
    
        def set_num(self, num):
            self.__num = num
    
    foo = Foo()
    print(foo.num)          # output: 0
    print(foo.get_num())    # output: 0
    print(foo._Foo__num)    # output: 0
    

How to check if a folder exists

import java.io.File;
import java.nio.file.Paths;

public class Test
{

  public static void main(String[] args)
  {

    File file = new File("C:\\Temp");
    System.out.println("File Folder Exist" + isFileDirectoryExists(file));
    System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));

  }

  public static boolean isFileDirectoryExists(File file)

  {
    if (file.exists())
    {
      return true;
    }
    return false;
  }

  public static boolean isDirectoryExists(String directoryPath)

  {
    if (!Paths.get(directoryPath).toFile().isDirectory())
    {
      return false;
    }
    return true;
  }

}

How to delete columns in numpy.array

From Numpy Documentation

np.delete(arr, obj, axis=None) Return a new array with sub-arrays along an axis deleted.

>>> arr
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1,  2,  3,  4],
       [ 9, 10, 11, 12]])

>>> np.delete(arr, np.s_[::2], 1)
array([[ 2,  4],
       [ 6,  8],
       [10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1,  3,  5,  7,  8,  9, 10, 11, 12])

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Print PDF directly from JavaScript

https://github.com/mozilla/pdf.js/

for a live demo http://mozilla.github.io/pdf.js/

it's probably what you want, but I can't see the point of this since modern browsers include such functionality, also it will run terribly slow on low-powered devices like mobile devices that, by the way, have their own optimized plugins and apps.

enabling cross-origin resource sharing on IIS7

Alsalaam Aleykum.

The first way is to follow the instructions in this link:

http://help.infragistics.com/Help/NetAdvantage/jQuery/2013.1/CLR4.0/html/igOlapXmlaDataSource_Configuring_IIS_for_Cross_Domain_OLAP_Data.html

Which corresponds to these configuration:

_x000D_
_x000D_
<handlers>_x000D_
  <clear />_x000D_
  <add name="OPTIONSVerbHandler" path="*" verb="OPTIONS" type="" modules="ProtocolSupportModule" scriptProcessor="" resourceType="Unspecified" requireAccess="Read" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />_x000D_
  <add name="xamlx-ISAPI-4.0_64bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="4194304" />_x000D_
  <add name="xamlx-ISAPI-4.0_32bit" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="4194304" />_x000D_
  <add name="xamlx-Integrated-4.0" path="*.xamlx" verb="GET,HEAD,POST,DEBUG" type="System.Xaml.Hosting.XamlHttpHandlerFactory, System.Xaml.Hosting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler" scriptProcessor=""_x000D_
  resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="rules-ISAPI-4.0_64bit" path="*.rules" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="rules-ISAPI-4.0_32bit" path="*.rules" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="rules-Integrated-4.0" path="*.rules" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="xoml-ISAPI-4.0_64bit" path="*.xoml" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="xoml-ISAPI-4.0_32bit" path="*.xoml" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="xoml-Integrated-4.0" path="*.xoml" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="svc-ISAPI-4.0_64bit" path="*.svc" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="svc-ISAPI-4.0_32bit" path="*.svc" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="svc-Integrated-4.0" path="*.svc" verb="*" type="System.ServiceModel.Activation.ServiceHttpHandlerFactory, System.ServiceModel.Activation, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler" scriptProcessor=""_x000D_
  resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="ISAPI-dll" path="*.dll" verb="*" type="" modules="IsapiModule" scriptProcessor="" resourceType="File" requireAccess="Execute" allowPathInfo="true" preCondition="" responseBufferLimit="4194304" />_x000D_
  <add name="AXD-ISAPI-4.0_64bit" path="*.axd" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="PageHandlerFactory-ISAPI-4.0_64bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="SimpleHandlerFactory-ISAPI-4.0_64bit" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="WebServiceHandlerFactory-ISAPI-4.0_64bit" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-rem-ISAPI-4.0_64bit" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-soap-ISAPI-4.0_64bit" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="aspq-ISAPI-4.0_64bit" path="*.aspq" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness64"_x000D_
  responseBufferLimit="0" />_x000D_
  <add name="cshtm-ISAPI-4.0_64bit" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="cshtml-ISAPI-4.0_64bit" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="vbhtm-ISAPI-4.0_64bit" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="vbhtml-ISAPI-4.0_64bit" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="TraceHandler-Integrated-4.0" path="trace.axd" verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TraceHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="WebAdminHandler-Integrated-4.0" path="WebAdmin.axd" verb="GET,DEBUG" type="System.Web.Handlers.WebAdminHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="AssemblyResourceLoader-Integrated-4.0" path="WebResource.axd" verb="GET,DEBUG" type="System.Web.Handlers.AssemblyResourceLoader" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="PageHandlerFactory-Integrated-4.0" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.PageHandlerFactory" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="SimpleHandlerFactory-Integrated-4.0" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="System.Web.UI.SimpleHandlerFactory" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="WebServiceHandlerFactory-Integrated-4.0" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="HttpRemotingHandlerFactory-rem-Integrated-4.0" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"_x000D_
  modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="HttpRemotingHandlerFactory-soap-Integrated-4.0" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="System.Runtime.Remoting.Channels.Http.HttpRemotingHandlerFactory, System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"_x000D_
  modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="aspq-Integrated-4.0" path="*.aspq" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="cshtm-Integrated-4.0" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="cshtml-Integrated-4.0" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="vbhtm-Integrated-4.0" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="vbhtml-Integrated-4.0" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" type="System.Web.HttpForbiddenHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0"_x000D_
  responseBufferLimit="4194304" />_x000D_
  <add name="ScriptHandlerFactoryAppServices-Integrated-4.0" path="*_AppService.axd" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="ScriptResourceIntegrated-4.0" path="*ScriptResource.axd" verb="GET,HEAD" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" modules="ManagedPipelineHandler"_x000D_
  scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="4194304" />_x000D_
  <add name="AXD-ISAPI-4.0_32bit" path="*.axd" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="PageHandlerFactory-ISAPI-4.0_32bit" path="*.aspx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="SimpleHandlerFactory-ISAPI-4.0_32bit" path="*.ashx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="WebServiceHandlerFactory-ISAPI-4.0_32bit" path="*.asmx" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-rem-ISAPI-4.0_32bit" path="*.rem" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="HttpRemotingHandlerFactory-soap-ISAPI-4.0_32bit" path="*.soap" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script"_x000D_
  allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="aspq-ISAPI-4.0_32bit" path="*.aspq" verb="*" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false" preCondition="classicMode,runtimeVersionv4.0,bitness32"_x000D_
  responseBufferLimit="0" />_x000D_
  <add name="cshtm-ISAPI-4.0_32bit" path="*.cshtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="cshtml-ISAPI-4.0_32bit" path="*.cshtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="vbhtm-ISAPI-4.0_32bit" path="*.vbhtm" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="vbhtml-ISAPI-4.0_32bit" path="*.vbhtml" verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="TRACEVerbHandler" path="*" verb="TRACE" type="" modules="ProtocolSupportModule" scriptProcessor="" resourceType="Unspecified" requireAccess="None" allowPathInfo="false" preCondition="" responseBufferLimit="4194304" />_x000D_
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />_x000D_
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG" type="" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />_x000D_
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" modules="ManagedPipelineHandler" scriptProcessor="" resourceType="Unspecified" requireAccess="Script" allowPathInfo="false"_x000D_
  preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />_x000D_
  <add name="StaticFile" path="*" verb="*" type="" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" scriptProcessor="" resourceType="Either" requireAccess="Read" allowPathInfo="false" preCondition="" responseBufferLimit="4194304"_x000D_
  />_x000D_
</handlers>
_x000D_
_x000D_
_x000D_

The second way is as to respond to the HTTP OPTIONS verb in your BeginRequest method.

  protected void Application_BeginRequest(object sender, EventArgs e)
{
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Request-Method", "GET ,POST, PUT, DELETE");

        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Origin,Content-Type, Accept");
        HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "86400"); // 24 hours
        HttpContext.Current.Response.End();
    }
}

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

I experienced this when I updated my JDK manually and removed the previous JDK

Red keywords

Solution

  • In the IntelliJ editor, click on the red keyword (Integer for example) and press ALT + ENTER (or click the light bulb icon)
  • select Setup JDK from the intentions menu

IntelliJ intentions menu

  • click on Configure

Project SDK selection dialog

  • In my case, the JDK path was incorrect (pointed on /opt/jdk1.7.0_51 instead of /opt/jdk1.7.0_65)

Broken Configure SDK dialog

  • Click on the ... and browse to the right JDK path

Fixed Configure SDK dialog

  • Let's clear the cache:

IntelliJ File menu

And everything should be back to life :)

No red keywords

Event binding on dynamically created elements?

You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.

Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
    </head>

    <body>
        <script src="http://code.jquery.com/jquery-latest.js"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>

        <input type="button" id="theButton" value="Click" />
        <script type="text/javascript">
            $(document).ready(function()
                {
                    $('.FOO').live("click", function (){alert("It Works!")});
                    var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
                                                                                                         autoOpen: false,
                                                                                                         tite: 'Basic Dialog'
                                                                                                     });
                    $('#theButton').click(function()
                    {
                        $dialog.dialog('open');
                        return('false');
                    });
                    $('#CUSTOM').click(function(){
                        //$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
                        var button = document.createElement("input");
                        button.setAttribute('class','FOO');
                        button.setAttribute('type','button');
                        button.setAttribute('value','CLICKMEE');
                        $('#container').append(button);
                    });
                    /* $('#FOO').click(function(){
                                                     alert("It Works!");
                                                 }); */
            });
        </script>
    </body>
</html>

Spring @Value is not resolving to value from property file

Have a read of pedjaradenkovic's comment.

Further to the link he provides, the reason this isn't working is that @Value processing requires a PropertySourcesPlaceholderConfigurer instead of a PropertyPlaceholderConfigurer.

How to merge a Series and DataFrame

If df is a pandas.DataFrame then df['new_col']= Series list_object of length len(df) will add the or Series list_object as a column named 'new_col'. df['new_col']= scalar (such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)

So a two-line code serves the purpose:

df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:    
    df[x] = s[x]

Output: 
   a  b  s1  s2
0  1  3   5   6
1  2  4   5   6

Add line break within tooltips

it is possible to add linebreaks within native HTML tooltips by simply having the title attribute spread over mutliple lines.

However, I'd recommend using a jQuery tooltip plugin such as Q-Tip: http://craigsworks.com/projects/qtip/.

It is simple to set up and use. Alternatively there are a lot of free javascript tooltip plugins around too.

edit: correction on first statement.

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

You only need to do this:

Intent myIntent = new Intent(MainActivity.this, nextActivity.class);

Node.js Web Application examples/tutorials

The Node Knockout competition wrapped up recently, and many of the submissions are available on github. The competition site doesn't appear to be working right now, but I'm sure you could Google up a few entries to check out.

Download a file from HTTPS using download.file()

Try following with heavy files

library(data.table)
URL <- "http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
x <- fread(URL)

Now() function with time trim

I would prefer to make a function that doesn't work with strings:

'---------------------------------------------------------------------------------------
' Procedure : RemoveTimeFromDate
' Author    : berend.nieuwhof
' Date      : 15-8-2013
' Purpose   : removes the time part of a String and returns the date as a date
'---------------------------------------------------------------------------------------
'
Public Function RemoveTimeFromDate(DateTime As Date) As Date


    Dim dblNumber As Double

    RemoveTimeFromDate = CDate(Floor(CDbl(DateTime)))

End Function

Private Function Floor(ByVal x As Double, Optional ByVal Factor As Double = 1) As Double
    Floor = Int(x / Factor) * Factor
End Function

How to get image width and height in OpenCV?

Also for openCV in python you can do:

img = cv2.imread('myImage.jpg')
height, width, channels = img.shape 

Selecting data from two different servers in SQL Server

SELECT
        *
FROM
        [SERVER2NAME].[THEDB].[THEOWNER].[THETABLE]

You can also look at using Linked Servers. Linked servers can be other types of data sources too such as DB2 platforms. This is one method for trying to access DB2 from a SQL Server TSQL or Sproc call...

HTML5 Email Validation

Using HTML 5,Just make the input email like :

_x000D_
_x000D_
<input type="email"/>
_x000D_
_x000D_
_x000D_

When the user hovers over the input box, they will a tooltip instructing them to enter a valid email. However, Bootstrap forms have a much better Tooltip message to tell the user to enter an email address and it pops up the moment the value entered does not match a valid email.

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

MySQL: determine which database is selected?

SELECT DATABASE();

p.s. I didn't want to take the liberty of modifying @cwallenpoole's answer to reflect the fact that this is a MySQL question and not an Oracle question and doesn't need DUAL.

How do I turn a C# object into a JSON string in .NET?

Use the DataContractJsonSerializer class: MSDN1, MSDN2.

My example: HERE.

It can also safely deserialize objects from a JSON string, unlike JavaScriptSerializer. But personally I still prefer Json.NET.

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Set min-width in HTML table's <td>

<table style="min-width:50px; max-width:150px;">
    <tr>
        <td style="min-width:50px">one</td>
        <td style="min-width:100px">two</td>
    </tr>
</table>

This works for me using an email script.

Is there a JavaScript / jQuery DOM change listener?

In addition to the "raw" tools provided by MutationObserver API, there exist "convenience" libraries to work with DOM mutations.

Consider: MutationObserver represents each DOM change in terms of subtrees. So if you're, for instance, waiting for a certain element to be inserted, it may be deep inside the children of mutations.mutation[i].addedNodes[j].

Another problem is when your own code, in reaction to mutations, changes DOM - you often want to filter it out.

A good convenience library that solves such problems is mutation-summary (disclaimer: I'm not the author, just a satisfied user), which enables you to specify queries of what you're interested in, and get exactly that.

Basic usage example from the docs:

var observer = new MutationSummary({
  callback: updateWidgets,
  queries: [{
    element: '[data-widget]'
  }]
});

function updateWidgets(summaries) {
  var widgetSummary = summaries[0];
  widgetSummary.added.forEach(buildNewWidget);
  widgetSummary.removed.forEach(cleanupExistingWidget);
}

T-SQL XOR Operator

Using boolean algebra, it is easy to show that:

A xor B = (not A and B) or (A and not B)


A B | f = notA and B | g = A and notB | f or g | A xor B    
----+----------------+----------------+--------+--------    
0 0 | 0              | 0              | 0      | 0    
0 1 | 1              | 0              | 1      | 1    
1 0 | 0              | 1              | 1      | 1    
1 1 | 0              | 0              | 0      | 0

No mapping found for HTTP request with URI Spring MVC

I have the same problem.... I change my project name and i have this problem...my solution was the checking project refences and use / in my web.xml (instead of /*)

Accessing Object Memory Address

You can get something suitable for that purpose with:

id(self)

How to store arbitrary data for some HTML tags

Just another way, I personally wouldn't use this but it works (assure your JSON is valid because eval() is dangerous).

<a class="article" href="link/for/non-js-users.html">
    <span style="display: none;">{"id": 1, "title":"Something"}</span>
    Text of Link
</a>

// javascript
var article = document.getElementsByClassName("article")[0];
var data = eval(article.childNodes[0].innerHTML);

Extract matrix column values by matrix column name

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

Sql Query to list all views in an SQL Server 2005 database

This is old, but I thought I'd put this out anyway since I couldn't find a query that would give me ALL the SQL code from EVERY view I had out there. So here it is:

  SELECT SM.definition
  FROM sys.sql_modules SM
  INNER JOIN sys.Objects SO ON SM.Object_id = SO.Object_id
  WHERE SO.type = 'v'

Call to undefined function curl_init().?

You have to enable curl with php.

Here is the instructions for same

How to count the occurrence of certain item in an ndarray?

take advantage of the methods offered by a Series:

>>> import pandas as pd
>>> y = [0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1]
>>> pd.Series(y).value_counts()
0    8
1    4
dtype: int64

How do I change the default location for Git Bash on Windows?

Add "cd your_repos_path" to your Git profile, which is under the %.

Passing variables through handlebars partial

Sounds like you want to do something like this:

{{> person {another: 'attribute'} }}

Yehuda already gave you a way of doing that:

{{> person this}}

But to clarify:

To give your partial its own data, just give it its own model inside the existing model, like so:

{{> person this.childContext}}

In other words, if this is the model you're giving to your template:

var model = {
    some : 'attribute'
}

Then add a new object to be given to the partial:

var model = {
    some : 'attribute',
    childContext : {
        'another' : 'attribute' // this goes to the child partial
    }
}

childContext becomes the context of the partial like Yehuda said -- in that, it only sees the field another, but it doesn't see (or care about the field some). If you had id in the top level model, and repeat id again in the childContext, that'll work just fine as the partial only sees what's inside childContext.

Handling warning for possible multiple enumeration of IEnumerable

I usually overload my method with IEnumerable and IList in this situation.

public static IEnumerable<T> Method<T>( this IList<T> source ){... }

public static IEnumerable<T> Method<T>( this IEnumerable<T> source )
{
    /*input checks on source parameter here*/
    return Method( source.ToList() );
}

I take care to explain in the summary comments of the methods that calling IEnumerable will perform a .ToList().

The programmer can choose to .ToList() at a higher level if multiple operations are being concatenated and then call the IList overload or let my IEnumerable overload take care of that.

How to read a file byte by byte in Python and how to print a bytelist as a binary?

Late to the party, but this may help anyone looking for a quick solution:

you can use bin(ord('b')).replace('b', '')bin() it gives you the binary representation with a 'b' after the last bit, you have to remove it. Also ord() gives you the ASCII number to the char or 8-bit/1 Byte coded character.

Cheers

Is it possible to select the last n items with nth-child?

This will select the last two iems of a list:

_x000D_
_x000D_
li:nth-last-child(-n+2) {color:red;}
_x000D_
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>
_x000D_
_x000D_
_x000D_

Java: get greatest common divisor

The % going to give us the gcd Between two numbers, it means:- % or mod of big_number/small_number are =gcd, and we write it on java like this big_number % small_number.

EX1: for two integers

  public static int gcd(int x1,int x2)
    {
        if(x1>x2)
        {
           if(x2!=0)
           {
               if(x1%x2==0)     
                   return x2;
                   return x1%x2;
                   }
           return x1;
           }
          else if(x1!=0)
          {
              if(x2%x1==0)
                  return x1;
                  return x2%x1;
                  }
        return x2;
        } 

EX2: for three integers

public static int gcd(int x1,int x2,int x3)
{

    int m,t;
    if(x1>x2)
        t=x1;
    t=x2;
    if(t>x3)
        m=t;
    m=x3;
    for(int i=m;i>=1;i--)
    {
        if(x1%i==0 && x2%i==0 && x3%i==0)
        {
            return i;
        }
    }
    return 1;
}

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

Get index of a key in json

Its too late, but it may be simple and useful

var json = { "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" };
var keytoFind = "key2";
var index = Object.keys(json).indexOf(keytoFind);
alert(index);

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I had this problem and found that removing the following folder helped, even with the non-Express edition.Express:

C:\Users\<user>\Documents\IISExpress

How to start anonymous thread class

Since anonymous classes extend the given class you can store them in a variable.

eg.

Thread t = new Thread()
{
    public void run() {
        System.out.println("blah");
    }
};
t.start();

Alternatively, you can just call the start method on the object you have immediately created.

new Thread()
{
    public void run() {
        System.out.println("blah");
    }
}.start();
// similar to new Thread().start();

Though personally, I would always advise creating an anonymous instance of Runnable rather than Thread as the compiler will warn you if you accidentally get the method signature wrong (for an anonymous class it will warn you anyway I think, as anonymous classes can't define new non-private methods).

eg

new Thread(new Runnable()
{
    @Override
    public void run() {
        System.out.println("blah");
    }
}).start();

Retrieving the text of the selected <option> in <select> element

If you found this thread and wanted to know how to get the selected option text via event here is sample code:

alert(event.target.options[event.target.selectedIndex].text);

CORS with POSTMAN

As @Musa comments it, it seems that the reason is that:

Postman doesn't care about SOP, it's a dev tool not a browser

By the way here's a chrome extension in order to make it work on your browser (this one is for chrome, but you can find either for FF or Safari).

Check here if you want to learn more about Cross-Origin and why it's working for extensions.

Remove all special characters, punctuation and spaces from string

The most generic approach is using the 'categories' of the unicodedata table which classifies every single character. E.g. the following code filters only printable characters based on their category:

import unicodedata
# strip of crap characters (based on the Unicode database
# categorization:
# http://www.sql-und-xml.de/unicode-database/#kategorien

PRINTABLE = set(('Lu', 'Ll', 'Nd', 'Zs'))

def filter_non_printable(s):
    result = []
    ws_last = False
    for c in s:
        c = unicodedata.category(c) in PRINTABLE and c or u'#'
        result.append(c)
    return u''.join(result).replace(u'#', u' ')

Look at the given URL above for all related categories. You also can of course filter by the punctuation categories.

Responsive iframe using Bootstrap

Working during August 2020

use this

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

use one aspect ratio

<div class="embed-responsive embed-responsive-4by3">
  <iframe class="embed-responsive-item" src="…"></iframe>
</div>

within iframe use options

 <iframe class="embed-responsive-item" src="..."
  frameborder="0"
    style="
      overflow: hidden;
      overflow-x: hidden;
      overflow-y: hidden;
      height: 100%;
      width: 100%;
      position: absolute;
      top: 0px;
      left: 0px;
      right: 0px;
      bottom: 0px;
    "
    height="100%"
    width="100%"
  ></iframe>

How to pause a YouTube player when hiding the iframe?

Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my html:

<div class="flexslider" style="height: 330px;">
  <ul class="slides">
    <li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
    <li class="post-65><img  src="http://localhost/..../banner_image_2.jpg "></li>
    <li class="post-67 ">
        <div class="fluid-width-video-wrapper ">
            <iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
        </div>
    </li>
  </ul>
</div>

Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.

Following is my JS file:

jQuery(document).ready(function($){
    jQuery(".flexslider").click(function (e) {
        setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated

    });
});

function checkiframe(){
    var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
    console.log(iframe_flag);
    var tooglePlay=0;
    if (iframe_flag) {                                //If Visible then AutoPlaying the Video
        tooglePlay=1;
        setTimeout(toogleVideo, 1000);                //Also using timeout here
    }
    if (!iframe_flag) {     
        tooglePlay =0;
        setTimeout(toogleVideo('hide'), 1000);  
    }   
}

function toogleVideo(state) {
    var div = document.getElementsByTagName("iframe")[0].contentWindow;
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}; 

Also, as a simpler example, check this out on JSFiddle

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

How to validate a form with multiple checkboxes to have atleast one checked

  $('#subscribeForm').validate( {
      rules: {
          list: {
              required: true,
              minlength: 1
          }
       }
   });

I think this will make sure at least one is checked.

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

Split string based on a regular expression

By using (,), you are capturing the group, if you simply remove them you will not have this problem.

>>> str1 = "a    b     c      d"
>>> re.split(" +", str1)
['a', 'b', 'c', 'd']

However there is no need for regex, str.split without any delimiter specified will split this by whitespace for you. This would be the best way in this case.

>>> str1.split()
['a', 'b', 'c', 'd']

If you really wanted regex you can use this ('\s' represents whitespace and it's clearer):

>>> re.split("\s+", str1)
['a', 'b', 'c', 'd']

or you can find all non-whitespace characters

>>> re.findall(r'\S+',str1)
['a', 'b', 'c', 'd']

What is CDATA in HTML?

All text in an XML document will be parsed by the parser.

But text inside a CDATA section will be ignored by the parser.

CDATA - (Unparsed) Character Data

The term CDATA is used about text data that should not be parsed by the XML parser.

Characters like "<" and "&" are illegal in XML elements.

"<" will generate an error because the parser interprets it as the start of a new element.

"&" will generate an error because the parser interprets it as the start of an character entity.

Some text, like JavaScript code, contains a lot of "<" or "&" characters. To avoid errors script code can be defined as CDATA.

Everything inside a CDATA section is ignored by the parser.

A CDATA section starts with "<![CDATA[" and ends with "]]>"

Use of CDATA in program output

CDATA sections in XHTML documents are liable to be parsed differently by web browsers if they render the document as HTML, since HTML parsers do not recognise the CDATA start and end markers, nor do they recognise HTML entity references such as &lt; within <script> tags. This can cause rendering problems in web browsers and can lead to cross-site scripting vulnerabilities if used to display data from untrusted sources, since the two kinds of parsers will disagree on where the CDATA section ends.

A brief SGML tutorial.

Also, see the Wikipedia entry on CDATA.

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

How do I create a message box with "Yes", "No" choices and a DialogResult?

The MessageBox does produce a DialogResults

DialogResult r = MessageBox.Show("Some question here");

You can also specify the buttons easily enough. More documentation can be found at http://msdn.microsoft.com/en-us/library/ba2a6d06.aspx

Detect and exclude outliers in Pandas data frame

For each of your dataframe column, you could get quantile with:

q = df["col"].quantile(0.99)

and then filter with:

df[df["col"] < q]

If one need to remove lower and upper outliers, combine condition with an AND statement:

q_low = df["col"].quantile(0.01)
q_hi  = df["col"].quantile(0.99)

df_filtered = df[(df["col"] < q_hi) & (df["col"] > q_low)]

How to pip install a package with min and max version range?

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.

Could not resolve all dependencies for configuration ':classpath'

late but it worked for me:
change your dns setting by going Network and sharing center.
In left pane choose change adapter setting
-right click on your network connection
-properties
-select ipv4
-properties
- now in dns server setting:-
-choose the option use the following dns server addresses
and use google dns server 8.8.8.8 as preferred dns server and 8.8.4.4 as alternate dns server.

it will solve your problem.

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))

MySQL convert date string to Unix timestamp

Here's an example of how to convert DATETIME to UNIX timestamp:
SELECT UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p'))

Here's an example of how to change date format:
SELECT FROM_UNIXTIME(UNIX_TIMESTAMP(STR_TO_DATE('Apr 15 2012 12:00AM', '%M %d %Y %h:%i%p')),'%m-%d-%Y %h:%i:%p')

Documentation: UNIX_TIMESTAMP, FROM_UNIXTIME

Conditionally formatting cells if their value equals any value of another column

I unable to comment on the top answer, but Excel actually lets you do this without adding the ugly conditional logic.

Conditional formatting is automatically applied to any input that isn't an error, so you can achieve the same effect as:

=NOT(ISERROR(MATCH(A1,$B$1:$B$1000,0)))

With this:

= MATCH(A1,$B$1:$B$1000,0)))

If the above is applied to your data, A1 will be formatted if it matches any cell in $B$1:$B$1000, as any non-match will return an error.

What does mscorlib stand for?

It stands for

Microsoft's Common Object Runtime Library

and it is the primary assembly for the Framework Common Library.

It contains the following namespaces:

 System
 System.Collections
 System.Configuration.Assemblies
 System.Diagnostics
 System.Diagnostics.SymbolStore
 System.Globalization
 System.IO
 System.IO.IsolatedStorage
 System.Reflection
 System.Reflection.Emit
 System.Resources
 System.Runtime.CompilerServices
 System.Runtime.InteropServices
 System.Runtime.InteropServices.Expando
 System.Runtime.Remoting
 System.Runtime.Remoting.Activation
 System.Runtime.Remoting.Channels
 System.Runtime.Remoting.Contexts
 System.Runtime.Remoting.Lifetime
 System.Runtime.Remoting.Messaging
 System.Runtime.Remoting.Metadata
 System.Runtime.Remoting.Metadata.W3cXsd2001
 System.Runtime.Remoting.Proxies
 System.Runtime.Remoting.Services
 System.Runtime.Serialization
 System.Runtime.Serialization.Formatters
 System.Runtime.Serialization.Formatters.Binary
 System.Security
 System.Security.Cryptography
 System.Security.Cryptography.X509Certificates
 System.Security.Permissions
 System.Security.Policy
 System.Security.Principal
 System.Text
 System.Threading
 Microsoft.Win32 

Interesting info about MSCorlib:

  • The .NET 2.0 assembly will reference and use the 2.0 mscorlib.The .NET 1.1 assembly will reference the 1.1 mscorlib but will use the 2.0 mscorlib at runtime (due to hard-coded version redirects in theruntime itself)
  • In GAC there is only one version of mscorlib, you dont find 1.1 version on GAC even if you have 1.1 framework installed on your machine. It would be good if somebody can explain why MSCorlib 2.0 alone is in GAC whereas 1.x version live inside framework folder
  • Is it possible to force a different runtime to be loaded by the application by making a config setting in your app / web.config? you won’t be able to choose the CLR version by settings in the ConfigurationFile – at that point, a CLR will already be running, and there can only be one per process. Immediately after the CLR is chosen the MSCorlib appropriate for that CLR is loaded.

Adding HTML entities using CSS content

In CSS you need to use a Unicode escape sequence in place of HTML Entities. This is based on the hexadecimal value of a character.

I found that the easiest way to convert symbol to their hexadecimal equivalent is, such as from ▾ (&#9662;) to \25BE is to use the Microsoft calculator =)

Yes. Enable programmers mode, turn on the decimal system, enter 9662, then switch to hex and you'll get 25BE. Then just add a backslash \ to the beginning.

The requested operation cannot be performed on a file with a user-mapped section open

The solution for me was to close out of all instances of VS and to kill any hanging devenv.exe processes.

how to get multiple checkbox value using jquery

try this one.. (guys I am a new bee.. so if I wrong then I am really sorry. But I found a solution by this way.)

var suggestion = [];
$('#health_condition_name:checked').each(function (j, ob) {

    var odata = {
        health_condition_name: $(ob).val()
    };

    health.push(odata);
});

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Why Response.Redirect causes System.Threading.ThreadAbortException?

There is no simple and elegant solution to the Redirect problem in ASP.Net WebForms. You can choose between the Dirty solution and the Tedious solution

Dirty: Response.Redirect(url) sends a redirect to the browser, and then throws a ThreadAbortedException to terminate the current thread. So no code is executed past the Redirect()-call. Downsides: It is bad practice and have performance implications to kill threads like this. Also, ThreadAbortedExceptions will show up in exception logging.

Tedious: The recommended way is to call Response.Redirect(url, false) and then Context.ApplicationInstance.CompleteRequest() However, code execution will continue and the rest of the event handlers in the page lifecycle will still be executed. (E.g. if you perform the redirect in Page_Load, not only will the rest of the handler be executed, Page_PreRender and so on will also still be called - the rendered page will just not be sent to the browser. You can avoid the extra processing by e.g. setting a flag on the page, and then let subsequent event handlers check this flag before before doing any processing.

(The documentation to CompleteRequest states that it "Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution". This can easily be misunderstood. It does bypass further HTTP filters and modules, but it doesn't bypass further events in the current page lifecycle.)

The deeper problem is that WebForms lacks a level of abstraction. When you are in a event handler, you are already in the process of building a page to output. Redirecting in an event handler is ugly because you are terminating a partially generated page in order to generate a different page. MVC does not have this problem since the control flow is separate from rendering views, so you can do a clean redirect by simply returning a RedirectAction in the controller, without generating a view.

pandas: find percentile stats of a given column

assume series s

s = pd.Series(np.arange(100))

Get quantiles for [.1, .2, .3, .4, .5, .6, .7, .8, .9]

s.quantile(np.linspace(.1, 1, 9, 0))

0.1     9.9
0.2    19.8
0.3    29.7
0.4    39.6
0.5    49.5
0.6    59.4
0.7    69.3
0.8    79.2
0.9    89.1
dtype: float64

OR

s.quantile(np.linspace(.1, 1, 9, 0), 'lower')

0.1     9
0.2    19
0.3    29
0.4    39
0.5    49
0.6    59
0.7    69
0.8    79
0.9    89
dtype: int32

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

How to load all modules in a folder?

Update in 2017: you probably want to use importlib instead.

Make the Foo directory a package by adding an __init__.py. In that __init__.py add:

import bar
import eggs
import spam

Since you want it dynamic (which may or may not be a good idea), list all py-files with list dir and import them with something like this:

import os
for module in os.listdir(os.path.dirname(__file__)):
    if module == '__init__.py' or module[-3:] != '.py':
        continue
    __import__(module[:-3], locals(), globals())
del module

Then, from your code do this:

import Foo

You can now access the modules with

Foo.bar
Foo.eggs
Foo.spam

etc. from Foo import * is not a good idea for several reasons, including name clashes and making it hard to analyze the code.

require_once :failed to open stream: no such file or directory

set_include_path(get_include_path() . $_SERVER["DOCUMENT_ROOT"] . "/mysite/php/includes/");

Also this can help.See set_include_path()

Downloading video from YouTube

Gonna give another answer, since the libraries mentioned haven't been actively developed anymore.

Consider using YoutubeExplode. It has a very rich and consistent API and allows you to do a lot of other things with youtube videos beside downloading them.

How do you serialize a model instance in Django?

This is a project that it can serialize(JSON base now) all data in your model and put them to a specific directory automatically and then it can deserialize it whenever you want... I've personally serialized thousand records with this script and then load all of them back to another database without any losing data.

Anyone that would be interested in opensource projects can contribute this project and add more feature to it.

serializer_deserializer_model

Check if a class is derived from a generic class

It might be overkill but I use extension methods like the following. They check interfaces as well as subclasses. It can also return the type that has the specified generic definition.

E.g. for the example in the question it can test against generic interface as well as generic class. The returned type can be used with GetGenericArguments to determine that the generic argument type is "SomeType".

/// <summary>
/// Checks whether this type has the specified definition in its ancestry.
/// </summary>   
public static bool HasGenericDefinition(this Type type, Type definition)
{
    return GetTypeWithGenericDefinition(type, definition) != null;
}

/// <summary>
/// Returns the actual type implementing the specified definition from the
/// ancestry of the type, if available. Else, null.
/// </summary>
public static Type GetTypeWithGenericDefinition(this Type type, Type definition)
{
    if (type == null)
        throw new ArgumentNullException("type");
    if (definition == null)
        throw new ArgumentNullException("definition");
    if (!definition.IsGenericTypeDefinition)
        throw new ArgumentException(
            "The definition needs to be a GenericTypeDefinition", "definition");

    if (definition.IsInterface)
        foreach (var interfaceType in type.GetInterfaces())
            if (interfaceType.IsGenericType
                && interfaceType.GetGenericTypeDefinition() == definition)
                return interfaceType;

    for (Type t = type; t != null; t = t.BaseType)
        if (t.IsGenericType && t.GetGenericTypeDefinition() == definition)
            return t;

    return null;
}

How to program a fractal?

If complex numbers give you a headache, there is a broad range of fractals that can be formulated using an L-system. This requires a couple of layers interacting, but each is interesting in it own right.

First you need a turtle. Forward, Back, Left, Right, Pen-up, Pen-down. There are lots of fun shapes to be made with turtle graphics using turtle geometry even without an L-system driving it. Search for "LOGO graphics" or "Turtle graphics". A full LOGO system is in fact a Lisp programming environment using an unparenthesized Cambridge Polish syntax. But you don't have to go nearly that far to get some pretty pictures using the turtle concept.

Then you need a layer to execute an L-system. L-systems are related to Post-systems and Semi-Thue systems, and like virii, they straddle the border of Turing Completeness. The concept is string-rewriting. It can be implemented as a macro-expansion or a procedure set with extra controls to bound the recursion. If using macro-expansion (as in the example below), you will still need a procedure set to map symbols to turtle commands and a procedure to iterate through the string or array to run the encoded turtle program. For a bounded-recursion procedure set (eg.), you embed the turtle commands in the procedures and either add recursion-level checks to each procedure or factor it out to a handler function.

Here's an example of a Pythagoras' Tree in postscript using macro-expansion and a very abbreviated set of turtle commands. For some examples in python and mathematica, see my code golf challenge.

ps l-system pythagoras tree luser-droog

How to display an activity indicator with text on iOS 8 with Swift?

While Esq's answer works, I've added my own implementation which is more in line with good component architecture by separating the view into it's own class. It also uses dynamic blurring introduced in iOS 8.

Here is how mine looks with an image background:

enter image description here

The code for this is encapsulated in it's own UIView class which means you can reuse it whenever you desire.

Updated for Swift 3

Usage

func viewDidLoad() {
  super.viewDidLoad()

  // Create and add the view to the screen.
  let progressHUD = ProgressHUD(text: "Saving Photo")
  self.view.addSubview(progressHUD)
  // All done!

  self.view.backgroundColor = UIColor.black
}

UIView Code

import UIKit

class ProgressHUD: UIVisualEffectView {

  var text: String? {
    didSet {
      label.text = text
    }
  }

  let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
  let label: UILabel = UILabel()
  let blurEffect = UIBlurEffect(style: .light)
  let vibrancyView: UIVisualEffectView

  init(text: String) {
    self.text = text
    self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
    super.init(effect: blurEffect)
    self.setup()
  }

  required init?(coder aDecoder: NSCoder) {
    self.text = ""
    self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect))
    super.init(coder: aDecoder)
    self.setup()
  }

  func setup() {
    contentView.addSubview(vibrancyView)
    contentView.addSubview(activityIndictor)
    contentView.addSubview(label)
    activityIndictor.startAnimating()
  }

  override func didMoveToSuperview() {
    super.didMoveToSuperview()

    if let superview = self.superview {

      let width = superview.frame.size.width / 2.3
      let height: CGFloat = 50.0
      self.frame = CGRect(x: superview.frame.size.width / 2 - width / 2,
                      y: superview.frame.height / 2 - height / 2,
                      width: width,
                      height: height)
      vibrancyView.frame = self.bounds

      let activityIndicatorSize: CGFloat = 40
      activityIndictor.frame = CGRect(x: 5,
                                      y: height / 2 - activityIndicatorSize / 2,
                                      width: activityIndicatorSize,
                                      height: activityIndicatorSize)

      layer.cornerRadius = 8.0
      layer.masksToBounds = true
      label.text = text
      label.textAlignment = NSTextAlignment.center
      label.frame = CGRect(x: activityIndicatorSize + 5,
                           y: 0,
                           width: width - activityIndicatorSize - 15,
                           height: height)
      label.textColor = UIColor.gray
      label.font = UIFont.boldSystemFont(ofSize: 16)
    }
  }

  func show() {
    self.isHidden = false
  }

  func hide() {
    self.isHidden = true
  }
}

Swift 2

An example on how to use it is like this:

override func viewDidLoad() {
    super.viewDidLoad()

    // Create and add the view to the screen.
    let progressHUD = ProgressHUD(text: "Saving Photo")
    self.view.addSubview(progressHUD)
    // All done!

    self.view.backgroundColor = UIColor.blackColor()
}

Here is the UIView code:

import UIKit

class ProgressHUD: UIVisualEffectView {

    var text: String? {
        didSet {
            label.text = text
        }
    }
    let activityIndictor: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
    let label: UILabel = UILabel()
    let blurEffect = UIBlurEffect(style: .Light)
    let vibrancyView: UIVisualEffectView

    init(text: String) {
        self.text = text
        self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
        super.init(effect: blurEffect)
        self.setup()
    }

    required init(coder aDecoder: NSCoder) {
        self.text = ""
        self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
        super.init(coder: aDecoder)
        self.setup()

    }

    func setup() {
        contentView.addSubview(vibrancyView)
        vibrancyView.contentView.addSubview(activityIndictor)
        vibrancyView.contentView.addSubview(label)
        activityIndictor.startAnimating()
    }

    override func didMoveToSuperview() {
        super.didMoveToSuperview()

        if let superview = self.superview {

            let width = superview.frame.size.width / 2.3
            let height: CGFloat = 50.0
            self.frame = CGRectMake(superview.frame.size.width / 2 - width / 2,
                superview.frame.height / 2 - height / 2,
                width,
                height)
            vibrancyView.frame = self.bounds

            let activityIndicatorSize: CGFloat = 40
            activityIndictor.frame = CGRectMake(5, height / 2 - activityIndicatorSize / 2,
                activityIndicatorSize,
                activityIndicatorSize)

            layer.cornerRadius = 8.0
            layer.masksToBounds = true
            label.text = text
            label.textAlignment = NSTextAlignment.Center
            label.frame = CGRectMake(activityIndicatorSize + 5, 0, width - activityIndicatorSize - 15, height)
            label.textColor = UIColor.grayColor()
            label.font = UIFont.boldSystemFontOfSize(16)
        }
    }

    func show() {
        self.hidden = false
    }

    func hide() {
        self.hidden = true
    }
}

I hope this helps, please feel free to use this code wherever you need.

Regular expression include and exclude special characters

You haven't actually asked a question, but assuming you have one, this could be your answer...

Assuming all characters, except the "Special Characters" are allowed you can write

String regex = "^[^<>'\"/;`%]*$";

How to quickly clear a JavaScript Object?

The short answer to your question, I think, is no (you can just create a new object).

  1. In this example, I believe setting the length to 0 still leaves all of the elements for garbage collection.

  2. You could add this to Object.prototype if it's something you'd frequently use. Yes it's linear in complexity, but anything that doesn't do garbage collection later will be.

  3. This is the best solution. I know it's not related to your question - but for how long do we need to continue supporting IE6? There are many campaigns to discontinue the usage of it.

Feel free to correct me if there's anything incorrect above.

How to convert int to Integer

i it integer, int to Integer

Integer intObj = new Integer(i);

add to collection

list.add(String.valueOf(intObj));

Xcode project not showing list of simulators

Try This, It worked like a charm! for me,

Follow below step

1) Clean Derived Data as show below,

 rm -rf ~/Library/Developer/Xcode/DerivedData/

OR

 Xcode---> Preferences--->Location--->Derived Data

Derived Data

2) In Deployment Info change Deployment Target

It's equal to or less then the SDK version of Xcode

enter image description here

3) Quit Xcode

enter image description here

4) Reopen Xcode you will see list of simulators

enter image description here

Hope this answer will help for someone.

How to select an item from a dropdown list using Selenium WebDriver with java?

public class checkBoxSel {

    public static void main(String[] args) {

         WebDriver driver = new FirefoxDriver();
         EventFiringWebDriver dr = null ;


         dr = new EventFiringWebDriver(driver);
         dr.get("http://www.google.co.in/");

         dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

         dr.findElement(By.linkText("Gmail")).click() ;

         Select sel = new Select(driver.findElement(By.tagName("select")));
         sel.selectByValue("fil");

    }

}

I am using GOOGLE LOGIN PAGE to test the seletion option. The above example was to find and select language "Filipino" from the drop down list. I am sure this will solve the problem.

How to fix java.net.SocketException: Broken pipe?

I noticed I was using the incorrect HTTP request url while making it, later which i changed that it resolved my problem. my upload url was : http://192.168.0.31:5000/uploader while i was using http://192.168.0.31:5000. that was a get call. and got a java.net.SocketException: Broken pipe? exception.

That was my reason. might lead you to check one more point when this issue

  public void postRequest()  {


        Security.insertProviderAt(Conscrypt.newProvider(), 1);

        System.out.println("mediafilename-->>" + mediaFileName);
        String[] dirarray = mediaFileName.split("/");
        String file_name = dirarray[6];
        //Thread.sleep(10000);

        RequestBody requestBody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("file",file_name, RequestBody.create(MediaType.parse("video/mp4"), new File(mediaFileName))).build();
        OkHttpClient okHttpClient = new OkHttpClient();
//        ExecutorService executor = newFixedThreadPool(20);
//        Request request = new Request.Builder().post(requestBody).url("https://192.168.0.31:5000/uploader").build();
        Request request = new Request.Builder().url("http://192.168.0.31:5000/uploader").post(requestBody).build();
//        Request request = new Request.Builder().url("http://192.168.0.31:5000").build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

//

                call.cancel();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),"Something went wrong:" + " ", Toast.LENGTH_SHORT).show();

                    }
                });
                e.printStackTrace();

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        try {
                            System.out.println(response.body().string());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });


                System.out.println("Response ; " + response.body().toString());
//                Toast.makeText(getApplicationContext(), response.body().toString(),Toast.LENGTH_LONG).show();
                System.out.println(response);

            }
        });

How to solve npm error "npm ERR! code ELIFECYCLE"

Cleaning Cache and Node_module are not enough. Follow this steps:

  • npm cache clean --force
  • delete node_modules folder
  • delete package-lock.json file
  • npm install

It works for me like this.

Multiple models in a view

I want to say that my solution was like the answer provided on this stackoverflow page: ASP.NET MVC 4, multiple models in one view?

However, in my case, the linq query they used in their Controller did not work for me.

This is said query:

var viewModels = 
        (from e in db.Engineers
         select new MyViewModel
         {
             Engineer = e,
             Elements = e.Elements,
         })
        .ToList();

Consequently, "in your view just specify that you're using a collection of view models" did not work for me either.

However, a slight variation on that solution did work for me. Here is my solution in case this helps anyone.

Here is my view model in which I know I will have just one team but that team may have multiple boards (and I have a ViewModels folder within my Models folder btw, hence the namespace):

namespace TaskBoard.Models.ViewModels
{
    public class TeamBoards
    {
        public Team Team { get; set; }
        public List<Board> Boards { get; set; }
    }
}

Now this is my controller. This is the most significant difference from the solution in the link referenced above. I build out the ViewModel to send to the view differently.

public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            TeamBoards teamBoards = new TeamBoards();
            teamBoards.Boards = (from b in db.Boards
                                 where b.TeamId == id
                                 select b).ToList();
            teamBoards.Team = (from t in db.Teams
                               where t.TeamId == id
                               select t).FirstOrDefault();

            if (teamBoards == null)
            {
                return HttpNotFound();
            }
            return View(teamBoards);
        }

Then in my view I do not specify it as a list. I just do "@model TaskBoard.Models.ViewModels.TeamBoards" Then I only need a for each when I iterate over the Team's boards. Here is my view:

@model TaskBoard.Models.ViewModels.TeamBoards

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Team</h4>
    <hr />


    @Html.ActionLink("Create New Board", "Create", "Board", new { TeamId = @Model.Team.TeamId}, null)
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => Model.Team.Name)
        </dt>

        <dd>
            @Html.DisplayFor(model => Model.Team.Name)
            <ul>
                @foreach(var board in Model.Boards)
                { 
                    <li>@Html.DisplayFor(model => board.BoardName)</li>
                }
            </ul>
        </dd>

    </dl>
</div>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Team.TeamId }) |
    @Html.ActionLink("Back to List", "Index")
</p>

I am fairly new to ASP.NET MVC so it took me a little while to figure this out. So, I hope this post helps someone figure it out for their project in a shorter timeframe. :-)

Calling a parent window function from an iframe

Another addition for those who need it. Ash Clarke's solution does not work if they are using different protocols so be sure that if you are using SSL, your iframe is using SSL as well or it will break the function. His solution did work for the domains itself though, so thanks for that.

How to find pg_config path

Have same issue on mac, you probably need to

brew install postgresql

then you can run

pip install psycopg2

The brew will fix PATH issue for you

this solution works for me at least.

Passing variables in remote ssh command

(This answer might seem needlessly complicated, but it’s easily extensible and robust regarding whitespace and special characters, as far as I know.)

You can feed data right through the standard input of the ssh command and read that from the remote location.

In the following example,

  1. an indexed array is filled (for convenience) with the names of the variables whose values you want to retrieve on the remote side.
  2. For each of those variables, we give to ssh a null-terminated line giving the name and value of the variable.
  3. In the shh command itself, we loop through these lines to initialise the required variables.
# Initialize examples of variables.
# The first one even contains whitespace and a newline.
readonly FOO=$'apjlljs ailsi \n ajlls\t éjij'
readonly BAR=ygnàgyààynygbjrbjrb

# Make a list of what you want to pass through SSH.
# (The “unset” is just in case someone exported
# an associative array with this name.)
unset -v VAR_NAMES
readonly VAR_NAMES=(
    FOO
    BAR
)

for name in "${VAR_NAMES[@]}"
do
    printf '%s %s\0' "$name" "${!name}"
done | ssh [email protected] '
    while read -rd '"''"' name value
    do
        export "$name"="$value"
    done

    # Check
    printf "FOO = [%q]; BAR = [%q]\n" "$FOO" "$BAR"
'

Output:

FOO = [$'apjlljs ailsi \n ajlls\t éjij']; BAR = [ygnàgyààynygbjrbjrb]

If you don’t need to export those, you should be able to use declare instead of export.

A really simplified version (if you don’t need the extensibility, have a single variable to process, etc.) would look like:

$ ssh [email protected] 'read foo' <<< "$foo"

How to capitalize the first letter of word in a string using Java?

Its simple only one line code is needed for this. if String A = scanner.nextLine(); then you need to write this to display the string with this first letter capitalized.

System.out.println(A.substring(0, 1).toUpperCase() + A.substring(1));

And its done now.

SVN - Checksum mismatch while updating

I had a similar error and fixed as follows:

(My 'fix' is based on an assumption which may or may not be correct as I don't know that much about how subversion works internally, but it definitely worked for me)

I am assuming that .svn\text-base\import.php.svn-base is expected to match the latest commit.

When I checked the file I was having the error on , the base file did NOT match the latest commit in the repository.

I copied the text from the latest commit and saved that in the .svn folder, replacing the incorrect file (made a backup copy in case my assumptions were wrong). (file was marked read only, I cleared that flag, overwrote and set it back to read only)

I was then able to commit successfully.

How to get the first element of an array?

Using ES6 destructuring

let [first] = [1,2,3];

Which is the same as

let first = [1,2,3][0];

JavaScript get window X/Y position for scroll

Maybe more simple;

var top  = window.pageYOffset || document.documentElement.scrollTop,
    left = window.pageXOffset || document.documentElement.scrollLeft;

Credits: so.dom.js#L492

Convert a SQL query result table to an HTML table for email

I made a dynamic proc which turns any random query into an HTML table, so you don't have to hardcode columns like in the other responses.

-- Description: Turns a query into a formatted HTML table. Useful for emails. 
-- Any ORDER BY clause needs to be passed in the separate ORDER BY parameter.
-- =============================================
CREATE PROC [dbo].[spQueryToHtmlTable] 
(
  @query nvarchar(MAX), --A query to turn into HTML format. It should not include an ORDER BY clause.
  @orderBy nvarchar(MAX) = NULL, --An optional ORDER BY clause. It should contain the words 'ORDER BY'.
  @html nvarchar(MAX) = NULL OUTPUT --The HTML output of the procedure.
)
AS
BEGIN   
  SET NOCOUNT ON;

  IF @orderBy IS NULL BEGIN
    SET @orderBy = ''  
  END

  SET @orderBy = REPLACE(@orderBy, '''', '''''');

  DECLARE @realQuery nvarchar(MAX) = '
    DECLARE @headerRow nvarchar(MAX);
    DECLARE @cols nvarchar(MAX);    

    SELECT * INTO #dynSql FROM (' + @query + ') sub;

    SELECT @cols = COALESCE(@cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
    FROM tempdb.sys.columns 
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @cols = ''SET @html = CAST(( SELECT '' + @cols + '' FROM #dynSql ' + @orderBy + ' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''    

    EXEC sys.sp_executesql @cols, N''@html nvarchar(MAX) OUTPUT'', @html=@html OUTPUT

    SELECT @headerRow = COALESCE(@headerRow + '''', '''') + ''<th>'' + name + ''</th>'' 
    FROM tempdb.sys.columns 
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @headerRow = ''<tr>'' + @headerRow + ''</tr>'';

    SET @html = ''<table border="1">'' + @headerRow + @html + ''</table>'';    
    ';

  EXEC sys.sp_executesql @realQuery, N'@html nvarchar(MAX) OUTPUT', @html=@html OUTPUT
END
GO

Usage:

DECLARE @html nvarchar(MAX);
EXEC spQueryToHtmlTable @html = @html OUTPUT,  @query = N'SELECT * FROM dbo.People', @orderBy = N'ORDER BY FirstName';

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Foo',
    @recipients = '[email protected];',
    @subject = 'HTML email',
    @body = @html,
    @body_format = 'HTML',
    @query_no_truncate = 1,
    @attach_query_result_as_file = 0;

Related: Here is similar code to turn any arbitrary query into a CSV string.

How to communicate between Docker containers via "hostname"

That should be what --link is for, at least for the hostname part.
With docker 1.10, and PR 19242, that would be:

docker network create --net-alias=[]: Add network-scoped alias for the container

(see last section below)

That is what Updating the /etc/hosts file details

In addition to the environment variables, Docker adds a host entry for the source container to the /etc/hosts file.

For instance, launch an LDAP server:

docker run -t  --name openldap -d -p 389:389 larrycai/openldap

And define an image to test that LDAP server:

FROM ubuntu
RUN apt-get -y install ldap-utils
RUN touch /root/.bash_aliases
RUN echo "alias lds='ldapsearch -H ldap://internalopenldap -LL -b
ou=Users,dc=openstack,dc=org -D cn=admin,dc=openstack,dc=org -w
password'" > /root/.bash_aliases
ENTRYPOINT bash

You can expose the 'openldap' container as 'internalopenldap' within the test image with --link:

 docker run -it --rm --name ldp --link openldap:internalopenldap ldaptest

Then, if you type 'lds', that alias will work:

ldapsearch -H ldap://internalopenldap ...

That would return people. Meaning internalopenldap is correctly reached from the ldaptest image.


Of course, docker 1.7 will add libnetwork, which provides a native Go implementation for connecting containers. See the blog post.
It introduced a more complete architecture, with the Container Network Model (CNM)

https://blog.docker.com/media/2015/04/cnm-model.jpg

That will Update the Docker CLI with new “network” commands, and document how the “-net” flag is used to assign containers to networks.


docker 1.10 has a new section Network-scoped alias, now officially documented in network connect:

While links provide private name resolution that is localized within a container, the network-scoped alias provides a way for a container to be discovered by an alternate name by any other container within the scope of a particular network.
Unlike the link alias, which is defined by the consumer of a service, the network-scoped alias is defined by the container that is offering the service to the network.

Continuing with the above example, create another container in isolated_nw with a network alias.

$ docker run --net=isolated_nw -itd --name=container6 -alias app busybox
8ebe6767c1e0361f27433090060b33200aac054a68476c3be87ef4005eb1df17

--alias=[]         

Add network-scoped alias for the container

You can use --link option to link another container with a preferred alias

You can pause, restart, and stop containers that are connected to a network. Paused containers remain connected and can be revealed by a network inspect. When the container is stopped, it does not appear on the network until you restart it.

If specified, the container's IP address(es) is reapplied when a stopped container is restarted. If the IP address is no longer available, the container fails to start.

One way to guarantee that the IP address is available is to specify an --ip-range when creating the network, and choose the static IP address(es) from outside that range. This ensures that the IP address is not given to another container while this container is not on the network.

$ docker network create --subnet 172.20.0.0/16 --ip-range 172.20.240.0/20 multi-host-network

$ docker network connect --ip 172.20.128.2 multi-host-network container2
$ docker network connect --link container1:c1 multi-host-network container2

Conversion from List<T> to array T[]

Try using

MyClass[] myArray = list.ToArray();

show icon in actionbar/toolbar with AppCompat-v7 21

A better way for setting multiple options:

setIcon/setLogo method will only work if you have set DisplayOptions Try this -

actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setIcon(R.drawable.ic_launcher);

You can also set options for displaying LOGO(just add constant ActionBar.DISPLAY_USE_LOGO). More information - displayOptions

Depend on a branch or tag using a git URL in a package.json?

On latest version of NPM you can just do:

npm install gitAuthor/gitRepo#tag

If the repo is a valid NPM package it will be auto-aliased in package.json as:

{ "NPMPackageName": "gitAuthor/gitRepo#tag" }

If you could add this to @justingordon 's answer there is no need for manual aliasing now !

How to write text in ipython notebook?

Change the cell type to Markdown in the menu bar, from Code to Markdown. Currently in Notebook 4.x, the keyboard shortcut for such an action is: Esc (for command mode), then m (for markdown).

How to create and handle composite primary key in JPA

Key class:

@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {

    public EntryKey() {
    }

    public EntryKey(final Long id, final Long version) {
        this.id = id;
        this.version = version;
    }

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getVersion() {
        return this.version;
    }

    public void setVersion(Long version) {
        this.version = version;
    }

    public boolean equals(Object other) {
        if (this == other)
            return true;
        if (!(other instanceof EntryKey))
            return false;
        EntryKey castOther = (EntryKey) other;
        return id.equals(castOther.id) && version.equals(castOther.version);
    }

    public int hashCode() {
        final int prime = 31;
        int hash = 17;
        hash = hash * prime + this.id.hashCode();
        hash = hash * prime + this.version.hashCode();
        return hash;
    }

    @Column (name = "ID")
    private Long id;
    @Column (name = "VERSION")
    private Long operatorId;
}

Entity class:

@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {

    @EmbeddedId
    public EntryKey getKey() {
        return this.key;
    }

    public void setKey(EntryKey id) {
        this.id = id;
    }

    ...

    private EntryKey key;
    ...
}

How can I duplicate it with another Version?

You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.

Reading in a JSON File Using Swift

Updated for Swift 3 with safest way

    private func readLocalJsonFile() {

    if let urlPath = Bundle.main.url(forResource: "test", withExtension: "json") {

        do {
            let jsonData = try Data(contentsOf: urlPath, options: .mappedIfSafe)

            if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) as? [String: AnyObject] {

                if let personArray = jsonDict["person"] as? [[String: AnyObject]] {

                    for personDict in personArray {

                        for (key, value) in personDict {

                            print(key, value)
                        }
                        print("\n")
                    }
                }
            }
        }

        catch let jsonError {
            print(jsonError)
        }
    }
}

enter image description here

nullable object must have a value

Assign the members directly without the .Value part:

DateTimeExtended(DateTimeExtended myNewDT)
{
   this.MyDateTime = myNewDT.MyDateTime;
   this.otherdata = myNewDT.otherdata;
}

Using Java generics for JPA findAll() query with WHERE clause

Hat tip to Adam Bien if you don't want to use createQuery with a String and want type safety:

 @PersistenceContext
 EntityManager em;

 public List<ConfigurationEntry> allEntries() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<ConfigurationEntry> cq = cb.createQuery(ConfigurationEntry.class);
        Root<ConfigurationEntry> rootEntry = cq.from(ConfigurationEntry.class);
        CriteriaQuery<ConfigurationEntry> all = cq.select(rootEntry);
        TypedQuery<ConfigurationEntry> allQuery = em.createQuery(all);
        return allQuery.getResultList();
 }

http://www.adam-bien.com/roller/abien/entry/selecting_all_jpa_entities_as

Can I use a min-height for table, tr or td?

The solution without div is used a pseudo element like ::after into first td in row with min-height. Save your HTML clean.

table tr td:first-child::after {
   content: "";
   display: inline-block;
   vertical-align: top;
   min-height: 60px;
}

How to do a scatter plot with empty circles in Python?

So I assume you want to highlight some points that fit a certain criteria. You can use Prelude's command to do a second scatter plot of the hightlighted points with an empty circle and a first call to plot all the points. Make sure the s paramter is sufficiently small for the larger empty circles to enclose the smaller filled ones.

The other option is to not use scatter and draw the patches individually using the circle/ellipse command. These are in matplotlib.patches, here is some sample code on how to draw circles rectangles etc.

How to set the text/value/content of an `Entry` widget using a button in tkinter

If you use a "text variable" tk.StringVar(), you can just set() that.

No need to use the Entry delete and insert. Moreover, those functions don't work when the Entry is disabled or readonly! The text variable method, however, does work under those conditions as well.

import Tkinter as tk

...

entryText = tk.StringVar()
entry = tk.Entry( master, textvariable=entryText )
entryText.set( "Hello World" )

Getter and Setter declaration in .NET

1st

string _myProperty { get; set; }

This is called an Auto Property in the .NET world. It's just syntactic sugar for #2.

2nd

string _myProperty;

public string myProperty
{
    get { return _myProperty; }
    set { _myProperty = value; }
}

This is the usual way to do it, which is required if you need to do any validation or extra code in your property. For example, in WPF if you need to fire a Property Changed Event. If you don't, just use the auto property, it's pretty much standard.

3

string _myProperty;

public string getMyProperty()
{
    return this._myProperty;
}

public string setMyProperty(string value)
{
    this._myProperty = value;
}

The this keyword here is redundant. Not needed at all. These are just Methods that get and set as opposed to properties, like the Java way of doing things.

Run Batch File On Start-up

If your Windows language is different from English, you can launch the Task Scheduler by

  1. Press Windows+X
  2. Select your language translation of "Computer Management"
  3. Follow the instruction in the answer provided by prankin

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Using :: in C++

look at it is informative [Qualified identifiers

A qualified id-expression is an unqualified id-expression prepended by a scope resolution operator ::, and optionally, a sequence of enumeration, (since C++11)class or namespace names or decltype expressions (since C++11) separated by scope resolution operators. For example, the expression std::string::npos is an expression that names the static member npos in the class string in namespace std. The expression ::tolower names the function tolower in the global namespace. The expression ::std::cout names the global variable cout in namespace std, which is a top-level namespace. The expression boost::signals2::connection names the type connection declared in namespace signals2, which is declared in namespace boost.

The keyword template may appear in qualified identifiers as necessary to disambiguate dependent template names]1

jQuery: How to get the HTTP status code from within the $.ajax.error method?

If you're using jQuery 1.5, then statusCode will work.

If you're using jQuery 1.4, try this:

error: function(jqXHR, textStatus, errorThrown) {
    alert(jqXHR.status);
    alert(textStatus);
    alert(errorThrown);
}

You should see the status code from the first alert.

JavaScript override methods

Once should avoid emulating classical OO and use prototypical OO instead. A nice utility library for prototypical OO is traits.

Rather then overwriting methods and setting up inheritance chains (one should always favour object composition over object inheritance) you should be bundling re-usable functions into traits and creating objects with those.

Live Example

var modifyA = {
    modify: function() {
        this.x = 300;
        this.y = 400;
    }
};

var modifyB = {
    modify: function() {
        this.x = 3000;
        this.y = 4000;
    }
};

C = function(trait) {
    var o = Object.create(Object.prototype, Trait(trait));

    o.modify();
    console.log("sum : " + (o.x + o.y));

    return o;
}

//C(modifyA);
C(modifyB);

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

If you're looking to paginate results, use the integrated paginator, it works great!

$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages

How do you query for "is not null" in Mongo?

In pymongo you can use:

db.mycollection.find({"IMAGE URL":{"$ne":None}});

Because pymongo represents mongo "null" as python "None".

React: why child component doesn't update when prop changes

Use the setState function. So you could do

       this.setState({this.state.foo.bar:123}) 

inside the handle event method.

Once, the state is updated, it will trigger changes, and re-render will take place.

Json.net serialize/deserialize derived types?

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" };
Derived object2 = new Derived() { Something = "Some other thing" };
List<Base> inheritanceList = new List<Base>() { object1, object2 };

JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
string Serialized = JsonConvert.SerializeObject(inheritanceList, settings);
List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings);

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

How to select data of a table from another database in SQL Server?

I've used this before to setup a query against another server and db via linked server:

EXEC sp_addlinkedserver @server='PWA_ProjectServer', @srvproduct='',
@provider='SQLOLEDB', @datasrc='SERVERNAME\PWA_ProjectServer'

per the comment above:

select * from [server].[database].[schema].[table]

e.g.

select top 6 * from [PWA_ProjectServer].[PWA_ProjectServer_Reporting].[dbo].[MSP_AdminStatus]

Python: json.loads returns items prefixing with 'u'

Those 'u' characters being appended to an object signifies that the object is encoded in "unicode".

If you want to remove those 'u' chars from your object you can do this:

import json, ast
jdata = ast.literal_eval(json.dumps(jdata)) # Removing uni-code chars

Let's checkout from python shell

>>> import json, ast
>>> jdata = [{u'i': u'imap.gmail.com', u'p': u'aaaa'}, {u'i': u'333imap.com', u'p': u'bbbb'}]
>>> jdata = ast.literal_eval(json.dumps(jdata))
>>> jdata
[{'i': 'imap.gmail.com', 'p': 'aaaa'}, {'i': '333imap.com', 'p': 'bbbb'}]

beyond top level package error in relative import

This one didn't work for me as I'm using Django 2.1.3:

import sys
sys.path.append("..") # Adds higher directory to python modules path.

I opted for a custom solution where I added a command to the server startup script to copy my shared script into the django 'app' that needed the shared python script. It's not ideal but as I'm only developing a personal website, it fit the bill for me. I will post here again if I can find the django way of sharing code between Django Apps within a single website.

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

What does the variable $this mean in PHP?

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

From the PHP docs:

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

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

I first came across this back with ADO and classic asp, the answer i got was: performance. if you do a straight

Select * from tablename

and pass that in as an sql command/text you will get a noticeable performance increase with the

Where 1=1

added, it was a visible difference. something to do with table headers being returned as soon as the first condition is met, or some other craziness, anyway, it did speed things up.

How can I find my php.ini on wordpress?

use this in your htaccess in your server

php_value upload_max_filesize 1000M php_value post_max_size 2000M

How to create timer in angular2

In Addition to all the previous answers, I would do it using RxJS Observables

please check Observable.timer

Here is a sample code, will start after 2 seconds and then ticks every second:

import {Component} from 'angular2/core';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'my-app',
    template: 'Ticks (every second) : {{ticks}}'
})
export class AppComponent {
  ticks =0;
  ngOnInit(){
    let timer = Observable.timer(2000,1000);
    timer.subscribe(t=>this.ticks = t);
  }
}

And here is a working plunker

Update If you want to call a function declared on the AppComponent class, you can do one of the following:

** Assuming the function you want to call is named func,

ngOnInit(){
    let timer = Observable.timer(2000,1000);
    timer.subscribe(this.func);
}

The problem with the above approach is that if you call 'this' inside func, it will refer to the subscriber object instead of the AppComponent object which is probably not what you want.

However, in the below approach, you create a lambda expression and call the function func inside it. This way, the call to func is still inside the scope of AppComponent. This is the best way to do it in my opinion.

ngOnInit(){
    let timer = Observable.timer(2000,1000);
    timer.subscribe(t=> {
        this.func(t);
    });
}

check this plunker for working code.

What does hash do in python?

TL;DR:

Please refer to the glossary: hash() is used as a shortcut to comparing objects, an object is deemed hashable if it can be compared to other objects. that is why we use hash(). It's also used to access dict and set elements which are implemented as resizable hash tables in CPython.

Technical considerations

  • usually comparing objects (which may involve several levels of recursion) is expensive.
  • preferably, the hash() function is an order of magnitude (or several) less expensive.
  • comparing two hashes is easier than comparing two objects, this is where the shortcut is.

If you read about how dictionaries are implemented, they use hash tables, which means deriving a key from an object is a corner stone for retrieving objects in dictionaries in O(1). That's however very dependent on your hash function to be collision-resistant. The worst case for getting an item in a dictionary is actually O(n).

On that note, mutable objects are usually not hashable. The hashable property means you can use an object as a key. If the hash value is used as a key and the contents of that same object change, then what should the hash function return? Is it the same key or a different one? It depends on how you define your hash function.

Learning by example:

Imagine we have this class:

>>> class Person(object):
...     def __init__(self, name, ssn, address):
...         self.name = name
...         self.ssn = ssn
...         self.address = address
...     def __hash__(self):
...         return hash(self.ssn)
...     def __eq__(self, other):
...         return self.ssn == other.ssn
... 

Please note: this is all based on the assumption that the SSN never changes for an individual (don't even know where to actually verify that fact from authoritative source).

And we have Bob:

>>> bob = Person('bob', '1111-222-333', None)

Bob goes to see a judge to change his name:

>>> jim = Person('jim bo', '1111-222-333', 'sf bay area')

This is what we know:

>>> bob == jim
True

But these are two different objects with different memory allocated, just like two different records of the same person:

>>> bob is jim
False

Now comes the part where hash() is handy:

>>> dmv_appointments = {}
>>> dmv_appointments[bob] = 'tomorrow'

Guess what:

>>> dmv_appointments[jim] #?
'tomorrow'

From two different records you are able to access the same information. Now try this:

>>> dmv_appointments[hash(jim)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __eq__
AttributeError: 'int' object has no attribute 'ssn'
>>> hash(jim) == hash(hash(jim))
True

What just happened? That's a collision. Because hash(jim) == hash(hash(jim)) which are both integers btw, we need to compare the input of __getitem__ with all items that collide. The builtin int does not have an ssn attribute so it trips.

>>> del Person.__eq__
>>> dmv_appointments[bob]
'tomorrow'
>>> dmv_appointments[jim]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: <__main__.Person object at 0x7f611bd37110>

In this last example, I show that even with a collision, the comparison is performed, the objects are no longer equal, which means it successfully raises a KeyError.

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

PHP cURL, extract an XML response

no, CURL does not have anything with parsing XML, it does not know anything about the content returned. it serves as a proxy to get content. it's up to you what to do with it.

use JSON if possible (and json_decode) - it's easier to work with, if not possible, use any XML library for parsin such as DOMXML: http://php.net/domxml

How do I install a module globally using npm?

I had issues installing Express on Ubuntu:

If for some reason NPM command is missing, test npm command with npm help. If not there, follow these steps - http://arnolog.net/post/8424207595/installing-node-js-npm-express-mongoose-on-ubuntu

If just the Express command is not working, try:

sudo npm install -g express

This made everything work as I'm used to with Windows7 and OSX.

Hope this helps!

Hide/Show Column in an HTML Table

The following is building on Eran's code, with a few minor changes. Tested it and it seems to work fine on Firefox 3, IE7.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
                "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script>
$(document).ready(function() {
    $('input[type="checkbox"]').click(function() {
        var index = $(this).attr('name').substr(3);
        index--;
        $('table tr').each(function() { 
            $('td:eq(' + index + ')',this).toggle();
        });
        $('th.' + $(this).attr('name')).toggle();
    });
});
</script>
<body>
<table>
<thead>
    <tr>
        <th class="col1">Header 1</th>
        <th class="col2">Header 2</th>
        <th class="col3">Header 3</th>
    </tr>
</thead>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
<tr><td>Column1</td><td>Column2</td><td>Column3</td></tr>
</table>

<form>
    <input type="checkbox" name="col1" checked="checked" /> Hide/Show Column 1 <br />
    <input type="checkbox" name="col2" checked="checked" /> Hide/Show Column 2 <br />
    <input type="checkbox" name="col3" checked="checked" /> Hide/Show Column 3 <br />
</form>
</body>
</html>

Convert NaN to 0 in javascript

using user 113716 solution, which by the way is great to avoid all those if-else I have implemented it this way to calculate my subtotal textbox from textbox unit and textbox quantity.

In the process writing of non numbers in unit and quantity textboxes, their values are bing replace by zero so final posting of user data has no non-numbers .

     <script src="/common/tools/jquery-1.10.2.js"></script>
     <script src="/common/tools/jquery-ui.js"></script>

     <!----------------- link above 2 lines to your jquery files ------>





    <script type="text/javascript" >
    function calculate_subtotal(){

    $('#quantity').val((+$('#quantity').val() || 0));
    $('#unit').val((+$('#unit').val() || 0));

    var  calculated = $('#quantity').val() * $('#unit').val() ;
    $('#subtotal').val(calculated);


    }
    </script>


      <input type = "text" onChange ="calculate_subtotal();" id = "quantity"/>
      <input type = "text" onChange ="calculate_subtotal();" id = "unit"/>
      <input type = "text" id = "subtotal"/>

How to auto-remove trailing whitespace in Eclipse?

In a pinch, for those editors that don't support removal of trailing whitespace at all (e.g. the XML editor), you can remove it from all lines by doing a find and replace, enabling regular expressions, then finding "[\t ]+$" and replacing it with "" (blank). There's probably a better regex to do that but it works for me without needing to install AnyEdit.

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

The important thing about a sprint is that: within a sprint the functionality that is to be delivered is fixed.

A sprint is normally an iteration. But you can for example have a 4 week sprint, but have 4 one week "internal" iterations within that sprint.

There is a lot of discussion about the length of sprints. I think that if you do it according to the book they should all be the same length.

We have found that a short first sprint to get the development environment up and running, followed by longer basic functionality sprints, then short sprints towards the end of the project, has worked for us.

CSS: Change image src on img:hover

For this you can use below code

1) html

<div id = "aks">

</div>

2) css

#aks
    {
        width:100px;
height:100px;    

        background-image:url('http://dummyimage.com/100x100/000/fff');}

#aks:hover {
    background-image:url('http://dummyimage.com/100x100/eb00eb/fff');

}

How do I determine height and scrolling position of window in jQuery?

From jQuery Docs:

const height = $(window).height();
const scrollTop = $(window).scrollTop();

http://api.jquery.com/scrollTop/
http://api.jquery.com/height/

With arrays, why is it the case that a[5] == 5[a]?

I think something is being missed by the other answers.

Yes, p[i] is by definition equivalent to *(p+i), which (because addition is commutative) is equivalent to *(i+p), which (again, by the definition of the [] operator) is equivalent to i[p].

(And in array[i], the array name is implicitly converted to a pointer to the array's first element.)

But the commutativity of addition is not all that obvious in this case.

When both operands are of the same type, or even of different numeric types that are promoted to a common type, commutativity makes perfect sense: x + y == y + x.

But in this case we're talking specifically about pointer arithmetic, where one operand is a pointer and the other is an integer. (Integer + integer is a different operation, and pointer + pointer is nonsense.)

The C standard's description of the + operator (N1570 6.5.6) says:

For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to a complete object type and the other shall have integer type.

It could just as easily have said:

For addition, either both operands shall have arithmetic type, or the left operand shall be a pointer to a complete object type and the right operand shall have integer type.

in which case both i + p and i[p] would be illegal.

In C++ terms, we really have two sets of overloaded + operators, which can be loosely described as:

pointer operator+(pointer p, integer i);

and

pointer operator+(integer i, pointer p);

of which only the first is really necessary.

So why is it this way?

C++ inherited this definition from C, which got it from B (the commutativity of array indexing is explicitly mentioned in the 1972 Users' Reference to B), which got it from BCPL (manual dated 1967), which may well have gotten it from even earlier languages (CPL? Algol?).

So the idea that array indexing is defined in terms of addition, and that addition, even of a pointer and an integer, is commutative, goes back many decades, to C's ancestor languages.

Those languages were much less strongly typed than modern C is. In particular, the distinction between pointers and integers was often ignored. (Early C programmers sometimes used pointers as unsigned integers, before the unsigned keyword was added to the language.) So the idea of making addition non-commutative because the operands are of different types probably wouldn't have occurred to the designers of those languages. If a user wanted to add two "things", whether those "things" are integers, pointers, or something else, it wasn't up to the language to prevent it.

And over the years, any change to that rule would have broken existing code (though the 1989 ANSI C standard might have been a good opportunity).

Changing C and/or C++ to require putting the pointer on the left and the integer on the right might break some existing code, but there would be no loss of real expressive power.

So now we have arr[3] and 3[arr] meaning exactly the same thing, though the latter form should never appear outside the IOCCC.

ln (Natural Log) in Python

Here is the correct implementation using numpy (np.log() is the natural logarithm)

import numpy as np
p = 100
r = 0.06 / 12
FV = 4000

n = np.log(1 + FV * r/ p) / np.log(1 + r)

print ("Number of periods = " + str(n))

Output:

Number of periods = 36.55539635919235

Integer division: How do you produce a double?

If you change the type of one the variables you have to remember to sneak in a double again if your formula changes, because if this variable stops being part of the calculation the result is messed up. I make a habit of casting within the calculation, and add a comment next to it.

double d = 5 / (double) 20; //cast to double, to do floating point calculations

Note that casting the result won't do it

double d = (double)(5 / 20); //produces 0.0

Offline Speech Recognition In Android (JellyBean)

I would like to improve the guide that the answer https://stackoverflow.com/a/17674655/2987828 sends to its users, with images. It is the sentence "For those that it doesn't, this is the ‘guide’ I supply them with." that I want to improve.

The user should click on the four buttons highlighted in blue in these images:

Go to your Android Application Settings, select Languages and input, edit Settings of Google Voice typing, select Download Offline speech recognition, select your languages in the ALL tab.

Then the user can select any desired languages. When the download is done, he should disconnect from network, and then click on the "microphone" button of the keyboard.

It worked for me (android 4.1.2), then language recognition worked out of the box, without rebooting. I can now dictates instructions to the shell of Terminal Emulator ! And it is twice faster offline than online, on a padfone 2 from ASUS.

These images are licensed under cc by-sa 3.0 with attribution required to stackoverflow.com/a/21329845/2987828 ; you may hence add these images anywhere along with this attribution.

(This the standard policy of all images and texts at stackoverflow.com)

Disable EditText blinking cursor

Perfect Solution that goes further to the goal

Goal: Disable the blinking curser when EditText is not in focus, and enable the blinking curser when EditText is in focus. Below also opens keyboard when EditText is clicked, and hides it when you press done in the keyboard.

1) Set in your xml under your EditText:

android:cursorVisible="false"

2) Set onClickListener:

iEditText.setOnClickListener(editTextClickListener);

OnClickListener editTextClickListener = new OnClickListener() 

{

    public void onClick(View v) 
    {
         if (v.getId() == iEditText.getId()) 
        {
            iEditText.setCursorVisible(true);
        }

    }
};

3) then onCreate, capture the event when done is pressed using OnEditorActionListener to your EditText, and then setCursorVisible(false).

//onCreate...

iEditText.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {
                    iEditText.setCursorVisible(false);
                if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    in.hideSoftInputFromWindow(iEditText.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });

Why does my Eclipse keep not responding?

I had similar symptoms recently. Turned out it was caused by the Subversion server being unavailable - once that was restarted I was able to right-click. My environment was Eclipse Luna with Subclipse.

So worth checking that any connected source control systems are operational. Hope that helps.

Removing duplicate rows from table in Oracle

solution :

delete from emp where rowid in
(
    select rid from
    (
        select rowid rid,
        row_number() over(partition by empno order by empno) rn
        from emp
    )
    where rn > 1
);

How are software license keys generated?

You can use and implement Secure Licensing API from very easily in your Software Projects using it,(you need to download the desktop application for creating secure license from https://www.systemsoulsoftwares.com/)

  1. Creates unique UID for client software based on System Hardware(CPU,Motherboard,Hard-drive) (UID acts as Private Key for that unique system)
  2. Allows to send Encrypted license string very easily to client system, It verifies license string and works on only that particular system
  3. This method allows software developers or company to store more information about software/developer/distributor services/features/client
  4. It gives control for locking and unlocked the client software features, saving time of developers for making more version for same software with changing features
  5. It take cares about trial version too for any number of days
  6. It secures the License timeline by Checking DateTime online during registration
  7. It unlocks all hardware information to developers
  8. It has all pre-build and custom function that developer can access at every process of licensing for making more complex secure code

Could not load file or assembly ... An attempt was made to load a program with an incorrect format (System.BadImageFormatException)

You may need to change the Appication Pool setting "Enable 32bit Applications" to TRUE in IIS7 if you have at least 1 32bit dll\exe in your project.

How to count the number of occurrences of a character in an Oracle varchar value?

REGEXP_COUNT should do the trick:

select REGEXP_COUNT('123-345-566', '-') from dual;

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

Expand and collapse with angular js

Here a simple and easy solution on Angular JS using ng-repeat that might help.

_x000D_
_x000D_
var app = angular.module('myapp', []);_x000D_
_x000D_
app.controller('MainCtrl', function($scope) {_x000D_
_x000D_
  $scope.arr= [_x000D_
    {name:"Head1",desc:"Head1Desc"},_x000D_
    {name:"Head2",desc:"Head2Desc"},_x000D_
    {name:"Head3",desc:"Head3Desc"},_x000D_
    {name:"Head4",desc:"Head4Desc"}_x000D_
    ];_x000D_
    _x000D_
    $scope.collapseIt = function(id){_x000D_
      $scope.collapseId = ($scope.collapseId==id)?-1:id;_x000D_
    }_x000D_
});
_x000D_
/* Put your css in here */_x000D_
li {_x000D_
  list-style:none;_x000D_
  padding:5px;_x000D_
  color:red;_x000D_
}_x000D_
div{_x000D_
  padding:10px;_x000D_
  background:#ddd;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html ng-app="myapp">_x000D_
  <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <title>AngularJS Simple Collapse</title>_x000D_
    <script data-require="[email protected]" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js" data-semver="1.5.11"></script>_x000D_
</head>_x000D_
<body ng-controller="MainCtrl">_x000D_
<ul>_x000D_
  <li ng-repeat='ret in arr track by $index'>_x000D_
    <div ng-click="collapseIt($index)">{{ret.name}}</div>_x000D_
    <div ng-if="collapseId==$index">_x000D_
      {{ret.desc}}_x000D_
    </div>_x000D_
  </li>_x000D_
</ul>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This should fulfill your requirements. Here is a working code.

Plunkr Link http://plnkr.co/edit/n5DZxluYHi8FI3OmzFq2?p=preview

Github: https://github.com/deepakkoirala/SimpleAngularCollapse

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

What is the Linux equivalent to DOS pause?

Try this:

function pause(){
   read -p "$*"
}

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Difference between Iterator and Listiterator?

There are two differences:

  1. We can use Iterator to traverse Set and List and also Map type of Objects. While a ListIterator can be used to traverse for List-type Objects, but not for Set-type of Objects.

    That is, we can get a Iterator object by using Set and List, see here:

    By using Iterator we can retrieve the elements from Collection Object in forward direction only.

    Methods in Iterator:

    1. hasNext()
    2. next()
    3. remove()
    Iterator iterator = Set.iterator();
    Iterator iterator = List.iterator();
  2. But we get ListIterator object only from the List interface, see here:

    where as a ListIterator allows you to traverse in either directions (Both forward and backward). So it has two more methods like hasPrevious() and previous() other than those of Iterator. Also, we can get indexes of the next or previous elements (using nextIndex() and previousIndex() respectively )

    Methods in ListIterator:

    1. hasNext()
    2. next()
    3. previous()
    4. hasPrevious()
    5. remove()
    6. nextIndex()
    7. previousIndex()
    ListIterator listiterator = List.listIterator();

    i.e., we can't get ListIterator object from Set interface.

Reference : - What is the difference between Iterator and ListIterator ?

Extract the filename from a path

If you are ok with including the extension this should do what you want.

$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf

From a Sybase Database, how I can get table description ( field names and types)?

sp_tables will also work in isql. It gives you the list of tables in the current database.

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Some special characters give this type of error, so use

$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";

Insert picture/table in R Markdown

Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.

Images

The bookdown book does a great job of explaining that the best way to include images is by using include_graphics(). For example, a full width image can be printed with a caption below:

```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```

The reason this method is better than the pandoc approach ![your image](path/to/image):

  • It automatically changes the command based on the output format (HTML/PDF/Word)
  • The same syntax can be used to the size of the plot (fig.width), the output width in the report (out.width), add captions (fig.cap) etc.
  • It uses the best graphical devices for the output. This means PDF images remain high resolution.

Tables

knitr::kable() is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.

```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```

If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table package. It provides a tidy graphical interface for making tables.

Achieving custom styling of the table column width is beyond the scope of knitr, but the kableExtra package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html

Style Tips

The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.

If you are looking for potential extensions to the formatting, the bookdown package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html

Accessing the index in 'for' loops?

If I were to iterate nums = [1, 2, 3, 4, 5] I would do

for i, num in enumerate(nums, start=1):
    print(i, num)

Or get the length as l = len(nums)

for i in range(l):
    print(i+1, nums[i])

Download a file by jQuery.Ajax

The simple way to make the browser downloads a file is to make the request like that:

 function downloadFile(urlToSend) {
     var req = new XMLHttpRequest();
     req.open("GET", urlToSend, true);
     req.responseType = "blob";
     req.onload = function (event) {
         var blob = req.response;
         var fileName = req.getResponseHeader("fileName") //if you have the fileName header available
         var link=document.createElement('a');
         link.href=window.URL.createObjectURL(blob);
         link.download=fileName;
         link.click();
     };

     req.send();
 }

This opens the browser download pop up.

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

For me the problem was in NDK_ROOT not being set.

Check your console if:

NDK_ROOT = None [!] NDK_ROOT not defined. Please define NDK_ROOT in your environment or in local.properties

Check if you have set:

  • NDK_ROOT and SDK_ROOT in C/C++->Build->Environment
  • Android->NDK
  • Android->SDK

Read text file into string. C++ ifstream

To read a whole line from a file into a string, use std::getline like so:

 std::ifstream file("my_file");
 std::string temp;
 std::getline(file, temp);

You can do this in a loop to until the end of the file like so:

 std::ifstream file("my_file");
 std::string temp;
 while(std::getline(file, temp)) {
      //Do with temp
 }

References

http://en.cppreference.com/w/cpp/string/basic_string/getline

http://en.cppreference.com/w/cpp/string/basic_string

Using PHP with Socket.io

UPDATE: Aug 2014 The current socket.io v1.0 site has a PHP example:- https://github.com/rase-/socket.io-php-emitter

SQL Server reports 'Invalid column name', but the column is present and the query works through management studio

If you are running this inside a transaction and a SQL statement before this drops/alters the table you can also get this message.

How do I delete unpushed git commits?

I wonder why the best answer that I've found is only in the comments! (by Daenyth with 86 up votes)

git reset --hard origin

This command will sync the local repository with the remote repository getting rid of every change you have made on your local. You can also do the following to fetch the exact branch that you have in the origin.

git reset --hard origin/<branch>

Is "&#160;" a replacement of "&nbsp;"?

Those do both mean non-breaking space, yes. &#xA0; is another synonym, in hex.

What's the difference between eval, exec, and compile?

  1. exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:

     exec('print(5)')           # prints 5.
     # exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
     exec('print(5)\nprint(6)')  # prints 5{newline}6.
     exec('if True: print(6)')  # prints 6.
     exec('5')                 # does nothing and returns nothing.
    
  2. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:

     x = eval('5')              # x <- 5
     x = eval('%d + 6' % x)     # x <- 11
     x = eval('abs(%d)' % -100) # x <- 100
     x = eval('x = 5')          # INVALID; assignment is not an expression.
     x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.
    
  3. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  4. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.

  5. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.

  6. compile(string, '', 'single') is like the exec mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')

Regular expression to extract URL from an HTML link

Don't use regexes, use BeautifulSoup. That, or be so crufty as to spawn it out to, say, w3m/lynx and pull back in what w3m/lynx renders. First is more elegant probably, second just worked a heck of a lot faster on some unoptimized code I wrote a while back.

How to remove an element from an array in Swift

To remove elements from an array, use the remove(at:), removeLast() and removeAll().

yourArray = [1,2,3,4]

Remove the value at 2 position

yourArray.remove(at: 2)

Remove the last value from array

yourArray.removeLast()

Removes all members from the set

yourArray.removeAll()

Node.js check if path is file or directory

Seriously, question exists five years and no nice facade?

function is_dir(path) {
    try {
        var stat = fs.lstatSync(path);
        return stat.isDirectory();
    } catch (e) {
        // lstatSync throws an error if path doesn't exist
        return false;
    }
}

ImportError: No module named BeautifulSoup

Try this from bs4 import BeautifulSoup

This might be a problem with Beautiful Soup, version 4, and the beta days. I just read this from the homepage.

Java 8 Lambda Stream forEach with multiple statements

You don't have to cram multiple operations into one stream/lambda. Consider separating them into 2 statements (using static import of toList()):

entryList.forEach(e->e.setTempId(tempId));

List<Entry> updatedEntries = entryList.stream()
  .map(e->entityManager.update(entry, entry.getId()))
  .collect(toList());

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

YYYY-MM-DD format date in shell script

You can do something like this:

$ date +'%Y-%m-%d'

Replace transparency in PNG images with white background

Using -flatten made me completely mad because -flatten in combination with mogrify crop and resizing simply doesn't work. The official and for me only correct way is to "remove" the alpha channel.

-alpha remove -alpha off (not needed with JPG)

See documention: http://www.imagemagick.org/Usage/masking/#remove

Split array into chunks

I prefer to use the splice method instead of slice. This solution uses the array length and chunk size to create a loop count and then loops over the array which gets smaller after every operation due to splicing in each step.

    function chunk(array, size) {
      let resultArray = [];
      let chunkSize = array.length/size;
      for(i=0; i<chunkSize; i++) {
        resultArray.push(array.splice(0, size));
      }
    return console.log(resultArray);
    }
    chunk([1,2,3,4,5,6,7,8], 2);

If you dont want to mutate the original array, you can clone the original array using the spread operator and then use that array to solve the problem.

    let clonedArray = [...OriginalArray]

How to iterate over a JSONObject?

org.json.JSONObject now has a keySet() method which returns a Set<String> and can easily be looped through with a for-each.

for(String key : jsonObject.keySet())

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

Zupa did a great job explaining closures with 'use' and the difference between EarlyBinding and Referencing the variables that are 'used'.

So I made a code example with early binding of a variable (= copying):

<?php

$a = 1;
$b = 2;

$closureExampleEarlyBinding = function() use ($a, $b){
    $a++;
    $b++;
    echo "Inside \$closureExampleEarlyBinding() \$a = ".$a."<br />";
    echo "Inside \$closureExampleEarlyBinding() \$b = ".$b."<br />";    
};

echo "Before executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "Before executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";  

$closureExampleEarlyBinding();

echo "After executing \$closureExampleEarlyBinding() \$a = ".$a."<br />";
echo "After executing \$closureExampleEarlyBinding() \$b = ".$b."<br />";

/* this will output:
Before executing $closureExampleEarlyBinding() $a = 1
Before executing $closureExampleEarlyBinding() $b = 2
Inside $closureExampleEarlyBinding() $a = 2
Inside $closureExampleEarlyBinding() $b = 3
After executing $closureExampleEarlyBinding() $a = 1
After executing $closureExampleEarlyBinding() $b = 2
*/

?>

Example with referencing a variable (notice the '&' character before variable);

<?php

$a = 1;
$b = 2;

$closureExampleReferencing = function() use (&$a, &$b){
    $a++;
    $b++;
    echo "Inside \$closureExampleReferencing() \$a = ".$a."<br />";
    echo "Inside \$closureExampleReferencing() \$b = ".$b."<br />"; 
};

echo "Before executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "Before executing \$closureExampleReferencing() \$b = ".$b."<br />";   

$closureExampleReferencing();

echo "After executing \$closureExampleReferencing() \$a = ".$a."<br />";
echo "After executing \$closureExampleReferencing() \$b = ".$b."<br />";    

/* this will output:
Before executing $closureExampleReferencing() $a = 1
Before executing $closureExampleReferencing() $b = 2
Inside $closureExampleReferencing() $a = 2
Inside $closureExampleReferencing() $b = 3
After executing $closureExampleReferencing() $a = 2
After executing $closureExampleReferencing() $b = 3
*/

?>

failed to lazily initialize a collection of role

Lazy exceptions occur when you fetch an object typically containing a collection which is lazily loaded, and try to access that collection.

You can avoid this problem by

  • accessing the lazy collection within a transaction.
  • Initalizing the collection using Hibernate.initialize(obj);
  • Fetch the collection in another transaction
  • Use Fetch profiles to select lazy/non-lazy fetching runtime
  • Set fetch to non-lazy (which is generally not recommended)

Further I would recommend looking at the related links to your right where this question has been answered many times before. Also see Hibernate lazy-load application design.

How to convert an Stream into a byte[] in C#?

The shortest solution I know:

using(var memoryStream = new MemoryStream())
{
  sourceStream.CopyTo(memoryStream);
  return memoryStream.ToArray();
}

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

Properties file with a list as the value for an individual key

If this is for some configuration file processing, consider using Apache configuration. https://commons.apache.org/proper/commons-configuration/javadocs/v1.10/apidocs/index.html?org/apache/commons/configuration/PropertiesConfiguration.html It has way to multiple values to single key- The format is bit different though

key=value1,value2,valu3 gives three values against same key.