Q:

why can I autowire or inject pojo but I can't autowire or inject RestTemplate

I read a lot in this forum about similiar problems happening when trying to Autowire a pojo and usually the answer to fix is related to component-scan or @Component/@Controller. But in my case I manage to autowire my pojo (Mas60010) but I can not autowire RestTemplate or ObjectMapper and possibly any other object from a package that I didn't code.
To make simple, I just mention RestTemplate. What I am doing wrong? I guess the problem is either with libraries or configuration. Note: please, don't point this question as duplicate only by showing a question that is related to his own pojo. You can see that it is not my question because I am able to manage this. The problem is with classes inside jars included in my project.
package com.ma.mhe.log.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.RestTemplate;

@Component
public class Lo_DisplayHandler extends Lo_Handler {

       @Autowired private Mas60010 _mas60010; //this work perfectly
       @Autowired private RestTemplate restTemplate; //this always cause nullPointException

mvc-dispatcher-servlet.xml
<context:annotation-config />
<mvc:annotation-driven />
<context:component-scan base-package="com.ma.mhe.log.handle, com.ma.mhe.log.domain" />
<context:property-placeholder location="classpath:restServices.properties"/>

<mvc:resources mapping="/**" location="/" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/pages/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter"/>
        </list>
    </property>
</bean>

<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</bean>

<!-- I was expecting this line to be enouth -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
</bean>

//Pojo - I can autowire it
package com.ma.log.domain;

import org.springframework.stereotype.Service;

@Service
public class Mas60010 {

All libraries

"validation-api-1.0.0.GA.jar"
"aopalliance-1.0.jar"
"commons-logging-1.1.1.jar"
"db2java.zip"
"hibernate-validator-4.1.0.Final.jar"
"hibernate-validator-annotation-processor-4.1.0.Final.jar"
"jackson-annotations-2.2.3.jar"
"jackson-core-2.2.3.jar"
"jackson-databind-2.2.3.jar"
"slf4j-api-1.7.5.jar"
"spring-aop-4.1.2.RELEASE.jar"
"spring-beans-4.1.2.RELEASE.jar"
"spring-context-4.1.2.RELEASE.jar"
"spring-context-support-4.1.2.RELEASE.jar"
"spring-core-4.1.2.RELEASE.jar"
"spring-expression-4.1.2.RELEASE.jar"
"spring-web-4.1.2.RELEASE.jar"
"spring-webmvc-4.1.2.RELEASE.jar"
"upload.jar"

//StackTrace
[12/17/14 10:38:54:243 CST] 00000033 SystemErr                                                    R        at com.ma.mhe.log.handler.Lo_DisplayHandler.lastPage(Lo_DisplayHandler.java:181)
[12/17/14 10:38:54:246 CST] 00000033 SystemErr                                                    R        at com.ma.mhe.log.Lo_Servlet.doDisDis(Lo_Servlet.java:164)
[12/17/14 10:38:54:248 CST] 00000033 SystemErr                                                    R        at com.ma.mhe.log.Lo_Servlet.doProcess(Lo_Servlet.java:51)
[12/17/14 10:38:54:250 CST] 00000033 SystemErr                                                    R        at com.ma.mhe.log.Lo_Servlet.doPost(Lo_Servlet.java:24)
[12/17/14 10:38:54:253 CST] 00000033 SystemErr                                                    R        at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
[12/17/14 10:38:54:255 CST] 00000033 SystemErr                                                    R        at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
[12/17/14 10:38:54:257 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1274)
[12/17/14 10:38:54:260 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:767)
[12/17/14 10:38:54:261 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:469)
[12/17/14 10:38:54:262 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1060)
[12/17/14 10:38:54:263 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:1377)
[12/17/14 10:38:54:265 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:185)
[12/17/14 10:38:54:266 CST] 00000033 SystemErr                                                    R        at com.ma.mhe.Mhe_ControllerServlet.doProcess(Mhe_ControllerServlet.java:83)
[12/17/14 10:38:54:267 CST] 00000033 SystemErr                                                    R        at com.ma.mhe.Mhe_ControllerServlet.doPost(Mhe_ControllerServlet.java:32)
[12/17/14 10:38:54:268 CST] 00000033 SystemErr                                                    R        at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
[12/17/14 10:38:54:269 CST] 00000033 SystemErr                                                    R        at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
[12/17/14 10:38:54:270 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1274)
[12/17/14 10:38:54:271 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:767)
[12/17/14 10:38:54:272 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:469)
[12/17/14 10:38:54:273 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1060)
[12/17/14 10:38:54:275 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:81)
[12/17/14 10:38:54:276 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:885)
[12/17/14 10:38:54:277 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:266)
[12/17/14 10:38:54:277 CST] 00000033 SystemErr                                                    R        at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:776)
[12/17/14 10:38:54:278 CST] 00000033 SystemErr                                                    R        at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
[12/17/14 10:38:54:279 CST] 00000033 SystemErr                                                    R        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
[12/17/14 10:38:54:280 CST] 00000033 SystemErr                                                    R        at java.lang.Thread.run(Thread.java:662)

IBM WebSphere Liberty Profile enabled features
<featureManager>
        <feature>jsp-2.2</feature>
        <feature>localConnector-1.0</feature>
        <feature>jdbc-4.0</feature>
        <feature>jaxrs-1.1</feature>
        <feature>json-1.0</feature>
        <feature>cdi-1.0</feature>
        <feature>managedBeans-1.0</feature>
        <feature>beanValidation-1.0</feature>
</featureManager>

//class Lo_DisplayHandler
@Component
public class Lo_DisplayHandler extends Lo_Handler {

       public Lo_DisplayHandler() {
              super();
       }

       @Autowired
       private Mas60010 _mas60010;
       @Autowired private RestTemplate restTemplate;

       public Lo_DisplayHandler(HttpServletRequest request,HttpServletResponse response) {
              super();

              this.request  = request;
              this.response = response;
       }

       public void lastPage() {
              //RestTemplate restTemplate = new RestTemplate(); //if I uncomment this line and comment the @Autowired it will work
              ObjectMapper mapper = new ObjectMapper();
              try{

                     myPojoParameters...

                     //the next line rises nullPointExcepetion if I choose Autowired instead of new RestTemplate()
                     LogDisplay _l = restTemplate.postForObject(myServiceUrl,myPojoParameters, LogDisplay.class);
                     Lo_DisplayRecord lo_DisplayRecord = new Lo_DisplayRecord();

                     ArrayList<Lo_DisplayRecord> displayValues = new ArrayList<Lo_DisplayRecord>();

                     for(int i = 0; i < _l.getDisplayValues().size(); i++){
                           lo_DisplayRecord = mapper.convertValue(_l.getDisplayValues().get(i), Lo_DisplayRecord.class);
                           displayValues.add(lo_DisplayRecord);
                     }

                     Some not relevant operations...
              }catch(Exception e){
                     e.printStackTrace();

//Lo_Servlet
package com.ma.mhe.log;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ma.mhe.Mhe_Servlet;
import com.ma.mhe.PageFlow;
import com.ma.mhe.log.handler.*;

public class Lo_Servlet extends Mhe_Servlet {

                private String _module = "lo       public void init(){}

                public void doPost(
                                javax.servlet.http.HttpServletRequest request,
                                javax.servlet.http.HttpServletResponse response)
                                throws javax.servlet.ServletException, java.io.IOException {
                                doProcess(request,response);
                }

                public void doGet(
                                javax.servlet.http.HttpServletRequest request,
                                javax.servlet.http.HttpServletResponse response)
                                throws javax.servlet.ServletException, java.io.IOException {
                                doProcess(request,response);
                }
                public void doProcess(
                                javax.servlet.http.HttpServletRequest request,
                                javax.servlet.http.HttpServletResponse response)
                                throws javax.servlet.ServletException, java.io.IOException {
                                HttpSession session = request.getSession();
                                int val = setTask(session,request);

                                switch(val){

                                //FILTER PAGE
                                case 1:doFilRep(request,response);break;
                                case 2:doFilFil(request,response);break;
                                case 3:doFilDis(request,response);break;
                                case 4:doFilDef(request,response);break;

                                //DISPLAY PAGE
                                case 5:doDisRep(request,response);break;
                                case 6:doDisFil(request,response);break;
                                case 7:doDisDis(request,response);break;

       private void doDisDis(HttpServletRequest request,HttpServletResponse response){

              Lo_DisplayHandler display = null;
              try{
                     display = new Lo_DisplayHandler(request,response);

                     display.lastPage();
              }catch(Exception e){
                                   }finally{
                     display = null;
              }

       }

//web.xml

    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
           MHE
       <servlet>
              <servlet-name>mvc-dispatcher</servlet-name>
              <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
              <load-on-startup>1</load-on-startup>
       </servlet>

       <servlet-mapping>
              <servlet-name>mvc-dispatcher</servlet-name>
              <url-pattern>/</url-pattern>
       </servlet-mapping>

       <listener>
              <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
       </listener>

    <servlet>
        <servlet-name>myservice</servlet-name>
        <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
                     <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>

       <servlet>
              <description>
              </description>
              <display-name>Lo_Servlet</display-name>
              <servlet-name>Lo_Servlet</servlet-name>
              <servlet-class>com.ma.mhe.log.Lo_Servlet</servlet-class>

       </servlet>
... others servlets configuration like this

A:

private void doDisDis(HttpServletRequest request,HttpServletResponse response){
    Lo_DisplayHandler display = null;
    try {
        display = new Lo_DisplayHandler(request,response);
        display.lastPage();
    }catch(Exception e){
    }finally{
        display = null;
    }
}

The code above is creating new instances of the Lo_DisplayHandler class. Those instances aren't managed by Spring, so basically the @Autowired is pretty useless here. Spring will only do dependency injection into beans it knows.
Assuming that you are using the ContextLoaderListener to load the spring configuration you can use the WebApplicationContextUtils to get the ApplicationContext. You can use this to get the beans you want.
private void doDisDis(HttpServletRequest request,HttpServletResponse response){
    Lo_DisplayHandler display = null;
    try {
        ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        display = context.getBean(Lo_DisplayHandler.class, request, response);
        display.lastPage();
    }catch(Exception e){
    }finally{
        display = null;
    }
}

To make this work you have to make your Lo_DisplayHandler a prototype bean, this means each time a getBean call is done a new instance is created. For this add the @Scope annotation to the class.
@Component
@Scope("prototype")
public class Lo_DisplayHandler extends Lo_Handler { ... }

A final note instead of doing a lookup for the ApplicationContext each time you need one, you might want to do it once in the init method of the servlet and store it as an instance variable. Saves you a line of code and some performance.


Q:

Determine $f^{(22)}(0)$, when $f(x)=x^{19}\ln(1+2x)$

"Determine $f^{(22)}(0)$, when $f(x)=x^{19}\ln(1+2x)$."
Here is my attempt. First, I wrote $f=gh$, where $g=x^{19}$ and $h=\ln(1+2x)$. The derivatives of both of these functions behave predictably at $x=0$. For example, $g^{19} = 19!$, taking further derivatives simply yields zero, and previous derivatives at $x=0$ are also zero, since they contain $x$ as a multiplier. The derivatives of $h$ behave according to this sequence $$\frac{{x_n}}{(1+2x)^n}$$
where ${x_n}=\{2,-4,16,-96,768,...\}.$ The denominator is $(1+2x)^n=(1+2 \cdot 0)^n=1^n =1$, so the value of $h'$ is simply the value of the sequence at $n\in \Bbb{N}.$ Next I tried to find a pattern in the application of the product rule with $f=gh$. Multiple applications yields $$f^1=g^1h+gh^1$$ $$f^2=g^2h+g^1h^1+g^1h^1+gh^2$$ $$f^3 = g^3h+g^2h^1+g^2h^1+g^1h^2+g^2h^1+g^1h^2+g^1h^2+gh^3$$ $$...$$
The idea was to find a way to connect $g^{19}$ with the correct values of $h'$, then compute the value of $f^{22}$ with the help of these simple derivatives.
I haven't found one yet, but I think it might be possible to find a pattern in repeated applications of the product rule, but before that I wanted to ask whether there is some flaw in my work. Also, I'm not entirely sure about this but might this https://en.wikipedia.org/wiki/General_Leibniz_rule help here?

A:

$f^{(22)}$ probably means the $22$th derivative of $f$, not $f$ raised to the $22$th power. With this in mind, write $\mathrm{ln}(1+2x) = 2x - \frac{(2x)^2}{2} + \frac{(2x)^3}{3} - \cdots$. Thus
$$
f(x) = x^{19}\mathrm{ln}(1+2x) = 2x^{20} - \frac{4x^{21}}{2} + \frac{8x^{22}}{3} - \cdots,
$$
from which we conclude that $f^{(22)}(0) = 22!\frac{8}{3}$, since the $n$th coefficient of the Taylor series at $x = 0$ for a function $f(x)$ is $\frac{f^{(n)}(0)}{n!}$.


Q:

Android Manifest file customization

How to customize an Android manifest file to have the following features?

LDPI devices must be excluded.
Camera with low resolution (320X240) must be excluded.
Tablet devices must be excluded.

A:

For compatible-screens write this code in your manifest:
    <compatible-screens>
<screen android:screenDensity="mdpi" android:screenSize="large"/>
<screen android:screenDensity="mdpi" android:screenSize="xlarge"/>
<screen android:screenDensity="hdpi" android:screenSize="small"/>
<screen android:screenDensity="hdpi" android:screenSize="normal"/>
<screen android:screenDensity="hdpi" android:screenSize="large"/>
<screen android:screenDensity="hdpi" android:screenSize="xlarge"/>
</compatible-screens>

This will only support mdpi and hdpi phones.


Q:

How to string match using dplyr mutate in R using a vector of strings

I am trying to string match values in a dataframe column with elements in a vector of strings. If there is a match I would like the element in the vector to be returned. I am using a function in dplyr:mutate to try and achieve this.
I have a dataframe called keywords like so:
+-----------------------+-------------+---------------+
|      Page.Title       | Event.Label | Unique.Events |
+-----------------------+-------------+---------------+
| Awesome Sale in Spain | pool        |           123 |
| Spain Holidays        | pool        |            34 |
| Edinburgh Castles     | sea-view    |            45 |
| London Houses         | help-to-buy |            56 |
| Cars in Greece        | beach       |            82 |
+-----------------------+-------------+---------------+

I have a vector called locations like so:
c('Edinburgh', 'London', 'Spain')
I created a function called location_finder like so:
function(locations,col_name){
  for (i in locations) {
    if (str_detect(col_name, i)) {
      return(i)
    } else {
      return ('Other')
    }
  }
}

My code is:
require(dplyr)
require(magrittr)
require(stringr)

df_working <- rowwise(keywords) %>%
  mutate(Location=location_finder(locations,Page.Title))

My expected output is:
+-----------------------+-------------+---------------+-----------+
|      Page.Title       | Event.Label | Unique Events | Location  |
+-----------------------+-------------+---------------+-----------+
| Awesome Sale in Spain | pool        |           123 | Spain     |
| Spain Holidays        | pool        |            34 | Spain     |
| Edinburgh Castles     | sea-view    |            45 | Edinburgh |
| London Houses         | help-to-buy |            56 | London    |
| Cars in Greece        | beach       |            82 | Other     |
+-----------------------+-------------+---------------+-----------+

My results only match on 'Edinburgh' only, otherwise 'Other' is only returned. Presumably because 'Edinburgh' is the first element in the vector. Any help would be appreciated.

A:

You could rewrite your function using grepl, and then extract the match from your cities list as such:
string <- "Awesome Sale in Spain"
cities <- c('Edinburgh', 'London', 'Spain')
cities[sapply(cities, grepl, string)]

This solution would also return multiple cities if there are multiple matches.
EDIT:
Here it has been done for a dataframe
df <- data.frame(Page.Title = c("Awesome Sale in Spain", "Spain Holidays", "Edinburgh Castles", "London Houses", "Cars in Greece"),
                 Event.Label = c("pool", "pool", "sea-view", "help-to-buy", "beach"))

cities <- c('Edinburgh', 'London', 'Spain')

df$cities <- sapply(df$Page.Title, function(title) {
  city <- cities[sapply(cities, grepl, title)]
})

EDIT2:
If you want to handle cases, then just use:
city <- cities[sapply(cities, grepl, title, ignore.case = TRUE)]


Q:

contact form 7 captcha support any other captcha plugin?

I am Using wp & I installed Contact form7. Now I want to Add Captcha with Contact form7. I don't like "Really Simple Captcha" because it shows very simple images. Any other Captcha Plugin Support Contact form7? I need Like the output of "SI CAPTCHA Anti-Spam" or "Fast Secure Contact Form", Here Unfortunately I can't Remove Contact form7 Plugin. So I want to Add Captcha Plugin with my Contact form7.

A:

Use SweetCaptcha!
http://wordpress.org/extend/plugins/sweetcaptcha-revolutionary-free-captcha-service/
If you need any help , drop them a mail to :
support@SweetCaptcha.com
http://www.SweetCaptcha.com
Cheers,
Josh


Q:

Raspberry Pi FileZilla SSH Permissions

Thanks for your help previously. I have now set my Pi up as a web server and when I go to remotely connect via SSH in FileZilla (OS X), I get the following errors when attempting to add/remove a file in certain directories:
Response:   200 Type set to A
Command:    PASV
Response:   227 Entering Passive Mode (192,168,2,4,190,243).
Command:    STOR index.php
Response:   550 index.php: Permission denied
Error:  Critical file transfer error
Status: Disconnected from server

Help please! :)
I'm trying to get in to the /var/www/ directory and add files here. Tried various types, and this is where I should upload my web server files.
I'm running Wheezy OS on my Raspberry Pi.

A:

It looks like your SSH user doesn't have write permission to /var/www, I'm guessing you are using pi@raspberrypi to connect SFTP. If you want to write there, you can simply run (assuming you have a user named www-data to represent your web server):

sudo chown -R www-data:www-data /var/www (This one gives /var/www to www-data user/group)
sudo chmod -R 664 /var/www/ (This one lets group users read/write, everyone else only read)
sudo usermod -aG www-data pi (Adds your user to www-data group)


Q:

Table replication in the same database

I would like to replicate a table (call this table source table) to a read-only table (call this table dest table) in the same database. I have only found information regarding publishing and subscribing across different databases. Is functionality to replicate a table in the same database supported in Microsoft SQL Server?
This need arises from the fact that we have a very complicated and not easy to change process that updates and inserts records into the source table, and since this process was created, we've developed a need to query the source table, which has caused intermittent conflicts (i.e. our process that updates the source table is temporarily blocked while other queries are running). And we need to avoid these blocks/delays to our process. Our queries on the source table are always lower priority.
All of the queries that run against the source table are queried on indexed columns for speed/efficiency and minimal table locking and most of the queries that are run against the source table are completed with (nolock) hint for the same reason. Yet we still encounter locking problems that delay our process that updates and inserts new records to the source table.
Based on everything I've read regarding transactional replication, this should allow us to query the dest table as much as we want without locking the source table. The problem with what I know about replication is that I would like my source table and dest table to reside in the same database.
Worst case, I can replicate the source table to another database on the same server and query across databases. I would prefer to avoid being forced to use two separate databases if there exists an option to complete this on the same database.

A:

If you don't mind your query table being somewhat behind your source table, why don't you create a stored procedure that:

Truncates the query only table.
Inserts your source table into your query only table.

Then just schedule a task to run your stored procedure every hour or however often you want to update your query table (ie, once every 4 hours, every 30 minutes, etc).
SQL Server is very fast at copying one table's contents into another table. Truncating your query only table first will be a very fast action in itself, and will prevent duplicate records. You might want to consider just dropping the query only table instead, and then letting SQL Server build the query only table as it inserts the contents of the source table. That is also quite fast. This select statement takes the form of Select * Into ReadOnlyTable From SourceTable. You can look up more information in your favorite search engine using the search term "SQL Select Into statement" (or just go over to http://www.w3schools.com/sql/sql_select_into.asp and read about it there if you don't want to be bothered with Googling it yourself).


Q:

PostgreSQL Replication

We constantly bat this around the office, and the question continues to come up. How do you deal with PostgreSQL replication? I'm not even necessarily talking about advanced clusters, just keeping it simple with Master-Slave, Master-MultiSlave, and Master-Master. I find that setting it up for MySQL is typically pretty simple. Failover is straightforward if not perfect, especially for how easy it is to configure. We've played with Slony, but it's a bit too hands on (schema changes require intervention, new databases require intervention, etc). PGPool2 was pretty nice, until a node went down and we couldn't find a graceful way (other than bringing everything down and reseeding the fallen node) to get replication back in sync. Basically here's what I'm typically looking for:

Easy setup (I'll settle for difficult setup, but easy to expand)
Simplistic failover
Bringing a fallen node back in just requires time (i.e. like mysql. Server goes down, you bring it up, and wait for replication to catch up)
Schema changes don't break replication
Adding a new database to the server is seamless (i.e. like mysql, you can replicate a whole DB server, so a new database is created on the master, it automatically propagates to the slave)

MySQL handles most of these fairly well, but I hold a certain fondness for PostgreSQL. Besides, we have some situations where it's our only option, and we'd like to add replication to the mix. What are you using currently, and how do you feel about your solution? This isn't a MySQL versus PostgreSQL post, I promise, because that's not what I'm trying to start. :)

A:

Short answer - there's no such solution yet for PostgreSQL if you need online readonly slaves.
There're two major development projects currently going on in this area which are included in PostgreSQL 9.0 (Spring/Summer 2010), namely:

Synchronous Replication:

http://wiki.postgresql.org/wiki/NTT's_Development_Projects

Read only hot standby slaves:

http://wiki.postgresql.org/wiki/Hot_Standby
which in combination aim to achieve the ease of use of MySQL-style replication minus the bugs/issues MySQL has plus the reliability users know from PostgreSQL.
All of this was kicked off by a manifest from the PostgreSQL Core Team in 2008:
http://archives.postgresql.org/pgsql-hackers/2008-05/msg00913.php
The PostgreSQL replication solutions to this day with the largest user base are Slony-I (more expensive for writes, makes schema changes fiddly), WAL shipping/walmgr (Slaves can't be used online) and pgQ/londiste from Skype/Skytools (more tools/building blocks than a finished solution).
I've written a few things on Log Shipping, walmgr and Slony-I, see
http://blogs.amd.co.at/mt/mt-search.cgi?blog_id=1&tag=pgrep&limit=20 for more information.

A:

And to throw another solution into the ring: rubyrep.
To compare with your requirements:

Easy setup
Yes, that's actually the primary focus of rubyrep.
Simplistic failover
Yes. In fact rubyrep does master-master replication - to fail over, no action is necessary at all. Just start using the other database.
Schema changes don't break replication
Yes.
For non-primary key changes replication doesn't even have to stop (but make sure the schema is changes on both sides at the same time)
To add / remove tables, simply restart the replication daemon.
Only changing the primary key column of a table takes a bit of effort.
Adding a new database to the server is seamless (i.e. like mysql, you can replicate a whole DB server, so a new database is created on the master, it automatically propagates to the slave)
This is only supported in a limited way: each rubyrep setup replicates only one database at a time. (But it is very easy to set up replication for more than one database.)

A:

You didn't mention having a hot read-slave as a requirement, so I'm going to propose using Heartbeat with either shared storage or DRBD. It just does the right thing and administration is a breeze. It's the Linux equivalent of older Microsoft SQL Server clustering. One node is active and the other node is passive while the data is shared between the two. You don't have to worry about SQL-based replication because it's all handled lower down at the block level.
Seriously, it's by far the best solution if you don't need read slaves. The WAL archive stuff was hokey at best and you must set everything up again if you ever disrupt the shipping process for a server reboot. slony and londiste don't cut the mustard. If you want to stay on the main source tree and not go commercial, Heartbeat is your best bet.


Q:

PHP Post Array Not Working (JSON)

I'm attempting to POST a JSON string that I grab from a MySql database to another php page. Here's my code for the parent page:
$ResultLists = array();
$counter = 0;
echo "<form target=\"_blank\" enctype=\"multipart/form-data\" method=\"post\" action=\"_popup.php\" name=\"compare\">";

while($data != NULL and $info = mysql_fetch_array( $data ))
{
Print "
";
//..
//I printed some data here, but not relevant to problem
//..
$ResultLists[$counter] = $info['ResultList']; //gets JSON string
echo gettype($ResultLists[$counter]); //prints "string"
//echo $ResultLists[$counter]; //prints the whole list (it is a list of lists <--from python)
$var = json_decode($ResultLists[$counter]); //decode JSON string
echo $var[1][0]; //prints wonderfully (I am only printing one value in "array", but it works).

Print '<input type="checkbox" name="data[]" value="'.$ResultLists[$counter].'" />	';
Print '
';
$counter++;
}
echo '
<input type="hidden" name="index" value="'.$counter.'" />';
echo '<input type="submit" value ="Compare Data"> </input>
';

On the child page, I try to get the data:
<?php

$index = $_POST['index'];
echo 'Number of rows: '.$index.'
';
$array = $_POST['data'];

$x = 0;

//echo gettype($array);

echo 'Type: '.gettype($array[$x]).'  Length: '.strlen($array[$x]).'  Data: '.$array[$x].'
';
$var = json_decode($array[$x]);
echo gettype($var).strlen($var);
echo $var[1][0];

?>

Which produces (for example)
Number of rows: 8
Type: string Length: 2 Data: [[
NULL0

So, it doesn't work. (It does this for every row of data I have submitted, so varying $x results in same output as long as its in the range of number of checkboxes I selected, if that makes sense.) Any ideas? Why does it show up as "[[" instead of the entire list? I can print the whole list on parent page and it works fine.
I have a suspicion its due to the presence of single quote " ' " characters, or something. Any ideas?
Edit:
So disabling magic quotes seems to have helped me post.
However, I'm having a strange issue, where it somehow submits all my data.
So when I get back data[] via POST, the length is the correct number of checkboxes that were checked, but the data it holds starts from the first row that is printed. Any ideas?

A:

You may probably want to escape the HTML characters in the json-ized string using htmlspecialchars. I.e.,
Print '<input type="checkbox" name="data[]" value="'.htmlspecialchars($ResultLists[$counter]).'" />	';


Q:

Kubernetes Readiness Probe in multi-tenant system

I am designing a system with a single kubernetes deployment for multiple tenants, but there are multiple databases, queues etc. per customer. Anything stateless is shared, and anything with state is separate for each tenant. Based on the request host (tenant1.company.com or tenant2.company.com), the code will connect to the corresponding databases and queues.
How should readiness probes be designed in this case, where my pod is designed to work for multiple tenants?
I can think of the following options, none of which seem correct:

Connect to all databases and queues and see if they are ready:
Disadvantage: this will cause pod to be not ready even if one
resource is down.
Connect to any one database and queue: Disadvantage: doesn't really check the readiness for all probes.
Do not have any readiness probe at all.

It feels like if I have separation at resources level to support multiple tenants (this is a B2B multi-tenant, takes time and effort to onboard new tenant), I also need to have separation at Kubernetes deployment level.
Is this the standard approach - either have complete separation at all levels, or have one single unified system with same shared resources? If not, how do I design the readiness probes?

A:

As per my understanding, you are trying to extend Kubernetes Pod's readiness probe to reflect Application health for specific tenant. Unfortunately, Readiness probe is not designed for that.
The only purpose of Kubernetes readiness probe (even the new feature Pod Ready++) is to reflect the certain Pod ability to serve the traffic. Deployment and StatefulSet controllers take into account Pod readiness state during the rolling-update process.
You can brake the whole update mechanics if you set the readiness probe to depend on external to the Pod components or a network endpoints connectivity.
 The correct way of using Readiness probe is to check only the Pod's internal components' conditions.
Kubernetes documentation pages:

Define readiness probes
Pod conditions and Container probes
Pod Ready++

For certain simple application or microservices that only contains one Pod, it may reflect also the state of the application. But usually, application architecture is much more complex and contains many parts, each of which may have dependencies.
Sometimes it's cheaper and simpler to create your own health check loop in the frontend app (www.example.com/healthz) that reflects the whole App health, taking to account all its components statuses and their dependencies, or collect and aggregate JSON statuses from other components.
In Kubernetes world, components/apps are usually Services that balance the traffic to one or more Pods. Thus, a component is healthy if at least one Pod behind the corresponding Service is in Ready state. The number of Ready Pods behind the Service tells more about App Performance, than about the App Health.
As per my ability to imagine your App design:

I would use several Ingress objects that make the traffic to be forwarded to the dedicated for each tenant frontend, in the tenant's Namespace. All other tenant's resources are also deployed there.
All shared components I would put in the additional Namespace, let's say "shared/static/commmon/stateless" and create ExternalName service in each tenant's Namespace to access them (or Ingress if I would serve this content on a specific URL path).
I would also deploy some solution for Application+cluster monitoring.

This way you can easily scale application parts if some tenant needs more resources.
To manage deployments I would use Helm charts. This way I can easily deploy one more tenant or remove/update the existing one.
There are many different solutions to monitor an Application Health, Performance, collect metrics and logs and take actions if certain conditions are met. It's just a brief list of most popular solutions:

Metrics Framework (Java)
Prometheus
EFK stack
Jaeger
Istio
Weave Scope
Datadog Realtime Kubernetes Monitoring
Cloud specific tools like Google Cloud's operations suite (formerly Stackdriver)
many more...

PS: In case you want to implement a circuit breaker for the tenants, Istio has built-in functionality.


Q:

Is kafka streaming driver waiting for executors to finish?

I have a spark streaming application that monitors some messages from kafka. For a specific message I may need to go to a long loop to continue pinging some ip until its reconnected.
What I can see that when some executor goes to this loop, it stops processing the stream.
Is it correct ?
How can I make this loop without interrupting continuing processing the stream ?

A:

Yes, the executors will not progress if they are blocked on a long-running task.
I would advise against running such long process on an executor. Assuming that those reconnect cases are sparse in time, I would use an asynchronous process in the driver. (Futures or barebone threads from a pool).


Q:

How to modify the Imagenet Caffe Model?

I would like to modify the ImageNet caffe model as described bellow:

As the input channel number for temporal nets is different from that
  of spatial nets (20 vs. 3), we average the ImageNet model filters of
  first layer across the channel, and then copy the average results 20
  times as the initialization of temporal nets.

My question is how can I achive the above results? How can I open the caffe model to be able to do those changes to it?
I read the net surgery tutorial but it doesn't cover the procedure needed.
Thank you for your assistance!
AMayer

A:

The Net Surgery tutorial should give you the basics you need to cover this. But let me explain the steps you need to do in more detail:

Prepare the .prototxt network architectures: You need two files: the existing ImageNet .prototxt file, and your new temporal network architecture. You should make all layers except the first convolutional layers identical in both networks, including the names of the layers. That way, you can use the ImageNet .caffemodel file to initialize the weights automatically.
As the first conv layer has a different size, you have to give it a different name in your .prototxt file than it has in the ImageNet file. Otherwise, Caffe will try to initialize this layer with the existing weights too, which will fail as they have different shapes. (This is what happens in the edit to your question.) Just name it e.g. conv1b and change all references to that layer accordingly.

Load the ImageNet network for testing, so you can extract the parameters from the model file:
net = caffe.Net('imagenet.prototxt', 'imagenet.caffemodel', caffe.TEST)

Extract the weights from this loaded model.
conv_1_weights = old_net.params['conv1'][0].data
conv_1_biases = old_net.params['conv1'][1].data

Average the weights across the channels:
conv_av_weights = np.mean(conv_1_weights, axis=1, keepdims=True)

Load your new network together with the old .caffemodel file, as all layers except for the first layer directly use the weights from ImageNet:
new_net = caffe.Net('new_network.prototxt', 'imagenet.caffemodel', caffe.TEST)

Assign your calculated average weights to the new network
new_net.params['conv1b'][0].data[...] = conv_av_weights
new_net.params['conv1b'][1].data[...] = conv_1_biases

Save your weights to a new .caffemodel file:
new_net.save('new_weights.caffemodel')


Q:

McStackIconOverflow

Is it just me or does the top menu have too many burgers for a healthy diet nowadays?
The new one at the left seems a bit Wimpy compared to the others.

(Good buns puns may be upvoted and relished.)

A:

You must be hungry.
I only see one burger icon in your picture.
From right to left...

The icon over on the right has been the icon of the larger Stack Exchange network for...quite some time now.  Its design has been emblematic and would be tough to mistake for a burger icon.

The review icon was the result of a lengthy discussion about what the heck the original icon was meant to be.  It's really not meant to be a menu at all, but an actual icon.
Stack Overflow's icon may have shrunk over the years (the number of lines has dropped from 6 to 5), but...I have a tough time thinking of that as a burger.
The last burger menu actually is a burger.  Looks delicious good on mobile.


Q:

Check if two Location Instances are the same value?

I want to check if two location instances are the same value. I'm just not sure how to do this?
I get the first location by using a service to constantly check the location in the background. The second Location instance is declared within an activity and i use a getAddress() method to recieve the address from the location it found.
I thought maybe something like this might work but it didn't:
  // Initialization of First Location
    LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
    Location FirstLocation =mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    //Initialization of Second Location
     Location SecondLocation = LocationServices.FusedLocationApi
            .getLastLocation(mGoogleApiClient);

    //Checking if they are the same

    if (FirstLocation ==SecondLocation){
        System.out.println("It worked");
    }
    else{
        System.out.println("It didn't work");
    }

It always returns "It didn't work".
Just wondering how I can solve this or if theres a better way?
Any feedback or answers would be most appreciated!

A:

Maybe try to use distanceTo() method it returns the approximate distance in meters between to locations, something similar to  :
SecondLocation.distanceTo(FirstLocation) < 1;

Hope this helps


Q:

How to send mail in hotmail using Python?

Is there a way to login my hotmail account and send mails with a Python program?

A:

You can try using their SMTP server:

User name: Your Windows Live ID, for example yourname@hotmail.com
Password: The password you usually use to sign in to Hotmail or Windows Live
SMTP server: smtp.live.com (Port 25) {Note: If port 25 has been blocked in your network or by your ISP, you can set SMTP port to 587 with TLS or SSL Encryption depending on the client in use}
Authentication required? Yes (this matches your POP username and password)
TLS/SSL required? Yes

Use smtplib to send mail. You can find some examples here.


Q:

Talend : tExtractRegexFields and globalMap

My job is composed like that :
tRest >> tExtractJSonFields >> ttExtractRegexFields > (row3) > tMSSqlRow
I'm using a tExtractRegexFields compenent with 3 output variables.
The next component is a tMSSqlRow.
I would like to use tExtractRegexFields's output in my SQL query as a parameter.
My SQL Query is like that :
;WITH nums AS
   (SELECT 1 AS PAGE
    UNION ALL
    SELECT PAGE + 1 AS value
    FROM nums
    WHERE nums.PAGE < "+(Integer)globalMap.get("row3.lastpage")")
INSERT INTO flight.Calendar_Page (DT_CAL, NUM_PAGE)
SELECT '2016-01-01', PAGE
FROM nums
option (maxrecursion 32767);"
"row3.lastpage" is a tExtractRegexFields's output variable.
This one is always contain NULL value.
I don't understand why globalMap.get("row3.lastpage") is null. Anyone knows how to use tExtractRegexFields's outputs ?
Thank you all

A:

Do not use globalMap.get("row3.lastpage") in the SQL query in your tMSSqlRow, but simply concatenate row3.lastpage with your SQL string. And row3.lastpage is not a string, but row3 is a Java class in the Talend generated code and lastpage is one of its fields. This field contains the data you want to inject into the SQL statement.
globalMap.get("row3.lastpage") will always by null.
Your query should be something like:
WITH nums AS (SELECT 1 AS PAGE UNION ALL SELECT PAGE + 1 AS value FROM nums WHERE nums.PAGE < " + row3.lastpage + ") INSERT INTO flight.Calendar_Page (DT_CAL, NUM_PAGE) SELECT '2016-01-01', PAGE FROM nums option (maxrecursion 32767);


Q:

principal component analysis (PCA) in R: which function to use?

Can anyone explain what the major differences between the prcomp and princomp functions are?
Is there any particular reason why I should choose one over the other? In case this is relevant, the type of application I am looking at is a quality control analysis for genomic (expression) data sets.
Thank you!

A:

There are differences between these two functions w/r/t

the function parameters (what you can/must pass in when you call the
function);
the values returned by each; and
the numerical technique used by each to calculate principal
components.

Numerical Technique Used to Calculate PCA
In particular, princomp should be a lot faster (and the performance difference will increase with the size of the data matrix) given that it calculates principal components via eigenvector decomposition on the covariance matrix, versus prcomp which calculates principal components via singular value decomposition (SVD) on the original data matrix.
Eigenvalue decomp is only defined for square matrices (because the the technique is just solving the characteristic polynomial) but that's not a practical limitation because the eigenvalue decomp always involves the predicate step of calculating from the original data matrix, the covariance matrix.
Not only is the covariance matrix square, but is is usually much smaller than the original data matrix (as long as the number of attributes is less than the number of rows, or n < m, which is true in most of the time.
The former (eigenvector decomp) is less accurate (the difference is often not material), but much faster because computation is performed on the covariance matrix rather than on the original data matrix; so for instance, if the data matrix has the usual shape such that n >> m, i.e., 1000 rows and 10 columns, then the covariance matrix is 10 x 10; by contrast prcomp calculates SVD on the original 1000 x 10 matrix.
I don't know the shape of data matrices for genomic expression data, but if the rows are in the thousands or even hundreds, then prcomp will be noticeably slower than princomp. I don't know your context, eg, whether pca is performed as a single step in a larger data flow and whether net performance (execution speed) is of concern, so i can't say whether this performance is indeed relevant for your use case. Likewise, it's difficult to say whether the difference in numerical accuracy between the two techniques is significant and in fact it depends on the data.

Return Values
princomp returns a list comprised of seven items; prcomp returns a list of five.
> names(pc1)    # prcomp
    [1] "sdev"     "rotation" "center"   "scale"    "x"

> names(pc2)    # princomp
    [1] "sdev"     "loadings" "center"   "scale"    "n.obs"    "scores"   "call"

For princomp, the most important items returnd are component scores and loadings.
The values returned by the two functions can be reconciled (compared) this way: prcomp returns, among other things, a matrix called rotation which is equivalent to the loadings matrix returned by princomp.
if you multiply prcomp's rotation matrix by the original data matrix the result is stored in the matrix keyed to x
finally, prcomp has a plot method which gives a scree plot (shows the relative and cumulative importance of each variable/column--the most useful visualization of PCA in my opinion).

Function Arguments
prcomp will scale (to unit variance) and mean center your data for you if you set to TRUE the arguments scale and center. That's a trivial difference between the two given that you can both scale and mean center your data in a single line using the scale function.


Q:

Parallelizing ant like GNU Make?

I need to execute multiple ant tasks. They haven't to run in the same JVM, a gnu make-like fork()-ed execution is this time perfect(*).
But, what I need, it were a functionality with the gnu make can with the -j flag: I need to be able to limit the maximal number of tasks running parallel. It is the main problem, in my current tries (subant task) I didn't find any option for that.
So, is there a solution for the problem? I really won't call a gnu make with an exec task...
(*) Yes, I know it is ineffecient, please don't worry because of that. In normal circumstances I also prefer a multithreaded solution, but now there are special circumstances.

A:

You can use the <parallel> task in ant, the doc's describe it as this:

Executes nested tasks in parallel with no guarantees of thread safety. Every task will run in its own thread, with the likelihood of concurrency problems scaling with the number of CPUs on the host system.

Example (from their docs):
<parallel threadCount="4">
  <dbpurge file="db/one" />
  <dbpurge file="db/two" />
  <dbpurge file="db/three" />
  <dbpurge file="db/four" />
  <dbpurge file="db/five" />
  <dbpurge file="db/six" />
  <dbpurge file="db/seven" />
  <dbpurge file="db/eight" />
  <!-- repeated about 40 times -->
</parallel>


Q:

How secure is a simple sessions-cookies authentification system?

Is the top-voted answer given here secure?
As far as I can tell, the communications are not encrypted. Any other holes need to be patched for a truly secure authentification system?

A:

In Express, sessions use cookies to make a connection between a browser and the database. The cookie is encrypted using a secret key you set in the application. If you are interested, this is the code used to encrypt the cookie: https://github.com/senchalabs/connect/blob/master/lib/utils.js#L158-163
If you are afraid that somebody on the network can sniff the traffic, then you should use HTTPS, and if you're even more paranoid you can encrypt the data again client-side and unencrypt it server-side using Stanford Javascript Crypto Library.


Q:

Why is Barium Phosphate soluble in dil HCl?

Why is Barium Phosphate soluble in dil HCl
While Barium Sulphate is not?

A:

Many phosphates are not soluble in water at standard temperature and pressure, except for the sodium, potassium, rubidium, cesium, and ammonium phosphates, which are all water-soluble. As a rule, the hydrogen and dihydrogen phosphates are slightly more soluble than the corresponding phosphates (Wikipedia). For example, based on Wikipedia Solubility Table, the solubility of $\ce{BaHPO4}$ is $\pu{0.013 g}$ in $\pu{100 mL}$ at $\pu{20 ^{\circ}C}$, and a CDC.gov Report states that:

The water solubility of barium compounds increases with decreasing $\mathrm{pH}$.

Nevertheless, the solubility studies of the phosphates of strontium, barium, and magnesium have been done previously (Ref.1). Alkaline earth phosphates as a whole have been reviewed as well (Ref.2).
That said, let's look at phosphates behaviour with $\mathrm{pH}$. The three $\mathrm{p}K_\mathrm{a}$ values for phosphoric acid are 2.16, 7.21, and 12.32. Thus, aqueous phosphate exists in four forms (Wikipedia):

In strongly basic conditions, the phosphate ion ($\ce{PO4^3-}$) predominates.
In weakly basic conditions, the hydrogen phosphate ion ($\ce{HPO4^2-}$) is prevalent.
In weakly acidic conditions, the dihydrogen phosphate ion ($\ce{H2PO4-}$) is most common.
In strongly acidic conditions, trihydrogen phosphate ($\ce{H3PO4}$) is the main form.

When dilute $\ce{HCl}$ (say $\pu{3 M}$ and hence $\mathrm{pH} \approx -0.48$) is added to solid $\ce{Ba3(PO4)2}$, following reactions will occur with aqueous hydronium ions:
$$\ce{Ba3(PO4)2(s) + nH2O(l) <=>  3Ba^2+(aq) + 2PO4^3-(aq)}$$
$$\ce{PO4^3-(aq) + H3O+(aq) ->  HPO4^2-(aq) + H2O(l)}$$
$$\ce{HPO4^2-(aq) + H3O+(aq) ->  H2PO4-(aq) + H2O(l)}$$
$$\ce{H2PO4-(aq) + H3O+(aq) ->  H3PO4(aq) + H2O(l)}$$
Because, $\mathrm{pH}$ of the acid solution  is lower than the $\mathrm{p}K_\mathrm{a1}$ of the $\ce{H3PO4}$ acid, $\ce{Ba3(PO4)2}$ solid would slowly dissolve to give $\ce{H3PO4(aq)}$ and $\ce{BaCl2(aq)}$ in the solution (Channel Le Chatelier's principle).
However, this phenomenon would not happen with $\ce{BaSO4}$ solid because $\mathrm{p}K_\mathrm{a1}$ of $\ce{H2SO4}$  is about $-3$, which is much lower than the operating $\mathrm{pH}$. Therefore, since $\mathrm{p}K_\mathrm{a2}=1.99$ for $\ce{H2SO4}$, it is possible to form  $\ce{Ba(HSO4)2}$, yet its solubility is said to be low as well ($\approx \pu{0.015 g}$ in $\pu{100 mL}$ of water at $\pu{25 ^{\circ}C}$).
References:

L. E. Holt, Jr., J. A Pierce, C. N Kajdi, “The solubility of the phosphates of strontium, barium, and magnesium and their relation to the problem of calcification,” Journal of Colloid Science 1954, 9(5), 409–426 (https://doi.org/10.1016/0095-8522(54)90029-X).
R. W. Mooney, M. A. Aia, “Alkaline Earth Phosphates,” Chem. Rev. 1961, 61(5), 433–462 (DOI: 10.1021/cr60213a001).


Q:

Do black, brown/grizzly or polar bears ever prey on humans?

Do bears, as opposed to defending cubs, being startled by humans, or trying to get into food, ever decide to prey on humans?
As in stalk, kill and then eat them?

A:

TLDR: While rare, it definitely happens.
In fact the majority of people killed by black bears in North America were killed by aggressive bears not by say surprised bears or mothers defending their cubs.

The study found that 63 people were killed in 59 incidents in Canada, Alaska and the lower 48 states. The researchers determined that the majority (88%) of fatal attacks involved a bear exhibiting predatory behaviour, and 92% of the predatory bears were males. The authors suggest male black bears have evolved some different behaviours than females.

Source

We judged that the bear involved acted as a predator in 88% (49 of 56) of fatal incidents. Adult (n = 23) or subadult (n = 10) male bears were involved in 92% (33 of 36) of fatal predatory incidents, reflecting biological and behavioral differences between male and female bears. That most fatal black bear attacks were predatory and were carried out by 1 bear shows that females with young are not the most dangerous black bears.

Source

Ken Marsh, a spokesman for the Alaska Department of Fish and Game, said the animal responsible for the attack was an adult male black bear. The carcass of the animal, which mine officials said was shot at the scene, was retrieved.
A preliminary examination of the case, Marsh said, appeared to rule out any sign that the mauling was the result of a surprise encounter or a defensive attack by the bear.
"Initial indications, the information we have, are consistent with a predatory attack," Marsh said.
...
Murphy, the ABR president, said employees told him the fatal mauling involved an "extremely aggressive, predatory black bear."
"The bear appears to have stalked them," Murphy said the employees told him. "It came up from behind them and attacked."

Source

WEST MILFORD, N.J. — Authorities say the first known fatal bear attack in New Jersey was unprovoked and the bear was acting in a "predatory" manner.
Officials attribute the death of a 22-year-old Rutgers University student from Edison to "mauling."

Source

Rancher Sevend (Sven) Satre might have been able to provide some answers to these questions if he were still alive. On June 14, 1996, the 53-year-old man was riding his horse, checking on his cattle in the timbered country near the central British Columbia community of Tatlayoko Lake. He never returned. Satre's partially eaten body was located the next morning and an aggressive black bear was dispatched at the gruesome site by the search party. A necropsy performed on the bear proved that indeed it was the man-eater. Interestingly, it was in perfect health.
By all indications, the bear had stalked Satre and his horse for more than half a mile before rushing in for the kill. The horse and rider had only just begun to react to the attack when Satre's saddle rolled after a tight left turn and he was thrown to the ground. Trackers concluded that Satre fought off the predatory black bear for less than 10 seconds before he was overpowered and killed. His axe was found at the site where the one-sided fight took place.

Source
Grizzly bears will also prey on people,

The man, who isn't being named by conservation officers, was moose calling with a hunting partner along the Smart River in northern B.C. on Wednesday, when a female grizzly attacked him from behind.

Conservation officers say the attack was predatory, meaning the bear wanted to eat the man.
Source

Predatory attacks by bears are very rare, but do occur.  Any bear that continues to approach, follow, disappear and reappear or displays other stalking behaviors is possibly considering you as prey.  Bears that attack you in your tent or confront you aggressively in your campsite or cooking area should also be considered a predatory threat.

Source
Polar bears will also prey on humans

Atwood was a member of a team that combed through nearly 150 years of records of bear attacks in Canada, Greenland, Russia, the US and Norway. They drew their data from government agencies, news reports and, in the older cases, from ships’ logs.
Between 1870 and 2014, they found 73 cases of polar bears attacking a group of people or an individual, with 63 people injured and 20 people dead. Bears were acting in a predatory manner in most attacks, and it was male bears that were more often involved.
Where details were available, the researchers assigned the attacking bear a score reflecting its body condition. It turned out that 61 per cent of these bears were in “below average” condition – a situation Atwood says is down to them not finding as much food because of dwindling time on sea ice, their habitual seal hunting ground.

Source
The last thing to note is that while people say that polar bears are the only animals that hunt humans, this is not true, since black bears and brown bears will do it as well.


Q:

Postgresql. Получение результата now() - timestamp в миллисекундах

Создал таблицу:
create table test(id integer,buf integer, start timestamp);

Вставил строку:
insert into test values(1,100,now());

Теперь мне как-то нужно получить разность текущего времени и времени, записанного в столбце start по id, результат типа integer.
Выяснил, что текущее время в миллисекундах типа double могу получить с помощью запроса select extract(from epoch now()); Далее у меня никак получается релиазовать задуманное. Пробывал нечто подобное:
select extract(epoch from st (select start as st from test where id=1)) as foo;

A:

Разницу между двумя датами можно получить простым вычитанием, такой оператор предоставляется в postgresql. Результатом будет значение типа interval, так же подходящее для использования в функции extract.
select extract(epoch from now() - "start") * 1000 as msdiff
from test;

extract epoch обозначает время в секундах, следовательно для значения в микросекундах его необходимо умножить на 1000.
Для перевода значения в int выберите подходящий вам способ округления double и приведите его к int:
select round(extract(epoch from now() - "start") * 1000)::int as msdiff
from test;

Возможно использовать round для математического округления, trunc для отбрасывания дробной части, ceil и floor для округления вверх и вниз соответственно.


Q:

Akka.Net Remoting: ActorSelection vs. IActorRef

Using Akka.net with remoting.  This article has the following to say about using ActorSelection:

The other time when I tend to use an ActorSelection is when I am
  initially communicating with a remote actor system.

What I don't quite understand is how to convert that initial ActorSelection into an IActorRef that I can continue to use.

A:

The simplest way here is to use actorSelection.ResolveOne(timeout) method, which will return Task<IActorRef>. Task may also end with timeout or ActorNotFoundException in case when no actor was found under provided path.
Another - more actor-idiomatic - way is to send Identify(correlationId) message to actor selection. It should respond with ActorIdentity(correlationId, actorRef) reply. Be aware that it may not respond at all, if there was no one to listen under provided actor selection.


Q:

What is the name of this Monad Stack function?

I've got a bunch of stateful functions inside a State monad. At one point in the program there needs to be some IO actions so I've wrapped IO inside a StateT getting a pair of types like this:
mostfunctions :: State Sometype a
toplevel :: StateT Sometype IO a

To keep things simple I don't want pass the IO context into the main set of functions and I would like to avoid wrapping them in the monad stack type. But in order to call them from the toplevel function I need something akin to a lift, but I'm not trying to lift a value from the inner monad. Rather I want to convert the state in the StateT monad into something equivalent in the State monad. To do this I've got the following:
wrapST :: (State Sometype a) -> StateT Sometype IO a
wrapST f = do s <- get
              let (r,s2) = runState f s
              put s2
              return r

This then get used to interleave things like the following:
toplevel = do liftIO $ Some IO functions
              wrapST $ Some state mutations
              liftIO $ More IO functions
              ....

It seems like a fairly obvious block of code so I'm wondering does this function have a standard name, and it is already implemented somewhere in the standard libraries? I've tried to keep the description simple but obviously this extends to pulling one transformer out of a stack, converting the wrapped value to the cousin of the transformer type, skipping the monads below in the stack, and then pushing the results back in at the end.

A:

It may be a good idea to refactor your code to use the type StateT SomeType m a instead of State SomeType a, because the first one is compatible to an arbitrary monad stack. If you'd change it like this, you don't need a function wrapST anymore, since you can call the stateful functions directly.
Okay. Suppose you have a function subOne :: Monad m => State Int Int:
subOne = do a <- get
            put $ a - 1
            return a

Now, change the types of all functions like this one from State SomeType a to StateT SomeType m a, leaving m as is. This way, your functions can work on any monadic stack. For those functions, that require IO, you can specify, that the monad at the bottom must be IO:
printState :: MonadIO m => StateT Int m ()
printState = do a <- get
             liftIO $ print a

Now, it should be possible to use both functions together:
-- You could use me without IO as well!
subOne :: Monad m => StateT Int m ()
subOne = do a <- get
            put $ a - 1

printState :: MonadIO m => StateT Int m ()
printState = do a <- get
             liftIO $ print a

toZero :: StateT Int IO ()
toZero = do subOne     -- A really pure function
            printState -- function may perform IO
            a <- get
            when (a > 0) toZero

PS: I use GHC 7, some of the libs changed midway, so it might be a bit different on GHC 6.

A:

A more direct answer to your question: the function hoist does exactly what you're describing in a slightly more generic way. Example usage:
import Control.Monad.State
import Data.Functor.Identity
import Control.Monad.Morph

foo :: State Int Integer
foo = put 1 >> return 1

bar :: StateT Int IO Integer
bar = hoist (return . runIdentity) foo

hoist is part of the MFunctor class, which is defined like this:
class MFunctor t where
  hoist :: Monad m => (forall a. m a -> n a) -> t m b -> t n b

There are instances for most monad tranformers, but not ContT.


Q:

readonly fields rule in infopath 2013

We have a new requirement to disable all fields in InfoPath form based the dropdown control selection.
please help me out

A:

There is no direct read-only rule. Meanwhile, you can achieve that by creating a format rule for each control you need to disable it as the following

Click on your dropdown control.
from the above ribbon > add rule > is equal to or based on your requirements > and select any option below formatting section.

Now set your field that you need to disable.
in the rule properties check disable this control.


Q:

« So far, so good » en français

Comment est-ce que je peux dire « so far, so good » en français ? « Jusqu'ici tout va bien » est la  meilleure traduction ?
Si quelqu'un ne sait pas ce que « so far, so good » signifie : c'est une expression qui veut dire « tout était bien jusqu'à présent mais à partir de maintenant peut-être ce ne sera plus bien ».

A:

Réponse courte : oui. « Jusqu'ici, tout va bien » correspond bien au sens général de « So far, so good » et donne la même impression de langage parlé. Dans certains contextes, on remplace parfois «va bien» par un verbe plus explicite, par exemple :

« Jusqu'ici, c'est clair ? » (un professeur explique quelque chose)

Mais « Jusqu'ici, tout va bien » peut s'utiliser dans tous les cas, je pense.
Aussi en version interrogative : « Jusqu'ici, tout va bien ? » (« So far, so good ? »)
Et en version plus familière : « Jusqu'ici, ça va ».


Q:

Shell Script Image Replication

I have a shell script which is being used on an embedded human machine interface (HMI). This script is used to copy a few files from a USB stick to a different place on the device, but with multiple instances of the same file under different names.
If it helps:

OS is Unix-like (BusyBox v1.11.2)
Commands available are located here
The filesystem is JFFS2

Any thoughts on improvements/optimizations would be appreciated.
#! /bin/sh
echo "
****Project Customisation Daemon STARTING****
"
echo "Main Background:"
# First, check the new image exists
if [ -s "/disk/usbsda1/New_Main.png" ]
then
   echo " -> Found new file to be used!"
   # Check if our directory is already present
   if [ -d "/opt/pclient/projekte/Main/" ]
   then
      # If our directory exists, remove the files
      echo " -> Found old directory, removing contents!"
      rm -rf /opt/pclient/projekte/Main/*
   else
      # If the directory isnt present, create it!
      echo " -> Creating new directory!"
      mkdir -p /opt/pclient/projekte/Main/
   fi
   # Now copy our files!
   echo " -> Copying new files, please wait!"
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page2.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page3.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page4.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page5.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page6.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page7.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page8.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page9.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page10.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page11.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page12.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page13.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page14.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page15.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page16.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page17.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page18.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page19.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page20.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page21.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page22.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page23.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page24.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page25.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page26.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page27.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page28.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page29.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page30.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page31.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page32.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page33.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page34.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page35.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page36.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page38.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page62.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page63.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page64.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page65.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page66.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page67.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page68.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page69.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page610.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page611.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page615.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page616.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page618.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page619.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page620.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page621.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page622.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page623.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page624.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page626.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page627.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page628.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page629.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page630.png
   cp /disk/usbsda1/New_Main.png /opt/pclient/projekte/Main/Main_Page631.png
else
   echo " -> Could not find new image to use, skipping!"
fi

# Inform the user that the files have been created
echo " -> All background images created!"
echo " -> Now copying to project folder!"
# move the files into the appropriate place
cp /opt/pclient/projekte/Main/* /opt/pclient/projekte/default_prj/terminal_files/

# Next we need to create copies of any additional images we will need
echo "Help Pages:"
# First, check the new image exists
echo " -> Now creating Help logos"
if [ -s "/disk/usbsda1/New_Help.png" ]
then
   echo " -> Found new file to be used!"
   # Check if our directory is already present
   if [ -d "/opt/pclient/projekte/Help/" ]
   then
      # If our directory exists, remove the files
      echo " -> Found old directory, removing contents!"
      rm -rf /opt/pclient/projekte/Help/*
   else
      # If the directory isnt present, create it!
      echo " -> Creating new directory!"
      mkdir -p /opt/pclient/projekte/Help/
   fi
   # Now copy our files!
   echo " -> Copying new files, please wait!"
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page.png
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page2.png
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page3.png
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page4.png
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page5.png
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page6.png
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page7.png
   cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page8.png
else
   echo " -> Could not find new image to use, skipping!"
fi

# Inform the user that the files have been created
echo " -> Applying changes to project!"
# move the files into the appropriate place
cp /opt/pclient/projekte/Help/* /opt/pclient/projekte/default_prj/terminal_files/
echo "Icon Pages:"
# Check the new Icon pages exists
echo " -> Now creating Icon logos"
if [ -s "/disk/usbsda1/New_Icon.png" ]
then
   echo " -> Found new file to be used!"
   # Check if our directory is already present
   if [ -d "/opt/pclient/projekte/Icon/" ]
   then
      # If our directory exists, remove the files
      echo " -> Found old directory, removing contents!"
      rm -rf /opt/pclient/projekte/Icon/*
   else
      # If the directory isnt present, create it!
      echo " -> Creating new directory!"
      mkdir -p /opt/pclient/projekte/Icon/
   fi
   # Now copy our files!
   echo " -> Copying new files, please wait!"
   cp /disk/usbsda1/New_Icon.png /opt/pclient/projekte/Icon/Icon_Page.png
   cp /disk/usbsda1/New_Icon.png /opt/pclient/projekte/Icon/Icon_Page2.png

else
   echo " -> Could not find new image to use, skipping!"
fi

# Inform the user that the files have been created
echo " -> Applying changes to project!"
# move the files into the appropriate place
cp /opt/pclient/projekte/Icon/* /opt/pclient/projekte/default_prj/terminal_files/

echo "Additional Logos:"
# Check the new logo page exists
echo " -> Now creating Logo"
if [ -s "/disk/usbsda1/New_Logo.png" ]
then
   echo " -> Found new file to be used!"
   # Check if our directory is already present
   if [ -d "/opt/pclient/projekte/Logo/" ]
   then
      # If our directory exists, remove the files
      echo " -> Found old directory, removing contents!"
      rm -rf /opt/pclient/projekte/Logo/*
   else
      # If the directory isnt present, create it!
      echo " -> Creating new directory!"
      mkdir -p /opt/pclient/projekte/Logo/
   fi
   # Now copy our files!
   echo " -> Copying new files, please wait!"
   cp /disk/usbsda1/New_Logo.png /opt/pclient/projekte/Logo/Logo2.png
else
   echo " -> Could not find new image to use, skipping!"
fi

# Inform the user that the files have been created
echo " -> Applying changes to project!"
# move the files into the appropriate place
cp /opt/pclient/projekte/Logo/* /opt/pclient/projekte/default_prj/terminal_files/

# Next we need to copy the boot logo and startup screen logo
echo "Boot Logos:"
# First, check the new image exists
echo " -> Now creating boot logos"
if [ -s "/disk/usbsda1/New_Boot.png" ]
then
   echo " -> Found new file to be used!"
   # Check if our directory is already present
   if [ -d "/opt/pclient/projekte/Boot/" ]
   then
      # If our directory exists, remove the files
      echo " -> Found old directory, removing contents!"
      rm -rf /opt/pclient/projekte/Boot/*
   else
      # If the directory isnt present, create it!
      echo " -> Creating new directory!"
      mkdir -p /opt/pclient/projekte/Boot/
   fi
   # Now copy our files!
   echo " -> Copying new files, please wait!"
   cp /disk/usbsda1/New_Boot.png /opt/pclient/projekte/Boot/loading_screen.png
else
   echo " -> Could not find new image to use, skipping!"
fi

# Inform the user that the files have been created
echo " -> Applying changes to project!"
# move the files into the appropriate place
cp /opt/pclient/projekte/Boot/* /opt/pclient/projekte/default_prj/terminal_files/additional_files
setbootlogo /opt/pclient/projekte/default_prj/terminal_files/additional_files/loading_screen.png

echo "Wrapping up:"
# Fully tidy up, by removing any un needed file paths
echo " -> Removing un-needed files!"
rm -rf /opt/pclient/projekte/Main/*
rm -rf /opt/pclient/projekte/Boot/*
rm -rf /opt/pclient/projekte/Help/*
rm -rf /opt/pclient/projekte/Icon/*
rm -rf /opt/pclient/projekte/Logo/*
echo " -> Removing un-needed directories!"
rmdir /opt/pclient/projekte/Main
rmdir /opt/pclient/projekte/Boot
rmdir /opt/pclient/projekte/Help
rmdir /opt/pclient/projekte/Icon
rmdir /opt/pclient/projekte/Logo

echo "
****Project Customisation Daemon COMPLETE****
"

A:

A few comments.  You make many copies of the files but JFFS2 seems to support hard links, so I would use links instead (see man ln and the ln command in the example below).  Also you copy all files into temporary directories and then copy them to the target directory.  This is unnecessary - just copy one file to the target directory and then link that to the necessary target file names.
I would probably write it using a loop, if your shell allows that.  And I would pass the source and maybe target directories into the script, so you would call it as:
myscript /disk/usbsda1/  /opt/pclient/projekte/default_prj/terminal_files/

My scripting is rusty, but here is a naive script using a loop.  Script experts can doubtless improve this.  Note that the -x on the first line causes the shell to print each command as it is executed.
#! /bin/sh -x

DISK=$1
TARGET=$2

copy_files()
{
    # called as: copy_files sourcedir sourcefile destdir destfile1 destfile2 ...
        SRCDIR=$1
        SRC=$2
        DESTDIR=$3
        shift; shift; shift
        cp $SRCDIR/$SRC $DESTDIR
        for f in $@
        do
                ln $DESTDIR/$SRC $DESTDIR/$f
        done
        rm $DESTDIR/$SRC
}

copy_files $DISK New_Main.png $TARGET Main_Page.png \
    Main_Page2.png \
    Main_Page3.png

A:

Extract repeated values to variables
The most important thing is to avoid copy-pasting absolute paths everywhere. If the path ever changes it's a hassle to replace all strings in the script. It also makes it difficult to test the script with dummy directories instead of the real ones. So, always constants in variables, for example:
SRCDIR=/disk/usbsda1
WORKDIR=/opt/pclient/projekte
DSTDIR=/opt/pclient/projekte/default_prj/terminal_files

Similarly, when using these constants repeatedly, it's good to introduce a temporary variable to capture the common element. For example, instead of this:
cp "$SRCDIR"/New_Main.png "$WORKDIR"/Main/Main_Page.png
cp "$SRCDIR"/New_Main.png "$WORKDIR"/Main/Main_Page2.png
cp "$SRCDIR"/New_Main.png "$WORKDIR"/Main/Main_Page3.png

I would do like this:
IMAGE="$SRCDIR"/New_Main.png
DIR="$WORKDIR"/Main
cp "$IMAGE" "$DIR"/Main_Page.png
cp "$IMAGE" "$DIR"/Main_Page2.png
cp "$IMAGE" "$DIR"/Main_Page3.png

These kind of extractions to variables make the script more flexible, as you can change a path in one place and it will affect all the places where it's used. Another good thing is that a variable serves as a label of the purpose, the intention, which can be often more descriptive than the actual hardcoded string.
A note about quoting
I didn't quote SRCDIR=/disk/usbsda1 because it's unnecessary. But afterwards I quote "$SRCDIR" everywhere, in case "somebody" might ever set SRCDIR to a path with spaces. This is good precaution. Finally, these are equivalent:
cp "$IMAGE" "$DIR"/Main_Page.png
cp "$IMAGE" "$DIR/Main_Page.png"

Extract repeated logic to functions
In the processing each of the image types, you use the same kind of logic to check if a directory exists and remove its contents, or else create the directory. This could be in a function:
prepare_dir() {
    DIR=$1
    if [ -d "$DIR" ]
    then
        echo " -> Found old directory, removing contents!"
        rm -rf "$DIR"/*
    else
        echo " -> Creating new directory!"
        mkdir -p "$DIR"
    fi
}

You can call this with prepare_dir "$WORKDIR"/Main, prepare_dir "$WORKDIR"/Help, prepare_dir "$WORKDIR"/Logo, and so on, reducing duplication and shortening your code.
Excessive comments
Your many echo statements already explain what the code does. The comments are redundant, I would remove all of them.
Moving code to the right enclosing block
In the processing of some of the image types, you run a cp after the main processing, even if a matching file did not exist, for example:

echo " -> Now creating Help logos"
if [ -s "/disk/usbsda1/New_Help.png" ]
then
    echo " -> Found new file to be used!"
    # ...
    echo " -> Copying new files, please wait!"
    cp /disk/usbsda1/New_Help.png /opt/pclient/projekte/Help/Help_Page.png
    # ...
else
    echo " -> Could not find new image to use, skipping!"
fi

echo " -> Applying changes to project!"
cp /opt/pclient/projekte/Help/* /opt/pclient/projekte/default_prj/terminal_files/

The last cp is outside of the if-then block. But intuitively, it seems that if the if condition was false, then this last cp would find no files to copy, in which case it should be within the then block above.
Misc
Do you really need to copy files to a temporary directory first? Based on just the script you posted, this seems pointless, you could have copied directly to the destination.
Suggested implementation
Applying the suggestions above, I would rewrite your script like this (but without spelling out all the individual files in some of the longer blocks):
#! /bin/sh

SRCDIR=/disk/usbsda1
WORKDIR=/opt/pclient/projekte
DSTDIR=/opt/pclient/projekte/default_prj/terminal_files

prepare_dir() {
    DIR=$1
    if [ -d "$DIR" ]
    then
        echo " -> Found old directory, removing contents!"
        rm -rf "$DIR"/*
    else
        echo " -> Creating new directory!"
        mkdir -p "$DIR"
    fi
}

echo "
****Project Customisation Script STARTING****
"
echo "Main Background:"
IMAGE="$SRCDIR"/New_Main.png
if [ -s "$IMAGE" ]
then
    echo " -> Found new file to be used!"
    DIR="$WORKDIR"/Main
    prepare_dir "$DIR"

    echo " -> Copying new files, please wait!"
    cp "$IMAGE" "$DIR"/Main_Page.png
    cp "$IMAGE" "$DIR"/Main_Page2.png
    # ... and so on ...

    echo " -> All background images created!"
    echo " -> Now copying to project folder!"
    cp "$DIR"/* "$DSTDIR"
else
    echo " -> Could not find new image to use, skipping!"
fi

echo "Help Pages:"
echo " -> Now creating Help logos"
IMAGE="$SRCDIR"/New_Help.png
if [ -s "$IMAGE" ]
then
    echo " -> Found new file to be used!"
    DIR="$WORKDIR"/Help
    prepare_dir "$DIR"

    echo " -> Copying new files, please wait!"
    cp "$IMAGE" "$DIR"/Help_Page.png
    cp "$IMAGE" "$DIR"/Help_Page2.png
    # ... and so on ...

    echo " -> Applying changes to project!"
    cp "$DIR"/* "$DSTDIR"
else
    echo " -> Could not find new image to use, skipping!"
fi

echo "Icon Pages:"
IMAGE="$SRCDIR"/New_Icon.png
if [ -s "$IMAGE" ]
then
    echo " -> Found new file to be used!"
    DIR="$WORKDIR"/Icon
    prepare_dir "$DIR"

    echo " -> Copying new files, please wait!"
    cp "$IMAGE" "$DIR"/Icon_Page.png
    cp "$IMAGE" "$DIR"/Icon_Page2.png

    echo " -> Applying changes to project!"
    cp "$DIR"/* "$DSTDIR"
else
    echo " -> Could not find new image to use, skipping!"
fi

echo "Additional Logos:"
echo " -> Now creating Logo"
IMAGE="$SRCDIR"/New_Logo.png
if [ -s "$IMAGE" ]
then
    echo " -> Found new file to be used!"
    DIR="$WORKDIR"/Logo
    prepare_dir "$DIR"

    echo " -> Copying new files, please wait!"
    cp "$IMAGE" "$DIR"/Logo2.png

    echo " -> Applying changes to project!"
    cp "$DIR"/* "$DSTDIR"
else
    echo " -> Could not find new image to use, skipping!"
fi

echo "Boot Logos:"
echo " -> Now creating boot logos"
IMAGE="$SRCDIR"/New_Boot.png
if [ -s "$IMAGE" ]
then
    echo " -> Found new file to be used!"
    DIR="$WORKDIR"/Boot
    prepare_dir "$DIR"

    echo " -> Copying new files, please wait!"
    cp "$IMAGE" "$DIR"/loading_screen.png

    echo " -> Applying changes to project!"
    cp "$DIR"/* "$DSTDIR"/additional_files
else
    echo " -> Could not find new image to use, skipping!"
fi

setbootlogo "$DSTDIR"/additional_files/loading_screen.png

echo "Wrapping up:"
# Fully tidy up, by removing any un needed file paths
echo " -> Removing un-needed files!"
rm -rf "$WORKDIR"/Main/*
rm -rf "$WORKDIR"/Boot/*
rm -rf "$WORKDIR"/Help/*
rm -rf "$WORKDIR"/Icon/*
rm -rf "$WORKDIR"/Logo/*
echo " -> Removing un-needed directories!"
rmdir "$DSTDIR"/Main
rmdir "$DSTDIR"/Boot
rmdir "$DSTDIR"/Help
rmdir "$DSTDIR"/Icon
rmdir "$DSTDIR"/Logo

echo "
****Project Customisation Script COMPLETE****
"

Looking at this code, there's still a lot of repetition: the processing of each image type looks very similar. You could go a step further and generalize that logic too, for example:
process_image() {
    TITLE=$1; shift
    IMAGE=$1; shift
    DIR=$1; shift
    CP_FUNCTION=$1; shift
    echo $TITLE
    if [ -s "$IMAGE" ]
    then
        echo " -> Found new file to be used!"
        prepare_dir "$DIR"

        echo " -> Copying new files, please wait!"
        $CP_FUNCTION "$IMAGE" "$DIR"

        echo " -> Applying changes to project!"
        cp "$DIR"/* "$DSTDIR"
    else
        echo " -> Could not find new image to use, skipping!"
    fi
}

cp_main() {
    IMAGE=$1; shift
    DIR=$1; shift
    cp "$IMAGE" "$DIR"/Main_Page.png
    cp "$IMAGE" "$DIR"/Main_Page2.png
    # ... and so on ...
}

process_image "Main Background:" "$SRCDIR"/New_Main.png "$WORKDIR"/Main cp_main

cp_help() {
    IMAGE=$1; shift
    DIR=$1; shift
    cp "$IMAGE" "$DIR"/Help_Page.png
    cp "$IMAGE" "$DIR"/Help_Page2.png
    # ... and so on ...
}

process_image "Help Pages:" "$SRCDIR"/New_Help.png "$WORKDIR"/Help cp_help

... but this risks the script becoming too cryptic. At some point you have to draw the line and find the right balance between optimization and overengineering.


Q:

How can I clear remote repository in git?

I want to clear the remote repository and push the new files.
I' am getting
git commit -m "fix"
# HEAD detached from 0027561
nothing to commit, working directory clean

and nothing is pushed to the remote.
I tried to git init, but it didn't work.
How can I do that?

A:

You can make a new branch
git checkout -b newBranch
git push -u origin newBranch

If you want to update an existing branch like master, you can rebase that new branch on top of master:
git rebase master
git checkout master
git merge newBranch
git push heroku master

I prefer that to directly checkout master, or to force master to the new branch (git branch -f master newBranch), because it takes into account the case where new commits were done on master concurrently (meaning "while commits where done with the detached HEAD")


Q:

Contextual / Conditional dependency injection with depth greater than 1 with Ninject?

I have a IDataContext interface implemented by a InMemoryDataContext and MyApplicationDataContext. This is consumed by all of my repositories which are defined as BananaRepository : IBananaRepository and take the data context in their constructor:
interface IDataContext {}
class InMemoryDataContext : IDataContext {}
class MyApplicationDataContext : IDataContext {}

interface IBananaRepository {}
class BananaRepository : IBananaRepository
{
    public BananaRepository(IDataContext dataContext) {}
}

So far my consumers of the interfaces and services are ASP.NET MVC controllers, synchronous commands and queries. NInject is configured in my Web project and IDataContext is bound to MyApplicationDataContext with InRequestScope().
 kernel.Bind<IDataContext>().To<MyApplicationDataContext>().InRequestScope();
 kernel.Bind<IBananaRepository>().To<BananaRepository>();

I have reached the point in the evolution of my project where I want to start adding asynchronous processing (commands, events+handlers, etc). The problem I am facing is that for those I need to get a transient IDataContext (new one each time) but the binding is already set-up for a IDataContext instance per request for my controllers.
Consider this simple scenario, where my DoSomethingAsyncCommand will execute on a new thread:
class DoSomethingAsyncCommand : IAsyncCommand<TArgs>
{
    public DoSomethingAsyncCommand(IBananaRepository repository) {}

    public bool Execute(TArgs args) {}
}

I want when NInject instantiates a class implementations of IAsyncCommand the IBananaRepository (and all my other repositories) to be initialized with a new instance of IDataContext rather than the one for the web request to be reused (effectively I want for IAsyncCommand my IDataContext to be bound as InTransientScope())
How can I do that?
P.S: I am using the CommonServiceLocator rather than the Ninject kernel directly to instantiate IAsyncCommand instances.

A:

Look at https://github.com/ninject/ninject/blob/master/src/Ninject/Planning/Bindings/BindingConfigurationBuilder.cs
There you find IsAnyAnchestorNamed. You can use that same loop and combine it with the condition you find in WhenInjectedInto and call it from a custom When.


Q:

Is it a Shakespear's quote or does that quote come from Shakespeare?

I was in the seminar the other day and the speaker quoted a line. I wanted to ask a question - so can you tell me which one of the above would have been appropriate ? Is there any difference ?

A:

The following variations are all correct.  They all mean the same thing:

Is it a Shakespeare quote?  (Using his name as an attributive noun.)
Is it a Shakespearean quote?  (This is the adjective form.)
Does that quote come from Shakespeare?

If you had a few quotes to choose from (such as one from the King James Bible, one from Milton, and one from Shakespeare), it would be appropriate to ask "Is it Shakespeare's quote?"  In this usage, the possessive is used to indicate the particular quote.  This makes the indefinite article "a" redundant.  It is incorrect to ask "Is it a Shakespeare's quote?"
By the way, Shakspere could spell his own name... several different ways.


Q:

Hibernate Problem Not Saving to database

I am getting a hibernate problem. I am trying with no success. I have a schema where there are Category,Attribute,AttributeOption. e.g. a category can be a 'computer', and its respective attribute can be 'RAM','Hard Disk' and e.g. 'RAM' can have attribute option '512MB','1024MB'
When I try the above schema with hibernate everything is OK.
Now I have one other requirement. A 'Category' can have many sub categories. e.g. a 'Computer' can have 'laptop' or 'Notebook' as sub categories. Now these subcategories are of the class Category themselves
then I get this scheme:

        1. Category  ------>Category
           A category can contain many sub categories
           e.g. A computer can be a notebook or laptop

        2. Category ------>Attribure
           A category can have many attribute
           A  notebook can have RAM , Hard Disk, Screen Size

        3. Attribute  ------>AttributeOption
           An Attribute can have many attribute options
           e.g. RAM can be 512 MB, 1024 MB

These are my classes without their getters and setters
Class Category:
public class Category implements IsSerializable
{
    private long CategoryId;
    private String CategoryName;
    private Set <Category> SubCategory=new HashSet <Category> ();
    private Set <Attribute> AllAttributes= new HashSet  <Attribute>();

}
Category Mapping File:

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 16, 2010 8:07:32 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
    <class name="com.BiddingSystem.Models.Category" table="CATEGORY">
        <id name="CategoryId" type="long">
            <column name="CATEGORYID" />
            <generator class="native" />
        </id>
        <property name="CategoryName" type="java.lang.String">
            <column name="CATEGORYNAME" />
        </property>
        <many-to-one name="ParentCategory" class="com.BiddingSystem.Models.Category">
            <column name="PARENTCATEGORYID" />
        </many-to-one>
        <set name="SubCategory" inverse="true" lazy="true" cascade="all" fetch="join">
            <key>
                <column name="PARENTCATEGORYID" />
            </key>
            <one-to-many class="com.BiddingSystem.Models.Category" />
        </set>
        <set name="AllAttributes" table="ATTRIBUTE" inverse="false" lazy="true">
            <key>
                <column name="CATEGORYID" />
            </key>
            <one-to-many class="com.BiddingSystem.Models.Attribute" />
        </set>
    </class>
</hibernate-mapping>

Class Attribute:
public class Attribute
{
    private long AttributeId;
    private String AttributeName;
    private Set <AttributeOption> Options= new HashSet <AttributeOption>();
}

Attribute Mapping File:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 16, 2010 5:25:09 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
    <class name="com.BiddingSystem.Models.Attribute" table="ATTRIBUTE">
        <id name="AttributeId" type="long">
            <column name="ATTRIBUTEID" />
            <generator class="native" />
        </id>
        <property name="AttributeName" type="java.lang.String">
            <column name="ATTRIBUTENAME" />
        </property>
        <set name="Options" table="ATTRIBUTEOPTION" inverse="false"  cascade="all">
            <key>
                <column name="ATTRIBUTEID" />
            </key>
            <one-to-many class="com.BiddingSystem.Models.AttributeOption" />
        </set>
    </class>
</hibernate-mapping>

Class AttributeOption:
public class AttributeOption
{
    private long AttributeOptionId;
    private String Option;
    private String SQLValue;
}
Attribute Mapping File:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 16, 2010 5:25:09 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
    <class name="com.BiddingSystem.Models.AttributeOption" table="ATTRIBUTEOPTION">
        <id name="AttributeOptionId" type="long">
            <column name="ATTRIBUTEOPTIONID" />
            <generator class="native" />
        </id>
        <property name="Option" type="java.lang.String">
            <column name="OPTION" />
        </property>
        <property name="SQLValue" type="java.lang.String">
            <column name="SQLVALUE" />
        </property>
    </class>
</hibernate-mapping>

I am trying the following. I am not getting any error but It is not saving the 'Laptop' which is a category of 'computer' else everything is being saved. So i think the problem is with this part from the category mapping file:
<set name="SubCategory" table="CATEGORY" cascade="all">
            <key>
                <column name="CATEGORYID" />
            </key>
            <one-to-many class="com.BiddingSystem.Models.Category" />
        </set>

This is part of my program

    Category C=new Category();
    C.setCategoryName("Computer");
    AttributeOption R512= new AttributeOption();R512.setOption("512");R512.setSQLValue("512");
    AttributeOption R1024= new AttributeOption();R1024.setOption("1024");R1024.setSQLValue("1024");

        Category C0= new Category();
    C0.setCategoryName("Laptop");

    C.getSubCategory().add(C0);

    Attribute RAM= new Attribute();
    RAM.setAttributeName("RAM");

    RAM.getOptions().add(R512);RAM.getOptions().add(R1024);

    C.getAllAttributes().add(RAM);

    Transaction tx = null;
    try
    {
        tx=session.beginTransaction();
        tx.begin();
        session.saveOrUpdate(C);
        tx.commit();
        return true;
    }
    catch (Exception e)
    {
        tx.rollback();
        e.printStackTrace();
        return false;
    }

A:

Ok, I made it to work
The key to it is the category mapping file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 16, 2010 8:37:02 AM by Hibernate Tools 3.4.0.Beta1 -->
<hibernate-mapping>
    <class name="com.BiddingSystem.Models.Category" table="CATEGORY">
        <id name="CategoryId" type="long">
            <column name="CATEGORYID" />
            <generator class="native" />
        </id>
        <property name="CategoryName" type="java.lang.String">
            <column name="CATEGORYNAME" />
        </property>

        <many-to-one name="ParentCategory" class="com.BiddingSystem.Models.Category">
            <column name="PARENT_CATEGORY_ID" />
        </many-to-one>

        <set name="SubCategory" lazy="false" cascade="all-delete-orphan" inverse="true">
            <key>
                <column name="PARENT_CATEGORY_ID" />
            </key>
            <one-to-many class="com.BiddingSystem.Models.Category" />
        </set>

        <set name="AllAttributes" table="ATTRIBUTE" inverse="false" lazy="true">
            <key>
                <column name="CATEGORYID" />
            </key>
            <one-to-many class="com.BiddingSystem.Models.Attribute" />
        </set>
    </class>
</hibernate-mapping>


Q:

Is there a method in PL/SQL to convert/encode text to XML compliant text?

I have a colleague who needs to convert text from a PL/SQL method into XML compliant text, as he is constructing a excel spreadsheet by updating a text template.
Is there a method in PL/SQL to convert/encode text to XML compliant text?

A:

Well, if you just want to convert XML characters, you'll want to do something like...
  outgoing_text := DBMS_XMLGEN.CONVERT(incoming_text)

Where outgoing_text and incoming_text are both VARCHAR2 or CLOB.
You can specify a second argument, but it defaults to DBMS_XMLGEN.ENTITY_ENCODE... it can also decode XML entities by passing DBMS_XMLGEN.ENTITY_DECODE as a second argument.

A:

Later versions of oracle have a built in XML package for manipulating XML data.
For example, is this the sort of thing your colleague wants to do?:
SELECT DBMS_XMLGEN.getXML('SELECT * FROM emp') FROM dual;


Q:

How To Remove Padding of Iframe from page

I want to remove padding (few pixel) of iframe. when we use iframe in any page and make its height & width 100% but it left few pixels from all side left, right, up & down.how to remove it. Please look at this URL.
http://mindmaker.org.in/frame.php
i have remove scroll bar from this page but few pixels are not remove from all side

A:

You have to reset default <body> padding / margin.
body {
  margin: 0;
  padding: 0;
}

Hope this helps