Q:

C# Web service consuming error in SAP

We have developed a webs service which consumes fine with a C#.net application but this web service not been able to consume by a SAP application getting the error : Unable to Handle request without a valid action parameter
What would be the problem?
WSDL File:
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tm="http://microsoft.com/wsdl/mime/textMatching/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:tns="http://sabretch.com/psr" xmlns:s="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://sabretch.com/psr">
<wsdl:types>
<s:schema elementFormDefault="qualified" targetNamespace="http://sabretch.com/psr">
<s:element name="SendChangeLog">
<s:complexType>
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="toDetails" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="subject" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="arr_psrAlertLogItems" type="tns:ArrayOfObj"/>
</s:sequence>
</s:complexType>
</s:element>
<s:complexType name="ArrayOfObj">
<s:sequence>
<s:element minOccurs="0" maxOccurs="unbounded" name="Obj" nillable="true" type="tns:Obj"/>
</s:sequence>
</s:complexType>
<s:complexType name="Obj">
<s:sequence>
<s:element minOccurs="0" maxOccurs="1" name="ChangeDateTime" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="SalesOrderKey" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Line" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="FieldTecnicalName" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="Value" type="s:string"/>
<s:element minOccurs="0" maxOccurs="1" name="ChangedUser" type="s:string"/>
</s:sequence>
</s:complexType>
<s:element name="SendChangeLogResponse">
<s:complexType>
<s:sequence>
<s:element minOccurs="1" maxOccurs="1" name="SendChangeLogResult" type="s:boolean"/>
</s:sequence>
</s:complexType>
</s:element>
</s:schema>
</wsdl:types>
<wsdl:message name="SendChangeLogSoapIn">
<wsdl:part name="parameters" element="tns:SendChangeLog"/>
</wsdl:message>
<wsdl:message name="SendChangeLogSoapOut">
<wsdl:part name="parameters" element="tns:SendChangeLogResponse"/>
</wsdl:message>
<wsdl:portType name="PSREmailServiceSoap">
<wsdl:operation name="SendChangeLog">
<wsdl:input message="tns:SendChangeLogSoapIn"/>
<wsdl:output message="tns:SendChangeLogSoapOut"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="PSREmailServiceSoap" type="tns:PSREmailServiceSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="SendChangeLog">
<soap:operation soapAction="http://sabretch.com/psr/SendChangeLog" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:binding name="PSREmailServiceSoap12" type="tns:PSREmailServiceSoap">
<soap12:binding transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="SendChangeLog">
<soap12:operation soapAction="http://sabretch.com/psr/SendChangeLog" style="document"/>
<wsdl:input>
<soap12:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap12:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="PSREmailService">
<wsdl:port name="PSREmailServiceSoap" binding="tns:PSREmailServiceSoap">
<soap:address location="http://122.255.30.75:8090/WebServices/PSREmailService.asmx"/>
</wsdl:port>
<wsdl:port name="PSREmailServiceSoap12" binding="tns:PSREmailServiceSoap12">
<soap12:address location="http://122.255.30.75:8090/WebServices/PSREmailService.asmx"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>

A:

When sending the SOAP request, part of the HTTP Header data must include a SOAP Action field in order to correctly identify (using the WDSL) what methods to execute. In C# this is processed automatically based on the action provided when sending the message which explains why you would be getting problems now.
Being as I'm not too well versed in SAP, I can't provide an example, however this knowledge should start you off on the right track.


Q:

Share session variables between asp.net and vb6

Hi i have a question about Session variables, i want to call in GET via ajax, from my .aspx page, a page .asp that have VB6 code inside, i need to share Session variables between them actually i tried this:
ASPX file

<title>let's try Ajax</title>

<form id="form1" runat="server">

        in the aspx: <%Response.Write(Session["try"].ToString()); %>

</form>

code behind page:
public partial class _Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session["try"] = "hello world";
    }
}

finally .asp page
<%
  [...]
  Response.Write  "" & Session("try")
  Response.End
  [...]
%>

Actually the Session doesn't show anything in the .asp page, but in the .aspx page shows it's string inside, what's wrong with my code? Is it possible to pass share a session?

A:

I think, you want to share your session between Class ASP and ASP.Net. so you need to store
your session information in SQL server. Please refer below link
http://msdn.microsoft.com/en-us/library/aa479313.aspx


Q:

PayPal charged, but payment response is "INVALID"

several of the webshops from our customers provide a checkout via PayPal.
Actually we have the problem, that when we're forcing a checkout, we get the answer, that something went wrong. But if we check the PayPal Account, then we see, that the charging still has taken place.
Now we're looking for the reason and figured out following:
- If we use a PayPal Sandbox Account, it all works fine
- The payment status is "Completed" (in both cases)
- www.sandbox.paypal.com returns "VERIFIED"
- www.paypal.com returns "INVALID"
Can anyone help us out in this case?
I'll attach two files with the responses from your servers.
Webshop-Request-Parameters:
cmd=_notify-validate&mc_gross=0.01&invoice=zz_zzzzzzzz&protection_eligibility=Ineligible&item_number1=zzzzzzzz&payer_id=CCCCCCCCCCCCC&tax=0.00&payment_date=05%3A10%3A46+Apr+29%2C+2015+PDT&payment_status=Completed&charset=UTF-8&mc_shipping=0.00&mc_handling=0.00&first_name=JOHN&mc_fee=0.01&notify_version=3.8&custom=2&payer_status=verified&business=john%40doe.com&num_cart_items=1&mc_handling1=0.00&payer_email=john%40aol.com&verify_sign=GiPC9Bj...&mc_shipping1=0.00&tax1=0.00&txn_id=CCCCCCCCCCCCCCCCC&payment_type=instant&last_name=Doe&item_name1=00000000&receiver_email=john%40doe.com&payment_fee=0.01&quantity1=1&receiver_id=CCCCCCCCCCCCC&txn_type=cart&mc_gross_1=0.01&mc_currency=USD&residence_country=US&transaction_subject=2&payment_gross=0.01&auth=AHMdYo7nB...
... = hash algorithm
Response is the standard PayPal-Header plus an "INVALID"
Some Support-Responses from the PayPal support team:
1.You need to include your PayerID as User-Agent in the HTTP Header
2.Use the URL https://ipnpb.paypal.com/cgi-bin/webscr for the post-back to bypass the AKAMAI.
Both solutions were unsuccessful
Next PayPal support solutions
•Check that your are posting your response to the correct URL, which is https://www.sandbox.paypal.com/cgi-bin/webscr (for Sandbox IPNs) or https://www.paypal.com/cgi-bin/webscr (for live IPNs). You will receive INVALID if you are testing in the Sandbox and your listener posts back to the live site (and vice versa).
•Verify that your response to the test IPN message contains exactly the same variables and values as the test message and that they are in the same order as in the test message. Finally, verify that the original variables are preceded by a cmd=_notify-validate variable.
•Verify that your response to an IPN: ◦contains exactly the same variables and values as the original IPN.
◦places these variables and values in the same order as does the original IPN.
◦precedes these variables with a cmd=_notify-validate variable.
•Ensure that you use the same character encoding for your response string as the encoding specified in the charset field of the original IPN message. When testing using the IPN Simulator, the character encoding will always be UTF-8.
... were unsuccessful, too

A:

Problem was figured out by wrong Charset set on the account settings.
In the "My Account" settings (under "More Encoding Options") the Econding has to be set for what your application sends. (In our case it had to be changed from paypal account installation default to UTF-8)


Q:

Would it be legal to use deadly force in a stampede?

Imagine a stampede where there is a reasonable fear of death or grievous bodily harm. Would it be legal for a victim to use deadly force in the form of a gun or knife in this scenario?
In states where family or strangers can use deadly force, would it be legal for them to shoot the stampeders?

A:

Self-Defense Law In A Nutshell
Self-defense (or defense of others) with deadly force is generally authorized when a reasonable person would believe that the use of death force is necessary to prevent death or serious bodily harm to a person (i.e. there aren't non-deadly options that can accomplish this end) and a reasonable person would believe that the use of force will prevent death or serious bodily harm to a person, subject to exceptions that would not apply to a private individual using deadly force in a stampede situation.
Incidentally, every state and every country absolves someone of liability for homicide when deadly force is used in self-defense, or in the defense of others (not necessarily family), although the exact details of when this is justified varies slightly. For example, in D.C. v. Heller, the right to self-defense is considered a natural or universal right.
The analysis would be somewhat different if the shooter were in law enforcement, and would be different again in the case of a shooter who was in the military with more or less clear orders.
But, that legal standard doesn't get you to an answer.
The Complex Phenomena Called Stampedes
The analysis would be extremely fact rich, in the sense of exactly who one would attempt to shoot, what that would be likely to accomplish, and what other alternatives would be available. And, to do that, you also need to understand the phenomena of deadly stampedes which are complex and often somewhat counter-intuitive phenomena.
While there are circumstances where it could be legal self-defense or defense of others to shoot a stampeding individual to save someone's life, there are also many stampede circumstances where a use of force would not be justified.
In practice, most stampedes, as a matter of physics, can only be stopped by removing a crush of bodies from the rear, where they do not know that they are causing a deadly stampede, while those at the front who end up directly harming others are frequently physically incapable of stopping.
Essentially, in a typical stampede that causes death, the problem is an inability of the people at the front to communicate to the people at the back to slow down. And, when a stampede is caused by a genuine threat to the people at the back like a fire or a terrorist, there is nothing that would persuade the people at the back to slow down anyway.
So, usually, shooting to kill someone at the front of a stampede would not achieve the intended result of protecting someone in its path. The person shot would either continue to surge forward while dead under the crush of bodies behind them, or would have their dead body trampled over by the next person in line who also has no physical ability to do anything other than to surge forward. So, usually, using deadly force to shoot someone at the front of a stampede will be futile and only cause an unnecessary death.
Given that using deadly force in a stampede, if directly at people in the front, is almost always futile, the question for the judge or jury deciding the case becomes whether a reasonable person would know that at the time, which would have to be decided a case by case basis.
Sometimes it is obvious from someone in a vantage point to shoot at the front of a stampede that this would be futile and sometimes it isn't. This question would be highly fact specific and depend a lot upon exactly what information about the situation was available to the person shooting a person in the stampede.
The situation where deadly force might not be futile would be one in which there is no actual life threatening harm that people are fleeing in which the deadly force is directed at the people in the back who are driving the stampede (even though they don't know it), to shock them into ceasing to do so. But, in that situation, if the shooting is done by someone who understands the situation well enough to know that this is what is actually necessary, that person also may be capable of firing warning shots or shooting to injure with the same effect, so justification might also be in doubt.
Protecting Targets of Mobs v. Protecting Targets of Stampedes
A similar situation where the use of deadly force might be justified is something visually similar to a stampede, but quite different in what would work factually.
This is a mob that is about to attack someone, possibly armed with pitchforks or knives or clubs or broken bottles or a noose. In the case of a mob, the use of deadly force to protect someone threatened by the mob would almost always be a justified use of force in self-defense or the defense of others, because shooting someone in the front is likely to be both necessary and effective.


Q:

Investigating python process to see what's eating CPU

I have a python process (Pylons webapp) that is constantly using 10-30% of CPU. I'll improve/tune logging to get some insight of what's going on, but until then, are there any tools/techniques that allow to see what python process is doing, how many and how busy threads it has etc?
Update:

configured access log which shows that there are no requests going on, webapp is just idling
no point to plug in paste.profile in middleware chain since there are no requests, activity must be happening either in webapp's worker threads or paster web server
running paster like this: "python -m cProfile -o outfile /usr/bin/paster serve dev.ini" and inspecting results shows that most time is spent in "posix.waitpid". Paster runs webapp in subprocess, subprocess activity is not picked up by profiler
looking into ;hacking PasteScript "serve" command so that subprocesses would get profiled

Another update:
After much tinkering, sticking profiler in various places and getting familiar with PasteScript insides, I discovered that the constant CPU load goes away if application is started without "--reload" parameter (this flag tells paster to restart itself if code changes, handy in development), which is fine in production environment.

A:

Profiling might help you learn a bit of what it's doing. If your sort the output by "time" you will see which functions are chowing up cpu time, which should give you some good hints.

A:

As you noted, in --reload mode, Paste sweeps the filesystem every second to see if any of the files loaded have changed. If they have, then Paste reloads the process. You can also manually tell Paste to monitor non-Python code modules for changes if desired.
You can change the reload interval with the --reload-interval option, this will reduce the CPU usage when using --reload as it will sweep less often.


Q:

WCF Data Service : Many to many query

So I have this database model :
Student<->StudentClasses<->Classes

where 1 student is linked to  many StudentClasses and one Class is linked to many StudentClasses.
How do I write a LINQ query to get all the classes linked to the student with Id 1 ?
the following query throws an exception
       ("Can only specify query options (orderby, where, take, skip) after last navigation.") :
                     var qry = from sc in service.StudentClasses
                      where sc.StudentId == 1
                      from c in service.Classes
                      where c.ClassId == sc.StudentId
                      select c;

A:

This would work, but it will crash if you the ID DNE.
var qry =  service.StudentClasses
              .Expand("Classes")
              .Where(x=>x.StudentId==1)
              .First()
              .Classes.Select(t=>t);


Q:

extends function from blade doesn't work

I have a problem, I don't know why but when I extend a blade template then I call it,  it prints an empty page in my browser.
In my /app/views/layout.blade.php
<div>
    @yield('main')
</div>

In my /app/views/error/notfound.blade.php
@extends('layout')
@section('main')
<myhtmlcode>
</myhtmlcode>
@stop

My notfound template is called when I catch a NotFoundHttpException
App::error(function(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception, $code)
{
    return View::make('error.notfound');
});

Every other View::make work fine.. this one worked fine before.. but I certainly made an invisible mistake. I need your hindsight guys.
Thanks.

A:

Ok I'm obvious..
So I prefix all my routes
Route::group(array('prefix' => '{lang}', 'before' => 'set.lang'), function($lang) {
});

So I tried to call my template notfound.blade.php inside my route::group with a route test and it didn't work too..
But there was a php warning telling me that he can't found the $lang variable in my layout.blade.php !
So I guess that when I returned my view by catching the notFoundHtppException there was this error too but laravel didn't show me anything.. so I just had to inject the $lang variable in my View::make like this in app/start/global.php
App::error(function(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $exception, $code)
{
    return View::make('error.notfound', ['lang' => App::getLocale()]);
});

Now it works like a charm..


Q:

Ionic Framework : Can't navigating back to my app after doing form-post to my hosting

I have an App which uploads a photo to a hosting by using codes below :

                <form action="{{ 'http://m.fxlegato.com/profileImages/upload.php?email=' + datauser.email}}" method="post" enctype="multipart/form-data">
                    <input type="file" class="light" name="fileToUpload" id="fileToUpload" accept="image/x-png, image/gif, image/jpeg" />
                    <input type="submit" class="button button-positive button-block" value="Upload Image" name="submit">
                </form>

When Upload button pressed, then a message from my upload.php appears. The photo is uploaded successfully, But I can't get back to my app while I am in that .php messages. This problem appears after I added the crosswalk to my app. If I not use that crosswalk, all works perfect.
How to solve this problem?

A:

IHMO, basic HTML forms, with a basic action are not a good solution to use on hybrid apps.
Since your are uploading a file, you should consider using a dedicated library, like one of those two:

https://github.com/nervgh/angular-file-upload
https://github.com/danialfarid/ng-file-upload

Also, some tutorials are available to do this kind of stuff. Here is an example:

https://blog.nraboy.com/2015/01/upload-files-remote-server-using-ionic-framework/


Q:

iPhone corebluetooth central Manager send data to peripheral

I want to send data from iPhone to a bluetooth device which get discovered and connects.
I am referring this tutorial to connect.
I am not able to send data to external bluetooth device which is connected as we do with External Accessory framework.
I am using iPhone5 as it has Bluetooth 4.0

A:

In Core Bluetooth you need to use the characteristics for communication. There is no standard stream based API like in the External Accessory Framework and I don't know of any open source libraries that implement something like that.
Basic operation
Peripheral -> Central:

Central subscribes to characteristic (either with notifications or indications)
Peripheral receives the subscribed callback so knows that the central is listening
Peripheral updates characteristic
Central receives characteristic updated notification

Central -> Peripheral:

Central writes characteristic
Peripheral receives write request update

The actual speed you can achieve depends on various factors. With indications the data is never lost (like TCP) but notifications don't have such guarantees (like UDP).
More info
I suggest you check out the official Core Bluetooth Programming Guide and concentrate on the

Performing common Central Role tasks
Performing common Peripheral Role tasks

sections. But better would be studying the whole guide as is. For a working example, check out the BTLE Transfer example from Apple, as well.

A:

If i understand you correctly you want the central to send data to your peripheral.
for that you use this method:
[peripheral writeValue:dataPacket forCharacteristic:writeChar type:CBCharacteristicWithResponse]


Q:

weak$^*$ topology is strictly coarser than weak topology ; a remark in Brezis

Let $E$ be a banach space. $\sigma(E^*,E)$ be the weak $^*$ topology, $\sigma(E^*, E^{**})$ the weak topology on $E^*$ induced by the functionals on $E^{**}$.
It is proven in Brezis, pg65,

Corollary 3.15: If $H$ is a hyperplane in $E^*$ closed in $\sigma(E^*,E)$ then $H$ has the form $$H= \{ f \in E^* \, :\, f(x_0)= \alpha \}$$for some $x_0 \in E$, $\alpha \in \Bbb R$.

He stated, if canonical injection $j:E \rightarrow E^{**}$ is not surjective then

Let $\xi \notin J(E)$, the set
  $$ H= \{ f \in E^* \, : \, \xi(f) = 0 \} $$
  is not closed in $\sigma(E^*,E)$.

I do not see how this follows from the corollary.

A:

Suppose $ \ker (\xi) = \{f\in E^* : \xi (f) = 0\}$ is closed in the weak star topology, then by corollary 3.15, $\ker(\xi) = \ker (J(x_0))$ for some $x_0\in E$.
The two elements $\xi$ and $J(x_0)$ in $E^{**}$ have the same kernel, then they must be constant multiple of each other. This is lemma 3.2 on page 64 from Brezis.


Q:

MVC3 How to implement a mulitple "add to cart" feature in a shopping cart?

I created my own simple shopping cart following the Music store mvc example. Problem is, my shop only allows one item addition at a time. But now I need a way to add multiple items at once to a cart and specify the quantity.
I was thinking about doing this: Model Binding to a List, but my Item model does not have a quantity property to hold the needed cart quantity.
public int ItemID { get; set; }

public string Barcode { get; set; }

public string Name { get; set; }

public string Description { get; set; }

public decimal Price { get; set; }

and my viewmodel:
public class ItemViewModel
{
    public int ItemID { get; set; }

    public string Barcode { get; set; }

    public string Name { get; set; }

    public string Description { get; set; }

    public decimal Price { get; set; }

    public int Quantity { get; set; }
}

public class ItemToCartViewModel
{
    public List<ItemViewModel> itemToCart { get; set; }
}

doesn't seem to post properly in my post action (null or no values passed):
[HttpPost]
public ActionResult addtocart(ICollection<ItemViewModel> items)
{ ... }

Any ideas?
UPDATE:
@model IList<MyTGP.ViewModels.ItemViewModel>
@{
    ViewBag.Title = "Search for Items";
    int count = 0;
}

    Search for Items

@Html.Partial("_SearchItemsPartial")

@using (Html.BeginForm("addtocart","Cart"))
{
if (String.IsNullOrEmpty(ViewBag.NoRecord)) {

            Barcode

            Name

            Description

            Price

            Quantity

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Barcode)

                @Html.DisplayFor(modelItem => item.Name)

                @Html.DisplayFor(modelItem => item.Description)

                @Html.DisplayFor(modelItem => item.Price)

                @Html.EditorFor(modelItem => item.Quantity)

        count++;
    }

} else { @ViewBag.NoRecord }

    <input type="submit" value="add items to cart" />

}

A:

I can't comment yet so I'm posting here. Can you show us the view? The html is important.
Update:
Try like this (in the foreach loop)
@Html.Hidden("["+count+"].ItemID",item.ItemID)
@Html.Hidden("["+count+"].Barcode",item.Barcode)
@Html.Hidden("["+count+"].Name",item.Name)
@Html.Hidden("["+count+"].Description",item.Description)
@Html.Hidden("["+count+"].Price",item.Price)

Then where you display the quantity @Html.TextBox("["+count+"].Quantity",item.Quantity)


Q:

Conditionally load JavaScript file

I need a JS statement that determine which JavaScript file to use.
I have one file:
<script type="text/javascript" src="js/jquery_computer.js"></script>

But when the screen width is less than 500px, I want load another file instead:
<script type="text/javascript" src="js/mobile_version.js"></script>

I have tried everything and it is not working.

A:

You'd have to create that markup yourself in JS. Something like this:
var head = document.getElementsByTagName('head')[0];
var js = document.createElement("script");

js.type = "text/javascript";

if (screen.width > 500)
{
    js.src = "js/jquery_computer.js";
}
else
{
    js.src = "js/mobile_version.js";
}

head.appendChild(js);

A:

If you want the script loaded asynchronously, the other answers here do that.
If you want it loaded synchronously with page load, this is one of the very, very few remaining valid uses cases for document.write:
<script>
(function() { // Scoping function to avoid globals
    var src = /*you want the main version*/ ? "jquery_computer.js" : "mobile_version.js";
    document.write('<script src="js/' + src + '"><\/script>');
})();
</script>

(I've removed type because JavaScript is the default, specifying it isn't useful.)

A:

Maybe you can use matchMedia.js and can load a script using jQuery.getScript
$(function(){
    if (matchMedia('only screen and (max-width: 500px)').matches) {
        $.getScript(...);
    }
});


Q:

Is it possible to MAC a quantum state with a classical key under reasonable assumption?

Assume that classical one-way functions secure against quantum adversaries exist.  Is it possible, given a quantum state $Q$ and classical secret key $k$, produce a quantum state $AuthQ$ such that:

One who knows $k$ can recover $Q$, provided that $AuthQ$ has not been altered.
If $AuthQ$ has been altered, this can be detected with high probability.

It may or may not be possible to recover the original state without the secret key.  What matters is that, given the secret key, one can be confident that:

The creator of the quantum state had the secret key
The message has not been tampered with since.

A:

Howard Barnum, Claude Crepeau, Daniel Gottesman, Adam Smith, Alain Tapp. "Authentication of Quantum Messages", FOCS 2002.
http://www.cse.psu.edu/~ads22/pubs/PS-CSAIL/BCGST02-focs-final.pdf
As with encryption, there is a protocol that requires no computational assumptions. It uses a key of length about 2n+2k to authenticate n qubits with security level 2^{-k}.


Q:

XPath expression to ignore the child nodes

I have the following xml:
<?xml version="1.0" encoding="UTF-8"?>
<response>
   <folder>
      <TestOne>F</TestOne>
      <TestTwo>01</TestTwo>
      <case>
         <CRDATTIM>2014-03-26-05.22.22.339840</CRDATTIM>
         <RECORDCD>C</RECORDCD>
      </case>
      <case>
         <CRDATTIM>2014-03-26-05.05.51.531840</CRDATTIM>
         <RECORDCD>C</RECORDCD>
      </case>
   </folder>
</response>

I need the XPath expression to read the nodes and their values immediately under the <folder> tag. I don't require the child nodes information. I mean, my extracted info should look like below:
<folder>
<TestOne>F</TestOne>
<TestTwo>01</TestTwo>
<folder>

Here the tags names listed under <folder>i.e <TestOne>, <TestTwo> are dynamic.
Is there any way to derive an XPath expression for above requirement? Please let me know if my question is not clear. Thanks in advance.

A:

Here's a template that will output only direct childs of a <folder> node:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" exclude-result-prefixes="xsl">
    <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    <xsl:template match="/response/folder">
        <folder>
            <xsl:apply-templates select="node()" mode="childs"/>
        </folder>
    </xsl:template>
    <xsl:template match="*" mode="childs">
        <xsl:if test="count(./text()) = 1">
            <xsl:element name="{local-name()}">
                <xsl:value-of select="."/>
            </xsl:element>
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

If you're just after the xpath to get all those nodes within your folder node:
/response/folder/node()[count(text()) = 1]

A:

XPath is a way to select particular nodes out of an XML tree, but on its own it can't change the content of any of those nodes.  If you use an expression to select the folder element
/response/folder

then you'll get the whole of that element, including the case children.  You could select just the "leaf" elements under folder using
/response/folder/*[not(*)]

which would give you a node set containing two elements (the TestOne and the TestTwo), but assembling those two elements into a new folder element is not something XPath can do for you.  You'll have to do that yourself using whatever facilities are provided by the language/tool you're using to evaluate the XPath expressions.


Q:

Ruby: Inserting records to existing rails database using non-rails script

I have a rails app that only allows users to search and view the contents of its (MySQL) database. To add records to the database, I'd like to run a ruby script automatically twice a day which generates the contents of the database and then updates the db. Is this possible, or does my script have to be a part of the rails web app?

A:

Solved this using rails runner command


Q:

Why is the focus never lost from my component when I press the JFrame?

I have a problem with the focus listener implemented by CustomTextField class. The focus listener is only called when another Swing component is getting the focus. But If I move the JFrame istelf by dragging it with the mouse, the focusLost() method is never called (in other words, it doesn´t seem that the focus is shifting from CustomTextField to JFrame).
EDIT: The solution of my question is below:
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import javax.swing.*;

public class ScrollFocus extends JFrame {

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            new ScrollFocus();
        }
    });
}

public ScrollFocus() {
    this.setLayout(new BorderLayout());
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Vector<String> values = new Vector<>();
    values.add("a");
    values.add("b");
    values.add("c");
    values.add("d");
    values.add("e");
    JComboBox<String> comboBox = new JComboBox<>(values);
    JScrollPane scrollPane = new JScrollPane(comboBox);
    this.add(scrollPane, BorderLayout.NORTH);

    CustomTextField customTextField = new CustomTextField();
    this.add(customTextField, BorderLayout.CENTER);

    JButton button = new JButton("press");
    final JPopupMenu menu = new JPopupMenu("Menu");
    menu.add(new JMenuItem("Test"));
    button.setComponentPopupMenu(menu);
    this.add(button, BorderLayout.SOUTH);

    pack();
    setVisible(true);
}

class CustomTextField extends JTextField implements FocusListener {

    private CustomPopup customPopup = new CustomPopup();

    public CustomTextField() {
        this.addFocusListener(this);

        this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "VK_UP");
        this.getActionMap().put("VK_UP", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setPopupSize();
                customPopup.show(CustomTextField.this, CustomTextField.this.getX(), CustomTextField.this.getY() + CustomTextField.this.getHeight());
                customPopup.setSelectedIndex(0);
            }
        });
        this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "VK_DOWN");
        this.getActionMap().put("VK_DOWN", new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                setPopupSize();
                customPopup.show(CustomTextField.this, CustomTextField.this.getX(), CustomTextField.this.getY() + CustomTextField.this.getHeight());
                customPopup.setSelectedIndex(0);
            }
        });
    }

    public void setPopupSize() {
        customPopup.setPopupSize(new Dimension(this.getWidth(), 110));
    }

    @Override
    public void focusGained(FocusEvent e) {
    }

    @Override
    public void focusLost(FocusEvent e) {
    }

    class CustomPopup extends JPopupMenu {
        String[] values = new String[]{"Value1", "Value2", "Value3", "Value4", "Value5", "Value6", "Value7",
                "Value8","Value9", "Value10", "Value11", "Value12", "Value13", "Value14", "Value15", "Value16",};
        JList<String> list = new JList<>(values);
        JScrollPane scrollPane = new JScrollPane(list);
        public int index = 0;

        public CustomPopup() {
            this.setLayout(new GridLayout(0,1));
            this.add(scrollPane);
            this.addKeyListener(new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyCode() == KeyEvent.VK_UP){
                        if(customPopup.index > 0)
                            customPopup.setSelectedIndex(--customPopup.index);
                    }
                    else if(e.getKeyCode() == KeyEvent.VK_DOWN){
                        if(customPopup.index < customPopup.getListSize()-1)
                            customPopup.setSelectedIndex(++customPopup.index);
                    }
                }
            });
            this.addFocusListener(new FocusAdapter() {
                @Override
                public void focusLost(FocusEvent e) {
                    index=0;
                }
            });
            pack();

        }

        public void setSelectedIndex(int index) {
            list.setSelectedIndex(index);
            list.ensureIndexIsVisible(index);
            requestFocus();
        }

        public int getListSize() {
            return values.length;
        }
    }
}
}

A:

//customPopup.setVisible(true);
customPopup.show((JComponent)e.getSource(), 0, 20);

You should be using the show(...) method to show the popup. This must add some listeners to the popup so you will no longer need the FocusListener on the text field.
However, now this is a different problem. The text field loses focus so the Action never get invoked. That would be ok, but the JList never gains focus so it doesn't respond to the up/down keys unless you click on the list box first. I'm not sure what the problem is here.
Maybe you can try to make the popup, scrollpane and list all non-focusable so that focus remains on the text field?


Q:

Does DirectSound usually support echo cancellation and noise reduction?

I'm currently using the waveInOpen set of Windows API functions to record audio for a VOIP application.  I'm now being asked to add echo cancellation, and possibly noise reduction, and gain control.  I know nothing about DirectSound, but while searching on "echo cancellation" on Google I came across references on MSDN to DirectSound such as CaptureAcousticEchoCancellationEffect.
If I switch to DirectSound will I get some of these features "for free"?  Are they only supported if the hardware supports it, and if so, how often will that hardware be present in the average consumer PC?

A:

Starting with Windows Vista, Microsoft provides a separate component Voice Capture DSP:

The voice capture DMO includes the following DSP components:
Acoustic echo cancellation (AEC)
Microphone array processing
Noise suppression
Automatic gain control
Voice activity detection

Applications can turn each component on and off individually.

You can use it in your DSP application to leverage EAC and NS implemented in software.


Q:

Keep router interfaces isolated

Have a Cisco Router 2811 with a HWIC that gives it an extra port so I have 3 Ethernet ports. Have it configured like this:
FA0/0- 192.168.1.1
FA0/1- 192.168.10.1
FA1/0- 10.0.0.1 (outside)
All that works fine except the .1 and .10 networks can talk and ping each other. Is there anyway to separate them so they can't see the other one but both can still access the internet?

A:

Add an ACL that blocks the traffic. Something along those lines (will need to be more tailored):
 ip access-list extended AL-INSIDE-1
  deny ip 192.168.1.0 255.255.255.0 192.168.10.0 255.255.255.0
  permit ip 192.168.1.0 255.255.255.0 any

 ip access-list extended AL-INSIDE-10
  deny ip 192.168.10.0 255.255.255.0 192.168.1.0 255.255.255.0
  permit ip 192.168.10.0 255.255.255.0 any

 int fa0/0
  ip access-group AL-INSIDE-1 in

 int fa0/1
  ip access-group AL-INSIDE-10 in

May need to tweak this - I don't know all the details of your setup but that should get you going pretty well.


Q:

Error: Could not find or load main class Akash

I want to run selenium program from command line. The code I have is
    class Akash
    {
        public static void main(String args[])
        {
            org.openqa.selenium.WebDriver driver = new org.openqa.selenium.firefox.FirefoxDriver();
        }
    }

Filename : Akash.java (Path : C:\Users\anigam\Desktop\Testing)

The required jars are present here : C:\Users\anigam\Desktop\Order Streaming\Automation_03.04.2017\For_Checkin\uitestframework\lib

I compiled the file as :

javac -cp "C:\Users\anigam\Desktop\Order Streaming\Automation_03.04.2017\For_Checkin\uitestframework\lib*" Akash.java

The compilation was successfull and I got Akash.class generated here :
C:\Users\anigam\Desktop\Testing
When I am trying to execute this class file as :

java -cp "C:\Users\anigam\Desktop\Order Streaming\Automation_03.04.2017\For_Checkin\uitestframework\lib*" Akash

I am getting an error :
Error: Could not find or load main class Akash
Can someone please help.
Thanks much.

A:

Your program is able to load dependant libraries from the classpath you provied but unable to load the class file which you compile and generate(Akash.class).
So try adding the current directory where Akash.class resides also in the class path.
1) Open Command prompt
2) cd C:\Users\anigam\Desktop\Testing
3) Running below command would help
java -cp "C:\Users\anigam\Desktop\Order Streaming\Automation_03.04.2017\For_Checkin\uitestframework\lib*;." Akash
Hope it helps.
-Sandeep


Q:

Ektron Pagebuilder JQuery interferes with Scripts in Edit Mode in IE8

Recently I discovered that for whatever reason on one of my sites, pagebuilder seems to be stopping my scripts from loading while its multiview is switched to the edit view. This is true both of scripts simply sitting in HTML inside of the edit view, and of scripts dynamically added via Ektron's JS.RegisterJSInclude method.
However, my dynamic scripts load find so long as i add
JS.RegisterJSInclude(this, JS.ManagedScript.EktronJS);

as the first include.
That was fine and well, but I recently discovered that this script fails to run in IE8, causing all of my edit scripts to fail. So, my question is: Can the script stripping behavior of pagebuilder be disabled, or is there a workaround using EktronJS to get it to run in IE8?
Ektron 8.6.1, Server 2008 R2, SQL Server 2008.

A:

I don't believe Ektron has any "script stripping" functionality, more likely is that there is a Javascript error on the page which is introduced when in edit mode due to the extra Javascript files that are loaded.
The "EktronJS" file that you are registering is actually the jQuery library that is bundled with Ektron.  Ektron's own jQuery files depend upon the core jQuery library being loaded.  However it is normally added automatically - without it the client side PageBuilder functionality will not work.
Ektron v8.6 should support IE8 and higher, so you have no problems there.
I would recommend creating a very basic PageBuilder wireframe - don't use your MasterPages - you just want the bare essentials.  Add the RegisterJSInclude, then add your custom jQuery files one at a time, see if your Javascript works ok, then add the next file and keep going.
This process will likely show that there is a specific Javascript file which fails in IE8.


Q:

SonataUserBundle : try to go /profile => route "sonata_customer_addresses" does not exist

I can't figured out why I have this error.
Herewith more informations abour my problem :
An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "sonata_customer_addresses" as such route does not exist.") in SonataUserBundle:Profile:action.html.twig at line 27.

to implement my own User Class.
I use Symfony 2.4 with dev-master SonataAdminBundle and SonataUserBundle. I try
you can find my config.yml :
    sonata_user:
    security_acl: true
    manager_type: orm
    profile:
        # Profile show page is a dashboard as in SonataAdminBundle
        dashboard:
            blocks:
                - { position: left, type: sonata.block.service.text, settings: { content: "
Welcome!
 This is a sample user profile dashboard, feel free to override it in the configuration! Want to make this text dynamic? For instance display the user's name? Create a dedicated block and edit the configuration!"} }
                - { position: left, type: sonata.order.block.recent_orders, settings: { title: Recent Orders, number: 5, mode: public }}
                - { position: right, type: sonata.timeline.block.timeline, settings: { max_per_page: 15 }}
                - { position: right, type: sonata.news.block.recent_posts, settings: { title: Recent Posts, number: 5, mode: public }}
                - { position: right, type: sonata.news.block.recent_comments, settings: { title: Recent Comments, number: 5, mode: public }}
        # Customize user portal menu by setting links
        menu:
            - { route: 'sonata_user_profile_show', label: 'sonata_profile_title', domain: 'SonataUserBundle'}
            - { route: 'sonata_user_profile_edit', label: 'link_edit_profile', domain: 'SonataUserBundle'}
            - { route: 'sonata_customer_addresses', label: 'link_list_addresses', domain: 'SonataCustomerBundle'}
            - { route: 'sonata_user_profile_edit_authentication', label: 'link_edit_authentication', domain: 'SonataUserBundle'}
            - { route: 'sonata_order_index', label: 'order_list', domain: 'SonataOrderBundle'}

#sonata_admin:
#    templates:
#        dashboard: SonataAdminBundle:Core:dashboard.html.twig

sonata_admin:
    title:      Admin Panel
    title_logo: /bundles/sonataadmin/logo_title.png
    templates:
        # default global templates
        layout:  SonataAdminBundle::standard_layout.html.twig
        ajax:    SonataAdminBundle::ajax_layout.html.twig

        # default actions templates, should extend a global templates
        list:    SonataAdminBundle:CRUD:list.html.twig
        show:    SonataAdminBundle:CRUD:show.html.twig
        edit:    SonataAdminBundle:CRUD:edit.html.twig
    dashboard:
        blocks:
            # display a dashboard block
            - { position: left, type: sonata.admin.block.admin_list }

sonata_block:
    default_contexts: [cms]
    blocks:
        sonata.admin.block.admin_list:
            contexts:   [admin]

        #sonata.admin_doctrine_orm.block.audit:
        #    contexts:   [admin]
        sonata.user.block.menu:
        sonata.user.block.account:
        sonata.block.service.text:
        sonata.block.service.action:
        sonata.block.service.rss:

sonata_doctrine_orm_admin:
    # default value is null, so doctrine uses the value defined in the configuration
    entity_manager: ~
    templates:
        form:
            - SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig
        filter:
            - SonataDoctrineORMAdminBundle:Form:filter_admin_fields.html.twig
        types:
            list:
                array:      SonataAdminBundle:CRUD:list_array.html.twig
                boolean:    SonataAdminBundle:CRUD:list_boolean.html.twig
                date:       SonataAdminBundle:CRUD:list_date.html.twig
                time:       SonataAdminBundle:CRUD:list_time.html.twig
                datetime:   SonataAdminBundle:CRUD:list_datetime.html.twig
                text:       SonataAdminBundle:CRUD:base_list_field.html.twig
                trans:      SonataAdminBundle:CRUD:list_trans.html.twig
                string:     SonataAdminBundle:CRUD:base_list_field.html.twig
                smallint:   SonataAdminBundle:CRUD:base_list_field.html.twig
                bigint:     SonataAdminBundle:CRUD:base_list_field.html.twig
                integer:    SonataAdminBundle:CRUD:base_list_field.html.twig
                decimal:    SonataAdminBundle:CRUD:base_list_field.html.twig
                identifier: SonataAdminBundle:CRUD:base_list_field.html.twig

            show:
                array:      SonataAdminBundle:CRUD:show_array.html.twig
                boolean:    SonataAdminBundle:CRUD:show_boolean.html.twig
                date:       SonataAdminBundle:CRUD:show_date.html.twig
                time:       SonataAdminBundle:CRUD:show_time.html.twig
                datetime:   SonataAdminBundle:CRUD:show_datetime.html.twig
                text:       SonataAdminBundle:CRUD:base_show_field.html.twig
                trans:      SonataAdminBundle:CRUD:show_trans.html.twig
                string:     SonataAdminBundle:CRUD:base_show_field.html.twig
                smallint:   SonataAdminBundle:CRUD:base_show_field.html.twig
                bigint:     SonataAdminBundle:CRUD:base_show_field.html.twig
                integer:    SonataAdminBundle:CRUD:base_show_field.html.twig
                decimal:    SonataAdminBundle:CRUD:base_show_field.html.twig

# Doctrine Configuration
doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        types:
            json: Sonata\Doctrine\Types\JsonType
        # if using pdo_sqlite as your database driver, add the path in parameters.yml
        # e.g. database_path: "%kernel.root_dir%/data/data.db3"
        # path:     "%database_path%"
    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        auto_mapping: true

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: MyProject\UserBundle\Entity\User
    group:
        group_class:   MyProject\UserBundle\Entity\Group
        group_manager: sonata.user.orm.group_manager

    service:
        user_manager: sonata.user.orm.user_manager

and my routing.yml here :
    sonata_user_security:
    resource: "@SonataUserBundle/Resources/config/routing/sonata_security_1.xml"

sonata_user_resetting:
    resource: "@SonataUserBundle/Resources/config/routing/sonata_resetting_1.xml"
    prefix: /resetting

sonata_user_profile:
    resource: "@SonataUserBundle/Resources/config/routing/sonata_profile_1.xml"
    prefix: /profile

sonata_user_register:
    resource: "@SonataUserBundle/Resources/config/routing/sonata_registration_1.xml"
    prefix: /register

sonata_user_change_password:
    resource: "@SonataUserBundle/Resources/config/routing/sonata_change_password_1.xml"
    prefix: /profile

sonata_user:
    resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml'
    prefix: /admin

admin:
    resource: '@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
    prefix: /admin

_sonata_admin:
    resource: .
    type: sonata_admin
    prefix: /admin

EDIT 1:
[router] Current routes
 Name                                     Method   Scheme Host Path
 _assetic_bootstrap_css                   ANY      ANY    ANY  /assetic/bootstrap_css.less
 _assetic_bootstrap_css_0                 ANY      ANY    ANY  /assetic/bootstrap_css_bootstrap_1.less
 _assetic_jquery                          ANY      ANY    ANY  /js/jquery.js
 _assetic_jquery_0                        ANY      ANY    ANY  /js/jquery_jquery-2.1.1_1.js
 _assetic_bootstrap_js                    ANY      ANY    ANY  /js/bootstrap.js
 _assetic_bootstrap_js_0                  ANY      ANY    ANY  /js/bootstrap_transition_1.js
 _assetic_bootstrap_js_1                  ANY      ANY    ANY  /js/bootstrap_alert_2.js
 _assetic_bootstrap_js_2                  ANY      ANY    ANY  /js/bootstrap_button_3.js
 _assetic_bootstrap_js_3                  ANY      ANY    ANY  /js/bootstrap_carousel_4.js
 _assetic_bootstrap_js_4                  ANY      ANY    ANY  /js/bootstrap_collapse_5.js
 _assetic_bootstrap_js_5                  ANY      ANY    ANY  /js/bootstrap_dropdown_6.js
 _assetic_bootstrap_js_6                  ANY      ANY    ANY  /js/bootstrap_modal_7.js
 _assetic_bootstrap_js_7                  ANY      ANY    ANY  /js/bootstrap_tooltip_8.js
 _assetic_bootstrap_js_8                  ANY      ANY    ANY  /js/bootstrap_popover_9.js
 _assetic_bootstrap_js_9                  ANY      ANY    ANY  /js/bootstrap_scrollspy_10.js
 _assetic_bootstrap_js_10                 ANY      ANY    ANY  /js/bootstrap_tab_11.js
 _assetic_bootstrap_js_11                 ANY      ANY    ANY  /js/bootstrap_affix_12.js
 _assetic_a56fa94                         ANY      ANY    ANY  /js/a56fa94.js
 _assetic_a56fa94_0                       ANY      ANY    ANY  /js/a56fa94_part_1.js
 _assetic_a56fa94_1                       ANY      ANY    ANY  /js/a56fa94_part_2.js
 _assetic_65cec74                         ANY      ANY    ANY  /css/65cec74.css
 _wdt                                     ANY      ANY    ANY  /_wdt/{token}
 _profiler_home                           ANY      ANY    ANY  /_profiler/
 _profiler_search                         ANY      ANY    ANY  /_profiler/search
 _profiler_search_bar                     ANY      ANY    ANY  /_profiler/search_bar
 _profiler_purge                          ANY      ANY    ANY  /_profiler/purge
 _profiler_info                           ANY      ANY    ANY  /_profiler/info/{about}
 _profiler_import                         ANY      ANY    ANY  /_profiler/import
 _profiler_export                         ANY      ANY    ANY  /_profiler/export/{token}.txt
 _profiler_phpinfo                        ANY      ANY    ANY  /_profiler/phpinfo
 _profiler_search_results                 ANY      ANY    ANY  /_profiler/{token}/search/results
 _profiler                                ANY      ANY    ANY  /_profiler/{token}
 _profiler_router                         ANY      ANY    ANY  /_profiler/{token}/router
 _profiler_exception                      ANY      ANY    ANY  /_profiler/{token}/exception
 _profiler_exception_css                  ANY      ANY    ANY  /_profiler/{token}/exception.css
 _configurator_home                       ANY      ANY    ANY  /_configurator/
 _configurator_step                       ANY      ANY    ANY  /_configurator/step/{index}
 _configurator_final                      ANY      ANY    ANY  /_configurator/final
 fos_user_security_login                  ANY      ANY    ANY  /login
 fos_user_security_check                  POST     ANY    ANY  /login_check
 fos_user_security_logout                 ANY      ANY    ANY  /logout
 sonata_user_security_login               ANY      ANY    ANY  /login
 sonata_user_security_check               POST     ANY    ANY  /login_check
 sonata_user_security_logout              ANY      ANY    ANY  /logout
 fos_user_resetting_request               GET      ANY    ANY  /resetting/request
 fos_user_resetting_send_email            POST     ANY    ANY  /resetting/send-email
 fos_user_resetting_check_email           GET      ANY    ANY  /resetting/check-email
 fos_user_resetting_reset                 GET|POST ANY    ANY  /resetting/reset/{token}
 sonata_user_resetting_request            GET      ANY    ANY  /resetting/request
 sonata_user_resetting_send_email         POST     ANY    ANY  /resetting/send-email
 sonata_user_resetting_check_email        GET      ANY    ANY  /resetting/check-email
 sonata_user_resetting_reset              GET|POST ANY    ANY  /resetting/reset/{token}
 fos_user_profile_show                    GET      ANY    ANY  /profile/
 fos_user_profile_edit_authentication     ANY      ANY    ANY  /profile/edit-authentication
 fos_user_profile_edit                    ANY      ANY    ANY  /profile/edit-profile
 sonata_user_profile_show                 GET      ANY    ANY  /profile/
 sonata_user_profile_edit_authentication  ANY      ANY    ANY  /profile/edit-authentication
 sonata_user_profile_edit                 ANY      ANY    ANY  /profile/edit-profile
 fos_user_registration_register           ANY      ANY    ANY  /register/
 fos_user_registration_check_email        GET      ANY    ANY  /register/check-email
 fos_user_registration_confirm            GET      ANY    ANY  /register/confirm/{token}
 fos_user_registration_confirmed          GET      ANY    ANY  /register/confirmed
 sonata_user_registration_register        ANY      ANY    ANY  /register/
 sonata_user_registration_check_email     GET      ANY    ANY  /register/check-email
 sonata_user_registration_confirm         GET      ANY    ANY  /register/confirm/{token}
 sonata_user_registration_confirmed       GET      ANY    ANY  /register/confirmed
 fos_user_change_password                 GET|POST ANY    ANY  /profile/change-password
 sonata_user_change_password              GET|POST ANY    ANY  /profile/change-password
 sonata_user_admin_security_login         ANY      ANY    ANY  /admin/login
 sonata_user_admin_security_check         ANY      ANY    ANY  /admin/login_check
 sonata_user_admin_security_logout        ANY      ANY    ANY  /admin/logout
 sonata_admin_redirect                    ANY      ANY    ANY  /admin/
 sonata_admin_dashboard                   ANY      ANY    ANY  /admin/dashboard
 sonata_admin_retrieve_form_element       ANY      ANY    ANY  /admin/core/get-form-field-element
 sonata_admin_append_form_element         ANY      ANY    ANY  /admin/core/append-form-field-element
 sonata_admin_short_object_information    ANY      ANY    ANY  /admin/core/get-short-object-description.{_format}
 sonata_admin_set_object_field_value      ANY      ANY    ANY  /admin/core/set-object-field-value
 sonata_admin_search                      ANY      ANY    ANY  /admin/search
 sonata_admin_retrieve_autocomplete_items ANY      ANY    ANY  /admin/core/get-autocomplete-items
 admin_sonata_user_user_list              ANY      ANY    ANY  /admin/sonata/user/user/list
 admin_sonata_user_user_create            ANY      ANY    ANY  /admin/sonata/user/user/create
 admin_sonata_user_user_batch             ANY      ANY    ANY  /admin/sonata/user/user/batch
 admin_sonata_user_user_edit              ANY      ANY    ANY  /admin/sonata/user/user/{id}/edit
 admin_sonata_user_user_delete            ANY      ANY    ANY  /admin/sonata/user/user/{id}/delete
 admin_sonata_user_user_show              ANY      ANY    ANY  /admin/sonata/user/user/{id}/show
 admin_sonata_user_user_export            ANY      ANY    ANY  /admin/sonata/user/user/export
 admin_sonata_user_group_list             ANY      ANY    ANY  /admin/sonata/user/group/list
 admin_sonata_user_group_create           ANY      ANY    ANY  /admin/sonata/user/group/create
 admin_sonata_user_group_batch            ANY      ANY    ANY  /admin/sonata/user/group/batch
 admin_sonata_user_group_edit             ANY      ANY    ANY  /admin/sonata/user/group/{id}/edit
 admin_sonata_user_group_delete           ANY      ANY    ANY  /admin/sonata/user/group/{id}/delete
 admin_sonata_user_group_show             ANY      ANY    ANY  /admin/sonata/user/group/{id}/show
 admin_sonata_user_group_export           ANY      ANY    ANY  /admin/sonata/user/group/export
 myproject_user_default_index            ANY      ANY    ANY  /hello/{name}
 myproject_comment_default_index         ANY      ANY    ANY  /hello/{name}
 myproject_provider_default_index        ANY      ANY    ANY  /hello/{name}
 myproject_provider_providersearch_index ANY      ANY    ANY  /ProviderSearch
 myproject_service_default_index         ANY      ANY    ANY  /hello/{name}
 myproject_geo_default_index             ANY      ANY    ANY  /hello/{name}
 myproject_schedule_default_index        ANY      ANY    ANY  /hello/{name}
 myproject_coupon_couponsearch_index     ANY      ANY    ANY  /couponSearch
 my_filter                                ANY      ANY    ANY  /filter/
 myproject_coupon_default_index          ANY      ANY    ANY  /coupon
 myproject_association_search            ANY      ANY    ANY  /associationSearch
 myproject_association_search_result     ANY      ANY    ANY  /associationSearch/result
 myproject_association_search_show       ANY      ANY    ANY  /association/{slug}
 myproject_contact                       ANY      ANY    ANY  /contact
 myproject_core_homepage                 ANY      ANY    ANY  /
 myproject_city_typeahead                ANY      ANY    ANY  /autocompleteCity
 myproject_assoName_typeahead            ANY      ANY    ANY  /autocompleteAssoName
 myproject_providerName_typeahead        ANY      ANY    ANY  /autocompleteProviderName
 myproject_core_static                   ANY      ANY    ANY  /{page}
 myproject_coupon                        ANY      ANY    ANY  /coupon
 myproject_coupon_search                 ANY      ANY    ANY  /couponSearch
 myproject_coupon_search_result          ANY      ANY    ANY  /couponSearch/result
 myproject_provider_search_show          ANY      ANY    ANY  /provider/{slug}
 fos_js_routing_js                        ANY      ANY    ANY  /js/routing.{_format}

A:

Ok I finally got a dashboard by removing all in sonata_user like this :
sonata_user:
    security_acl:           true
    manager_type: orm

I try to get a Dashboard like in this documentation : http://sonata-project.org/bundles/user/2-2/doc/reference/user_dashboard.html without success.
I have a blank page now, I will do all dashboard on my own,I can't see other way...


Q:

How to combine multiple variable data to a single variable data?

After making my data frame, and selecting the variables i want to look at, i face a dilemma. The excel sheet which acts as my data source was used by different people recording the same type of data.
Mock     Neg Neg1PCR Neg2PCR  NegPBS     red     Red RedWine   water   Water   white   White
  1       9       1       1       1       2      18       4       4       4       2      26

As you can see, because the data is written diffently, Major groups (Redwine, Whitewine and Water) have now been split into undergroups . How do i combine the undergroups into a combined group eg. red+Red+RedWine -> Total wine. I use the phyloseq package for this kind of dataset

A:

names <- c("red","white","water")
df2 <- setNames(data.frame(matrix(ncol = length(names), nrow = nrow(df))),names)

for(col in names){
  df2[,col] <- rowSums(df[,grep(col,tolower(names(df)))])
}

here
grep(col,tolower(names(df)))

looks for all the column names that contain the strings like "red" in the names of your vector. You then just sum them in a new data.frame df2 defined with the good lengths


Q:

What is @csrf_exempt

I am a newbie in django-rest-framework. I don't know very well about this. What is "@csrf_exempt"? Why should we use this in our views.py? Please help me with the details.
And also if there is any other option of "@csrf_exempt" please tell me that too.

A:

Normally when you make a request via a form you want the form being submitted to your view to originate from your website and not come from some other domain. To ensure that this happens, you can put a csrf token in your form for your view to recognize. If you add @csrf_exempt to the top of your view, then you are basically telling the view  that it doesn't need the token. This is a security exemption that you should take seriously.

A:

The decorator marks a view as being exempt from the protection ensured by the middleware. Example:
    from django.http import HttpResponse
    from django.views.decorators.csrf import csrf_exempt

    @csrf_exempt
    def my_view(request):
        return HttpResponse('Hello world')

Check out the documentations for  csrf Cross Site Request Forgery protection.
A good way to read documentation of a stack you are using would be to use something like zeal to get reference.


Q:

iOS 4.2 simulator files?

Where are the files associated with my app in the iOS 4.2 simulator - need to look at my sqllite DB and I can't find it.

A:

~/Library/Application Support/iPhone Simulator/4.2/Applications/APP_UUID/
In Xcode 6, check
~/Library/Developer/CoreSimulator/Devices/DEVICE_UUID/data/Containers/Data/Application/APP_UUID/


Q:

What happened to the Spring Modules project?

I read on Spring web site that the Spring Modules project is now deprecated in favor of Spring Extensions. However, unless I am missing something, Spring Extensions does not support Lucene like Spring Modules did.
Am I missing something?

A:

No, I don't think you're missing anything. Users of Spring Modules were rather left in the lurch, I feel.
There is an alternative to Spring Lucene, though, which is Compass. Rather than being a library to make lucene easier, it actually provides an abstraction layer on top of Lucene. I like it, I;ve used it for several lucene-based projects now, it's good quality.


Q:

How to convert a big list of comma-separated numbers into float

I need to make a script, which takes 2 columns of data from 2 columns of .csv file and then plot a graph based on this data. I managed to export data from columns as such list (there are actually 140 nubmers, but you got the idea):
['0', '0,1', '0,2', '0,3', '0,4', '0,5', '0,6', '0,7', '0,8000001', '0,9000001', '1', '1,1', '1,2']

The problem is, when i try to plot with this data, matplotlib gives an error, because it's not float numbers. And I can't convert this data to float, because numbers are separated with commas, instead of dots. So, how can I replace all this commas with dots or maybe there are some other easier solutions to this? I'm totally new to Python.
Update: My mistake, the format I exported data in is not list, but DICT. I could succesfully convert it into a long string, but can't find a way to convert it into an array of floats. Thanks for all your help.

A:

n = ['0', '0,1', '0,2', '0,3', '0,4', '0,5', '0,6', '0,7',
     '0,8000001', '0,9000001', '1', '1,1', '1,2']
[float(m.replace(",", ".")) for m in n]
# => [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7,
#     0.8000001, 0.9000001, 1.0, 1.1, 1.2]


Q:

How can I use the Text.RSS module in an application already using Text.XmlHtml without also importing Text.XML.HaXml?

I have an pretty stereotypical weblogging application that I've been working on for practice.  The top level of my application is a Happstack layer using pretty standard routing.  I have gotten to the point where I want to add an XML feed to the code.
Here's the part that bothers me.  Since I used Heist for templating, I have already brought in the Text.XmlHtml module as part of working with Heist.  Using Text.RSS requires that I bring in Text.XML.HaXml, too.  It seems excessive to me to need to use two different XML modules in the same application.
So, short of writing my own RSS feed (and probably doing it wrong/in violation of spec/investing a ton of excessive time), is there any way to stick with just a single XML library in my application?  Also, is there any serious drawback or code bloat to having two different XML modules present?

A:

If you want to use Text.RSS, then no.  XmlHtml was written specifically because Heist has some unique requirements for it's underlying xml library and none of the existing ones were sufficient.  If you don't want to use Text.RSS, then you could always write your own version backed by XmlHtml or try to port Text.RSS to it.


Q:

What's the difference between a 'var' declared variable and 'this' created property in Javascript?

first using var
 function testCode(some)
    {
         var something = some;
    }

the second using this
function testCode2(some)
{
     this.something = some ;
}

A:

In the first function, something is a private (local) variable, meaning it will be completely inaccessible outside the function; whilst in the second it's a public instance variable. The context on which the variable will be set will depend on how you invoke the function:
> testCode2("foo"); // this will refer to document.window
> something
"foo"

>> var obj = new testCode2("foo"); // this will refer to the new object
>> something
ReferenceError: something is not defined
>> obj.something
"foo"

Reference:

Private Members in JavaScript, by Douglas Crockford

A:

If those functions are used as functions, the this keyword will make the variable static. If the function is called twice, this.something will still have its value while the first subject will erase the variable data once the function has finished executing.
If you are using them as class constructors, var will define a private variable and this will declare a public variable.
See this fiddle: http://jsfiddle.net/UUFuX/1/


Q:

System.abortJob() from APEX test method

I have a Schedulable APEX class that applies System.abortJob() on multiple CronTrigger.
I need to cover in test this method but I am afraid of the behaviour:

In a Test context, how is the CronTrigger table ?
If it is shared with non test context, will the job aborting be rollbacked outside the test context ?

UPDATE: code example
global ScheduledCronDelete implements Schedulable {

  global void execute(ScheduleContext context) {

    for (CronTrigger job: [
      SELECT Id, State, CronjobDetail.Name, CronJobDetail.Id, NextFireTime
      FROM CronTrigger
      WHERE NextFireTime = NULL
      AND CronJobDetail.Name LIKE 'CronJobNameToDelete%'
    ]) {
      System.abortJob(job.Id);
    }

  }
}

How can I do APEX tests over this ?

A:

To write any Apex Job always remember to create one helper method that will contain your Job logic. Call helper method from execute method by passing appropriate parameters. Why I'm recommending this because it will keep your code modularize and easy to test it. Specially from test class.
Also when you deploy your code to client side, imagine how your clients are going to test your Apex Job. You should not expect that they will go to developer console to schedule your job and wait until your job gets executed (specially if your Job will execute after 1 month). Am I right?. So having helper method is always a good practice. You can build VF page and simply invoke helper method to show how your Job will run without the need of scheduling a Apex job.
I've restructured your Apex Job so that it is convenient to test it and incorporates above point which I mentioned.
Apex Job
global class ScheduledCronDelete implements Schedulable {

    global ScheduledCronDelete () {

    }
    global void execute(SchedulableContext sc) {
        // passing null since it's a legitimate call from Apex Job and
        // not from test class or any VF page
        helperMethod(null);
    }
    public void helperMethod(String jobName) {
        List<CronTrigger> lstJobs = new List<CronTrigger>();
        String query = 'SELECT Id, State, CronjobDetail.Name, CronJobDetail.Id, NextFireTime FROM CronTrigger WHERE ';
        // if jobName is null then it is invoke from execute class
        if(jobName == NULL) {
            String name = 'CronJobNameToDelete%';
            query = query + ' CronJobDetail.Name LIKE \''+name+'\'';

        } else {
            // it's a simple use case for testing purpose
            query = query + ' CronJobDetail.Name LIKE \''+jobName+'%\'';
        }
        System.debug(query);
        lstJobs = Database.query(query);

        if(lstJobs.size() > 0) {
            for (CronTrigger job : lstJobs)
                System.abortJob(job.Id);
        }
    }
}

Test Class
@isTest
public class JobTest {
    static @isTest void myTest () {
        test.startTest();
            String hour = String.valueOf(Datetime.now().hour());
            String min = String.valueOf(Datetime.now().minute() + 1); String ss = String.valueOf(Datetime.now().second());

            //parse to cron expression
            String nextFireTime = ss + ' ' + min + ' ' + hour + ' * * ?';
            ScheduledCronDelete s = new ScheduledCronDelete();
            System.schedule('CronJobNameToDelete' + String.valueOf(Datetime.now()), nextFireTime, s);

            System.schedule('TestJob' + String.valueOf(Datetime.now()), nextFireTime, s);
            String jobName = 'TestJob';
            s.helperMethod(jobName);
        test.stopTest();
    }
}

Above test class will give you 100% code coverage.
And your doubts:

In a Test context, how is the CronTrigger table ? --> It doesn't affect your already schedule Jobs. I tried it and it didn't affected existing job. Give it a try.
If it is shared with non test context, will the job aborting be rollbacked outside the test context ? --> Once you try for point 1 you will eventually get the answer for this question.


Q:

Wrapping text in a table column

So I have this table, which I just used an online tool to create, but I want the columns to wrap. So, I just change \begin{tabular} to \begin{tabularx} and then the last column vertical line is about 1cm from the table... How can I fix that gap?
\begin{tabularx}{\textwidth}{|X|X|X|X|}
\hline
Name:                                      & Donald Trump                              & Student ID:                                         & 99999999                                     \\ \hline
\multicolumn{2}{|p{0.5\textwidth}|}{Feedback focus:}                                                 & \multicolumn{2}{p{0.5\textwidth}|}{asoidjfaopsidjfp oiajdfpo iasjdfp oiasjdfpo ij}                                \\ \hline
\multicolumn{2}{|p{0.5\textwidth}|}{askdljf ;laksjdf;l aksjdf;lkajsd;:}                          & \multicolumn{2}{l|}{as;ldifja;lsdkfja;lsdkfja; slkfj; aldkjf ;aslkdj ;alk}                         \\ \hline \hline
\multicolumn{4}{|p{\textwidth}|}{as;ldkf;lkj: aklsduhf asldkj f;alskdjf ;alskdjf ;alskdf }                                                                  \\ \hline
Fully Met                                  & Met                                      & Partially Met                                       & Not Met                                      \\ \hline
Comments:                                  & \multicolumn{3}{l|}{}                                                                                \\ \hline
\multicolumn{4}{|p{\textwidth}|}{asldkjf;alksdj f;laksjdf:as;dlk ja;lsdk fjas;ldkfj a;slkdfj ;lakasdlk;jkdj }                                                                               \\ \hline
Fully Met                                  & Met                                      & Partially Met                                       & Not Met                                      \\ \hline
Comments:                                  & \multicolumn{3}{l|}{}                                                                                \\ \hline
\multicolumn{4}{|p{\textwidth}|}{a;lsdkjf; lakj;l3: alkjdsf l;aksjdf;l kasjd;lf kjasd;l fkjas;ldkfjas;ldkf jas;ldkf ja;sldkfj asldkfj alksjferopijp34qjp asdf} \\ \hline
Fully Met                                  & Met                                      & Partially Met                                       & Not Met                                      \\ \hline
Comments:                                  & \multicolumn{3}{l|}{}                                                                                \\ \hline
\multicolumn{4}{|p{\textwidth}|}{as;ldkfjal;kej ;l4: alskdjf ;lasdkjf ;alskdjf ;laskd}                                                                                \\ \hline
Fully Met                                  & Met                                      & Partially Met                                       & Not Met                                      \\ \hline
Comments:                                  & \multicolumn{3}{l|}{}                                                                                \\ \hline
\multicolumn{4}{|p{\textwidth}|}{asl;dkjf;lk4j: asl;dkjfaslkdjf eirkajp (asl;dkfj a) aslkdjf l}                                                                                \\ \hline
Fully Met                                  & Met                                      & Partially Met                                       & Not Met                                      \\ \hline
Comments:                                  & \multicolumn{3}{l|}{}                                                                                \\ \hline
\end{tabularx}

Gives:

A:

(rewrote parts of the answer to incorporate @Zarko's comments and observations)
Your column-width calculations aren't taking into account that space needs to be set aside for (a) the whitespace padding around columns and (b) the widths of the vertical lines. You need to

replace all instances of
\multicolumn{2}{|p{0.5\textwidth}|}

with
\multicolumn{2}{|P\lengtha}|}

and replace all instances of
\multicolumn{4}{|p{\textwidth}|}

with
\multicolumn{4}{|P{\lengthb}|}

where \lengtha and \lengthb are defined in the code shown below. P is defined via the instruction
\newcolumntype{P}[1]{>{\RaggedRight\arraybackslash}p{#1}}

The \RaggedRight instruction, provided by the ragged2e package, serves to typeset the material in ragged-right moder rather in fully-justified mode, while still permitting hyphenation. (Because the columns are quite narrow, it is much more difficult to fully justify the column text satisfactorily. Better to go to ragged-right mode immediately.)
Furthermore, instructions such as
\multicolumn{2}{l|}{as;ldifja;lsdkfja;lsdkfja; slkfj; aldkjf ;aslkdj ;alk}

seriously mess up the appearance of the table because the l column type doesn't allow automatic line breaking. You should either have only short strings in columns that don't allow line breaking or not use the l column type to begin with. My recommendation is to replace all instances of \multicolumn{2}{l|} with \multicolumn{2}{P{\lengtha}|}.
An additional note about the code: I've also defined a variant of the X column type, called Y, that typesets its material in ragged-right rather than in fully-justified mode. The Y column type is used for the main column definitions.

\documentclass{article}
\usepackage{tabularx,ragged2e}
% "\RaggedRight" allows hyphenation
\newcolumntype{P}[1]{>{\RaggedRight\arraybackslash}p{#1}}
\newcolumntype{Y}{>{\RaggedRight\arraybackslash}X}

\newlength\lengthx % basic column width
\setlength{\lengthx}{\dimexpr0.25\textwidth-2\tabcolsep-1.25\arrayrulewidth\relax}
\newlength\lengtha % width of two-columm multicolumn
\setlength{\lengtha}{\dimexpr2\lengthx+2\tabcolsep+1\arrayrulewidth\relax}
\newlength\lengthb % width of four-columm multicolumn
\setlength{\lengthb}{\dimexpr\textwidth-2\tabcolsep-2\arrayrulewidth\relax}

\begin{document}
\noindent % <--- this is necessary
\begingroup
\setlength\extrarowheight{2pt} % optional: go for a more open "look"
\begin{tabularx}{\textwidth}{|Y|Y|Y|Y|}
\hline
Name: & XYZ & Student ID: & 99999999
\\ \hline
\multicolumn{2}{|P{\lengtha}|}{Feedback focus:} &
\multicolumn{2}{ P{\lengtha}|}{asoidjfaopsidjfp oiajdfpo iasjdfp oiasjdfpo ij}
\\ \hline
\multicolumn{2}{|P{\lengtha}|}{askdljf ;laksjdf;l aksjdf;lkajsd;:} &
\multicolumn{2}{ P{\lengtha}|}{as;ldifja;lsdkfja;lsdkfja; slkfj; aldkjf ;aslkdj ;alk}
\\ \hline \hline
\multicolumn{4}{|P{\lengthb}|}{as;ldkf;lkj: aklsduhf asl dkj f;als kdjf ;als kdjf ;alskdf }
\\ \hline
Fully Met & Met & Partially Met & Not Met
\\ \hline
Comments: & \multicolumn{3}{l|}{}
\\ \hline \hline
\multicolumn{4}{|P{\lengthb}|}{asldkjf;alksdj f;lak sjdf:as;dlk ja;lsdk fjas;ldkfj a;s lkdfj ;lak asdlk;jkdj }
\\ \hline
Fully Met & Met & Partially Met & Not Met
\\ \hline
Comments: & \multicolumn{3}{l|}{}
\\ \hline \hline
\multicolumn{4}{|P{\lengthb}|}{a;lsdkjf; lakj;l3: alkjdsf l;ak sjdf;l ka sjd;lf kjasd;l fkjas;ld kfjas; ldkf jas ;ldkf ja;s ldkfj asl dkfj alk sjfe ropij p34qjp asdf}
\\ \hline
Fully Met & Met & Partially Met & Not Met
\\ \hline
Comments: & \multicolumn{3}{l|}{}
\\ \hline \hline
\multicolumn{4}{|P{\lengthb}|}{as;ldkfjal;kej ;l4: alskdjf ;lasdkjf ;alskdjf ;laskd}
\\ \hline
Fully Met & Met & Partially Met & Not Met
\\ \hline
Comments: & \multicolumn{3}{l|}{}
\\ \hline \hline
\multicolumn{4}{|P{\lengthb}|}{asl;dkjf;lk4j: asl;dkjfaslkdjf eirkajp (asl;dkfj a) aslkdjf l}
\\ \hline
Fully Met & Met & Partially Met & Not Met
\\ \hline
Comments: & \multicolumn{3}{l|}{}
\\ \hline
\end{tabularx}
\endgroup
\end{document}


Q:

Is a parallel Spring-MVC application possible with a non-spring web app?

I have a Tomcat application pretty huge. Very ctitical to the business (real money making). But it is legacy Java code. Meaning, JSP (with a lot of Javascript, Java code), Servlets (with thousands of lines of code) and so on. We want to get away from this crappy code. Now a request has come for another application (different purpose, different functionality). We need it at another context root /NewApp lets say under the legacy application directory structure. Like a mini-site. It will have a different URL, could even be serving a few virtual hosts.
We dont want to extend the Legacy code. We want to move to better technologies and better way of doing things. We are strongly for Spring (tiles, jackson etc. etc.) and all the things it has to offer including portlets. So, we are thinking of possibilities of bringing in DispatcherServlet/ContextLoaderListener/configLocation etc into the legacy app web.xml and have a spring app side by side.
The main reason is the new app has serious dependencies on the legacy services and libraries.

Is this peaceful coexistance possible?
What are the challenges that we could possibly face?
Can you please point us to any example configurations?

We cant separate them out unfortunately. Appreciate your insight into this.
Thank you!!

A:

We went through a similar use case some time ago, while migrating moderately large application from EJB 2.1 to Spring. For a great deal of time Spring beans were coexisting with EJBs. We were choosing leafs in the dependency hierarchy first, so that Spring beans depended on EJBs but not the other way around. This was working beautifully, beans were calling EJBs like any other bean thanks to Spring proxies and dependency injection.
In the same application we had both Struts 1 and Wicket for new pages (damn, there were even Wicket iframes inside Struts pages!), we even had legacy JDBC-based persistence solution side by side with JPA. It all worked well.
Things to keep in mind:

It's still one application, watch out for back-end caching
Treat legacy services like Spring beans. Build some bridges/proxies/adapters, inject legacy services just like you inject other beans. Do not depend on legacy APIs (I imagine some singletons, factories, JNDI lookups)
Testing borders between old and new will be hard, prepare for a lot of mocking.
Think about web security, can you integrate both "applications" easily?
Let's face it, you'll never completely rewrite old code to new technologies. By that time new technologies will become old as well and new developers will come in. But try improving the quality of old code bit-by-bit every time. Refactoring can do miracles!

There is nothing special with configuration. It's a misunderstanding that Spring has to rule your whole application. It can be used as a lightweight, thin add-on, living next to the rest of your application.


Q:

Looping "complex" object with ItemsControl

I have the following "element":
public class ReportElementViewModel
{
    public string Name
    {
        get { return _name; }
        set
        {
            if (_name != value)
            {
                _name = value;
                RaisePropertyChanged("Name");
            }
        }
    }

    public bool IsChecked
    {
        get { return _isChecked; }
        set
        {
            if (_isChecked != value)
            {
                _isChecked = value;
                RaisePropertyChanged("IsChecked");
            }
        }
    }
}

My ViewModel contains many ReportElementViewModels:
public abstract class ReportViewModel<TPrimaryModel> : SharedViewModel
    where TPrimaryModel : Model, new()
{
    public ObservableCollection<ReportElementViewModel> ReportElementViewModels
    {
        get { return _reportElementViewModels; }
        set
        {
            if (_reportElementViewModels != value)
            {
                _reportElementViewModels = value;
                RaisePropertyChanged("ReportElementViewModels");
            }
        }
    }
}

I removed the members to reduce code complexity but they are implemented correctly.
In my view I want to show all ReportElementViewModels by showing their Name and IsChecked (checkbox).
I thought the ItemsControl would be the right "tool", however it doesn't work (nothing is shown):
<ItemsControl ItemsSource="{Binding ReportElemetViewModels}" Height="auto" VerticalAlignment="Top" Grid.Row="1">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="269"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

A:

You have made a spelling mistake in your Binding.
ItemsSource="{Binding ReportElemetViewModels}"

Should be:
ItemsSource="{Binding ReportElementViewModels}"


Q:

linux shell installing packages automaticc

I want to install packages automatically by running a script
I can write
 yum install php

but I want it to install another package once installation of the php package is completed
Is  there any solution to make it automatic?
I have around 20packages which are to be downloaded from remi repository

A:

Write your script named installer.sh as:
#!/bin/bash
yum -y install php
yum -y install <another_package>
yum -y install <yet_another_package>
...

Then run it $ bash installer.sh


Q:

Modify photos of the album photo

I'm trying to develop an application that modify photos of the album photo, (exactly adding tags to the photos).
It is possible to modify the content of the album photo from the application? (replace the photo with the tagged one)?
If it's possible, it is best to copy the picture in the sandbox, edit it, and send it back to the album photo or modify directly the photo without copying it in the application sandbox?

A:

No you can't not change a photo in the photo album.
You can copy them, them edit them and add a new photo to the photo album.
You can use UIImagePickerController to allow the user to select an image from the photo library. Or use AssetsLibrary to roll your own image picker.
You will have to use UIImageWriteToSavedPhotosAlbum to save the an UIImage to the photo library.


Q:

JPA / Hibernate: CriteriaBuilder - How to create query using relationship object?

I have the following four tables:
SCHEDULE_REQUEST TABLE:
ID,
APPLICATION_ID (FK)
APPLICATION TABLE:
ID,
CODE
USER_APPLICATION TABLE:
APPLICATION_ID (FK),
USER_ID (FK)
USER TABLE:
ID,
NAME
Now I wanted to create a CriteriaBuilder where condition is to select ScheduleRequests for specified user Ids.
I have the following codes:
List<User> usersList = getSelectedUsers(); // userList contains users I wanted to select

CriteriaBuilder builder = getJpaTemplate().getEntityManagerFactory().getCriteriaBuilder();
CriteriaQuery<ScheduleRequest> criteria = builder.createQuery(ScheduleRequest.class);
Root<ScheduleRequest> scheduleRequest = criteria.from(ScheduleRequest.class);
criteria = criteria.select(scheduleRequest);

ParameterExpression<User> usersIdsParam = null;
if (usersList != null) {
    usersIdsParam = builder.parameter(User.class);
    params.add(builder.equal(scheduleRequest.get("application.userApplications.user"), usersIdsParam));
}

criteria = criteria.where(params.toArray(new Predicate[0]));

TypedQuery<ScheduleRequest> query = getJpaTemplate().getEntityManagerFactory().createEntityManager().createQuery(criteria);

// Compile Time Error here:
// The method setParameter(Parameter<T>, T) in the type TypedQuery<ScheduleRequest> is not
// applicable for the arguments (ParameterExpression<User>, List<User>)
query.setParameter(usersIdsParam, usersList);

return query.getResultList();

Can you please help me how to pass query filter to a relationship object?
I think what I did in "application.userApplications.user" is wrong?
Please really need help.
Thank you in advance!

A:

Using the canonical Metamodel and a couple of joins, it should work. Try if you get some hints from the following pseudo-code (not tested):
...
Predicate predicate = cb.disjunction();
if (usersList != null) {
    ListJoin<ScheduleRequest, Application> applications = scheduleRequest.join(ScheduleRequest_.applications);
    ListJoin<Application, UserApplication> userApplications = applications.join(Application_.userApplications);
    Join<UserApplication, User> user = userApplications.join(UserApplication_.userId);
    for (String userName : usersList) {
        predicate = builder.or(predicate, builder.equal(user.get(User_.name), userName));
    }
}

criteria.where(predicate);
...

In order to understand Criteria Queries, have a look at these tutorials:
http://www.ibm.com/developerworks/java/library/j-typesafejpa/
http://docs.oracle.com/javaee/6/tutorial/doc/gjitv.html
The second link should also guide you on how to use Metamodel classes, that should be built automatically by the compiler / IDE.


Q:

Is an English will valid if the testator dies while living in Scotland?

If a testator makes a will while living in England, to what extent will it be valid if the testator—

permanently moves to Scotland, and
subsequently dies there without making a further will?

A:

(I am not your lawyer. I am not here to help you. If you are reading this because someone has died, please stop and instead read the Scottish Courts and Tribunals guide to dealing with a deceased's estate in Scotland, or contact a solicitor.)
Yes, in general. Section 1 of the Wills Act 1963, which is in force in Scotland, specifies that "[a] will shall be treated as properly executed if its execution conformed to the internal law in force in the territory where it was executed." Furthermore, Section 4 states that "[t]he construction of a will shall not be altered by reason of any change in the testator’s domicile after the execution of the will." "Construction" here refers to interpreting the language and effect of the will.
So if the will was validly executed in England, it should also be in force in Scotland, and a Scottish court will give it the same meaning it would have had under English law.
Furthermore, the same rule of validity seems to apply in both England and Scotland: Wills Act 1837 section 9.
There may be other Scottish laws affecting the disposition of the estate that differ from English law. Relevant statutes include Succession (Scotland) Act 1964, section 21A, which seems consistent with Wills Act 1963.
(I am trained in U.S. rather than English or Scottish law; I'm trusting the accuracy of the UK's excellent online legislation archive for the proposition that the statutes cited are in force in Scotland. I haven't checked the case law for contrary interpretations.)


Q:

How To Insert Data concurrently with the libpqxx API? (PostgreSQL,threads)

Stuff used:
Library: libpqxx:x64-windows version 6.4.4
OS: Windows 10
Compiler: Visual C++ (MSVC)
This is my SQL Table:
CREATE TABLE test(
    test_name VARCHAR(16)
);

This is my minimalistic test version:
main.cpp
#include <pqxx/pqxx>
#include "test.h"
int main()
{

    pqxx::connection database_connection("dbname = test user = postgres password = *****\
      hostaddr = 127.0.0.1 port = 5432");

    database_connection.prepare("insert_into_table", "INSERT INTO test \
    VALUES ($1)");

    test test(&database_connection);

    system("pause");
}

test.h
#pragma once
#include <pqxx/connection.hxx>
#include <thread>
#include <array>
class test
{
public:
    explicit test(pqxx::connection* database_connection);
    void InsertData();

    std::array<std::thread, 1> threads{};
    pqxx::connection* database_connection;
};

test.cpp
#include "test.h"
#include <iostream>
#include <pqxx/transaction.hxx>

test::test(pqxx::connection* database_connection) : database_connection(database_connection)
{
    for (auto& i : threads)
    {
        i = std::thread(&test::InsertData, this);
    }
}

void test::InsertData()
{

    pqxx::work work(*database_connection);
    try
    {

        pqxx::result result = work.exec_prepared("insert_into_table", "test_data"); //prepared data in real project pqxx::binarystring blobs

        work.commit();

    }
    catch (const std::exception& e) {
        work.abort();
    }

}

Changing the thread size in test.h to anything greater than 1 results in.
Note: I have to use a prepared SQL statement to later insert raw bytea data into my table.
Output:
Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB00FF050.
Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB03FEF50.
Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB04FED30.
Exception thrown at 0x00007FFC2FF44008 in Project3.exe: Microsoft C++ exception : pqxx::usage_error at memory location 0x000000CEB02FEAF0.
Debug Error!

How do I concurrently insert with this API?

A:

Link for solution: https://pqxx.org/development/libpqxx/wiki/Threading
Approaches for thread - safe programs

Approach 1: single database thread
Make one of your threads the dedicated "database thread." Ensure that that thread is the only one that ever accesses objects or functions from libpqxx.Use message - passing to channel all your database interactions through this thread.

This approach should be safe even if your libpq build is not thread - safe.

Approach 2 : global lock
Let multiple threads access objects and functions from libpqxx, but never simultaneously.Use a single, global lock to protect any access to libpqxx.

You do need a lock of some sort.You can't generally rely on other ways to know that thread 1 is done before thread 2 uses the library! Data from thread 1 may still be cached in a register or, depending on your system architecture, a processor cache that thread 2 isn't synchronized with.Or vice versa.It gets ugly and subtle.

Approach 3 : thread - local connections
Every connection in libpqxx acts as its own little world.It produces result objects, you create transactions on it, it uses error message callbacksand so forth.Keep all of the objects related to a connection exclusively inside the same thread that created the connection.This way you'll need no locking at all.

Of course you can still have more than one connection inside the same thread.This model should be fine for most applications, so this is probably as far as you'll want to read.

Approach 4 : per - connection locking
If you really have to share any libpqxx objects at all between threads, set up one lock per connection.This lock should protect all objects related to that connection.That way, all access to a connectionand its related objects will be serialized as if they all stayed in the same thread.

The risk of deadlocks may be slightly greater if you go this way.

In my case I changed the connection to
static thread_local database_connection;

so every thread has its own connection and then the code works without changing much.


Q:

Can a static class be set as delegate for a UItextfield (Objective C)?

In my current project I have a few viewcontrollers that use a UItextfield. As of now I have all the viewcontrollers set as delegates for the textField. However, I have all the same code for each of the viewcontrollers (at least for the UItextfield delegate methods). Is there a way I can just create a static class and set that as the delegate for all the UItextfields?

A:

You can achieve using two ways.

Once create a singleton class that can handle your delegates and assign the singleton instance as your delegate.
You can inherit the UITextField say myTextField and implement all the delegate methods which you want to override. For all the instances where you want to use TextField and have the custom behavior use myTextField.


Q:

Ghostscript error limitcheck in string

Why is the final part of my PDF creation process failing please.  See output from ps2pdf command below.  This is at the end of my own developed tool chain.  I harvest images from Matlab, stitch them together using LaTeX and then create the final PDF using latexmk.
This has worked fine until now when the document in question has grown to 3356 pages!
File position 238282 in file output.ps (as mentioned in the ghostscript error output) is towards the end of the "SDict begin [ {Catalog} << /PageLabels<>1<>2 " line.  This line is 51542 chars long and describes all 3356 pages.
Is this line length just too long now?  If I trim my .tex file down towards 3000 pages and re-run the latexmk it completes fine.
Running ps2pdf in isolation to show error.  Same error when run from latexmk:
C:\temp>c:\MiKTeX\miktex\bin\ps2pdf.exe output.ps output.pdf > error.txt 2>&1

Gave output:
Error: /limitcheck in --string--
Operand stack:
   --nostringval--   --nostringval--   --dict:1/1(L)--   PUT   --nostringval--   2   --nostringval--   2   false   --nostringval--   --nostringval--   (])   --nostringval--   --nostringval--   (3327)   --nostringval--   --nostringval--   P   1   .pdfcvstring   (<<\n/P \(3225\)\n>> 3226 <<\n/P \(32)   (<<\n/Nums [0 <<\n/P \(1\)\n>> 1 <<\n/P \(1\)\n>> 2 <<\n/P \(2\)\n>> 3 <<\n/P \(3\)\n>> 4 <<\n/P \(4\)\n>> 5 <<\n/P \(5\)\n>> 6 <<\n/P \(6\)\n>> 7 <<\n/P \(7\)\n>> 8 <<\n/P \(8\)\n>> 9 <<\n/P \(9\)\n>> 10 <<\n/P \(10\)\n>> 11 <<\n/P \(11\)\n>> 12 <<\n...)   65550
Execution stack:
   %interp_exit   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   --nostringval--   --nostringval--   false   1   %stopped_push   1910   1   3   %oparray_pop   1909   1   3   %oparray_pop   1893   1   3   %oparray_pop   1787   1   3   %oparray_pop   --nostringval--   %errorexec_pop   .runexec2   --nostringval--   --nostringval--   --nostringval--   2   %stopped_push   --nostringval--   1917   4   5   %oparray_pop   --nostringval--   3   1   2   --nostringval--   %for_pos_int_continue   --nostringval--   --nostringval--   --nostringval--   --dict:1/1(L)--   --nostringval--   1   %dict_continue   --nostringval--   --nostringval--   --nostringval--   --nostringval--   %array_continue   --nostringval--   --nostringval--   --dict:1/1(L)--   --nostringval--   1   %dict_continue   --nostringval--   --nostringval--   %zwritecvp_continue   1   %s_proc_write_continue   --nostringval--   --nostringval--   --nostringval--   --nostringval--
Dictionary stack:
   --dict:1159/1684(ro)(G)--   --dict:0/20(G)--   --dict:81/200(L)--   --dict:188/300(L)--   --dict:36/200(L)--   --dict:10/10(G)--
Current allocation mode is local
Last OS error: No such file or directory
Current file position is 238282
MiKTeX GPL Ghostscript  9.00: Unrecoverable error, exit code 1

Edit: Added my complete page labels line from the postscript file that goes into ps2pdf.  See pastebin entry http://pastebin.com/FFvZpaRY

A:

I ran pdfmark you provided with 9.10's pdfwrite device without error, but 9.00 fails with the same message as you show.

Ghostscript has been extended to support Postscript string and array
objects with >64k entries.

Update:
Assuming, that page labels you need are 1,1,2,3...3261 (don't know why, but that's what is in your example), it's simpler to add auto-incrementing numeric labels, not string prefixes as you do.
[{Catalog}<<
/PageLabels<</Nums[0<</S/D>>1<</S/D>>]>>
>> /PUT pdfmark

Or, if prefixes are what's necessary, split your big array into two or more:
[/_objdef{leaf1}/type/dict/OBJ pdfmark
[/_objdef{leaf2}/type/dict/OBJ pdfmark
[{leaf1}<</Limits[0 3000]
/Nums[
... 0 to 3000 labels go here ...
>>/PUT pdfmark
[{leaf2}<</Limits[3001 3261]
/Nums[
... 3001 to 3261 labels go here ...
>>/PUT pdfmark
[{Catalog}<</PageLabels<</Kids[{leaf1} {leaf2}]>>
>>/PUT pdfmark

Both these solutions work with 9.00


Q:

Second promise does not run (NodeJS)

I'm trying to learn promises in Nodejs. It happens that when i try to run two promises, the first one gets resolved, but the second one neither rejects or resolves.
UPDATE - promises does not run in order.
I tried both ways
let promiseConnectMongo = mongoDB.connectMongo();
let promiseCreateCollections = mongoDB.createCollections();

First:
promiseConnectMongo
.then((result) => {
    console.log(result);
    return promiseCreateCollections;
});

Second:
promiseConnectMongo.then((result) => {
    console.log(result);
    promiseCreateCollections.then((result) => {
        console.log(result);
    });

Both methods (not too fancy):
connectMongo: function () {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url, { useNewUrlParser: true }, (err, db) => {
            if (err)
                reject("Failed to connect db.\n")
            else {
                dbase = db.db(dbName);
                resolve("Connected sucessfully to the database: " + dbName);
            }
        });
    });

},

createCollections: function () {
    return new Promise((resolve, reject) => {

        console.log("Creating collections");

        dbase.createCollection("products", (err, result) => {
            if (err)
                reject(err);
            console.log(result);
        })
            .then(() => dbase.createCollection("bag", (err, result) => {
                if (err)
                    reject(err);
                console.log(result);
            }))
            .then(() => dbase.createCollection("brands", (err, result) => {
                if (err)
                    reject(err);
                console.log(result);
            }))

        resolve("Collections created sucessfully");
    });
}

The output is:

UPDATED OUTPUT

Why the second Promise running first?

A:

I think some of this is going to be related to how you are using promises. Specifically, I se you following this pattern:
somethingAsync
  .then(Math.random())
  .then(x => console.log(x)) // undefined

You might expect the random number but what is happening is you are passing the result of calling Math.random to the .then callback. You are following this pattern in a couple places, e.g.:
.then(dbase.createCollection("bag", (err, result) => ...))

Using the method like this means it doesn't wait for your createCollection to finish. It just passes an undefined down the pipeline. That means createCollections resolves almost immediately with undefined as its value.
You can solve this simply by wrapping your calls:
.then(() => dbase.createCollection("bag", (err, result) => ...))
//    ^^^^^