Q: How to insert dynamic image as option in php and mysql im currently developing a small school project that involve creating a style survey for an interior design website to identify the type of room that a client wish to decorate.
i created a dynamic list that will return the list of option from the database which will show the options in the form of images.
when the user click one of the image that shows the type of room, the page should automatically bring the user to next question and save the option that the user has clicked.
my problem now is I cannot insert the option chosen by the user into my database, the image that the user has click.
below is my code
<?php
$dynamicList = "";
$sql = mysqli_query($con,"SELECT * FROM room ORDER BY room_date");
$roomCount = mysqli_num_rows($sql);
if ($roomCount > 0) {

        while($row = mysqli_fetch_array($sql)){
             $id = $row["room_id"];
             $room_name = $row["room_name"];
             $room_date = strftime("%b %d, %Y", strtotime($row["room_date"]));
             $dynamicList .= '

' . $room_name . '

<?php
if (isset($_POST["id"])) {
    $id = $row["room_id"];
    $room_name = $row["room_name"];
    $survey_id = $row["survey_id"];
    $room_id = $row["room_id"];
    $date = strftime("%b %d, %Y", strtotime($row["date"]));
    $sql = mysqli_query($con,"INSERT INTO survey (survey_id , room_id, user_id, room_name, date) VALUES('$survey_id','$room_id','$_SESSION[usr_name]','$room_name',now())") or die (mysql_error());

        echo "Unable to insert data";
        exit();
    }

?>

A: Here you pass values as a get method you need to use $_GET['id'] like this
while($row = mysqli_fetch_array($sql)){
   $id = $row["room_id"];
   $room_name = $row["room_name"];
   $room_date = strftime("%b %d, %Y", strtotime($row["room_date"]));
   $dynamicList .= '

' . $room_name . '

';

  }
  } else {
   $dynamicList = "No room listed";
   }
  mysqli_close($con);
  ?>

<?php
if (isset($_GET["id"])) {
 $id = $_GET["room_id"];
 $room_name = $_GET["room_name"];
 $survey_id = $_GET["survey_id"];
 $date = $_GET["room_date"];
 $sql = mysqli_query($con,"INSERT INTO survey (survey_id , room_id, user_id,   room_name, date) VALUES('$survey_id','$room_id','$_SESSION[usr_name]','$room_name',now())") or  die (mysql_error());

    echo "Unable to insert data";
    exit();
}

?>

Now try this it should work


Q: Grails Searchable plugin and GORM marshalling I have an one-to-one relationship (hasOne in User domain and belongsTo in UserInfo domain). When the BootStrap is executing I get an exception:

org.compass.core.converter.ConversionException: Trying to marshall a null id [id] for alias [UserInfo]

this line of code produces it:
def user = new User(....., new UserInfo()).save()

A: According to Peter Ledbrook, this is a non-trivial conflict between Hibernate and Searchable: http://jira.grails.org/browse/GPSEARCHABLE-19
The solution is to turn off mirroring in the Searchable plugin and handle updating indexes manually.


Q: Ignite topology and partition owners left am facing below issue either when the Kubernetes or Ignite client nodes are getting restarted then we are not able to establish the connection to Ignite pods. We deployed the ignite as a Service and running in a Client/server mode.
Caused by: org.apache.ignite.internal.processors.cache.CacheInvalidStateException: Failed to execute the cache operation (all partition owners have left the grid, partition data has been lost)

class org.apache.ignite.internal.cluster.ClusterTopologyCheckedException: Failed to send message (node left topology): TcpDiscoveryNode [

And the below are the deployment and config details

<property name="dataStorageConfiguration">
            <bean class="org.apache.ignite.configuration.DataStorageConfiguration">
                <!-- Redefining the default region's settings -->
                <property name="defaultDataRegionConfiguration">
                    <bean class="org.apache.ignite.configuration.DataRegionConfiguration">
                        <property name="name" value="18GB_Region"/>
                        <!-- 2 GB initial size (RAM). -->
                        <property name="initialSize" value="#{2L * 1024 * 1024 * 1024}"/>
                        <!-- Setting the size of the default region to 20GB. -->
                        <property name="maxSize" value="#{20L * 1024 * 1024 * 1024}"/>
                        <!--property name="persistenceEnabled" value="true"/-->
                        <!-- Enabling RANDOM_LRU eviction for this region.  -->
                        <property name="pageEvictionMode" value="RANDOM_2_LRU"/>
                        <!-- Increasing the buffer size to 2 GB. -->
                        <property name="checkpointPageBufferSize" value="#{2L * 1024 * 1024 * 1024}"/>
                    </bean>
                </property>
                <!-- Set the page size to 8 KB -->
                <property name="pageSize" value="#{8 * 1024}"/>
                <!-- Changing WAL Mode. -->
                <property name="walMode" value="NONE"/>
                <!-- Enable write throttling. -->
                <property name="writeThrottlingEnabled" value="false"/>
            </bean>
        </property>
         <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.kubernetes.TcpDiscoveryKubernetesIpFinder">
                        <property name="masterUrl" value=""/>
                    </bean>
                </property>
            </bean>
        </property>


Q: How to calculate the probability of an event when you don't know the initial probabilities? Say there are two coins: coin A is fair, but coin B always comes up heads.
A friend then flips one of the two coins, and you observe that the coin came up heads.
How do you calculate the probability that this was coin A, when you don't know if your friend chose the coin randomly or not?

A: If you don't know your friend's motivation for picking the coin, it's very difficult to come up with a theoretical probability.
You have to somehow identify your current probability that your friend picked the fair coin... in Bayesian probability this is called the "prior" - your assessment of the probability before you collected the data. In the situation you describe, this might have to be a subjective decision. There is extensive discussion of "uninformative priors" at the link provided.
Remember, that probability is based on the information that you have, and can change depending on what new information you collect.
For example, if your friend makes some knowing wink or comment, you might interpret this as a reason to change your prior probability.
If I have some reason to know that my friend would have picked coin A (like, she prefers tails), then I might assess the probability of coin A to be 1, or under other circumstances 0, or indeed anything in between.
Suggestion: Unless you have some reason to believe that your friend picked in a particular way, it might be sensible to set your prior as though your friend chose randomly (in that case, the posterior probability of coin A would be 1/3).
If your chosen prior probability that your friend picked coin A is set at $p$,
then the resulting posterior probability (after you observe a head) that your friend picked coin A will be $(0.5p)/(1-0.5p)$.
Typically, the 'heads' observation will revise your probability of coin A downwards from the probability you initially thought (unless $p=0$ or $p=1$).

A: Assuming that your friend chose the coin randomly, what we are looking for is what is the probability that your friend chose coin A given that when he flipped it he got a heads. Note that this can we written as $P(\text{coin A}|\text{heads})$. To solve this we use the well known $P(A|B)=\frac{P(A\cap B)}{P(B)}$. Therefore we get $P(\text{coin A}|\text{heads})=\frac{P(\text{coin A}\cap\text{heads})}{P(\text{heads})}$. Using a tree diagram we can find that the probability of choosing coin A and then getting a heads is $\frac{1}{4}$ while the probaility of getting heads is $\frac{3}{4}$. Therefore we get $P(\text{coin A}|\text{heads})=\frac{0.25}{0.75}=\frac{1}{3}$

A: You can never arrive at an exact answer - you can only guess at how your friend chooses the coin, and then see how likely your guess is to be true.
You might make the hypothesis that your friend always chose coin $B$.  In that case, the probability of getting a head would be $0.5$ - you might not think that was likely enough, but most hypotheses are rejected only when they predict that the observed behaviour will occur with probability at most $0.1$.
You might suppose that your friend chooses the coins at random.  In that case, the probability of getting a head would be $0.75$ - that seems likely enough.
The fact that the coin landed heads is, unfortunately, not enough to tell you anything about how your friend had chosen the coin.  If it had landed on tails, then you would know that your friend had chosen $B$, and you would know that she had not adopted the strategy 'always choose heads', and you could be reasonably confident that she had not adopted the strategy 'choose heads with probability $0.99$; otherwise, choose tails'.  Of course, in that case, you would know that your friend had chosen $B$, but...
So you really have nothing to work with.  What you need to do is to repeat the process a number of times, assuming that your friend uses the same strategy each time.
Suppose we wish to test the hypothesis that your friend chooses the coin randomly with probability $\frac{1}{2}$.  Get your friend to toss the coin $10000$ times.  Now we define the $95\%$ confidence interval for the number of heads under our hypothesis to be a range of values for the number of heads such that if our hypothesis is correct, there is a $0.95$ chance that the number of heads lies in that range.  A quick calculation (details of which I am happy to provide) shows that this interval is [7415,7585].  So if your friend tosses $7503$ heads, you can be reasonable confident in your hypothesis.  However, if she tosses $8703$, then you are probably wrong.
Suppose you have good reason to believe that your friend is choosing the coins randomly with probability $\frac{1}{2}$, and you observe her toss $7503$ out of $1000$ heads.  Then you have no evidence to reject your hypothesis, so you accept it.  Now suppose your friend tosses again and gets a head.  Using Emile's method, you know the probability she chose coin $A$ is $\frac{1}{3}$.


Q: Qt - Keyboard Hook I'm using Qt 5.1.1 and I want make keyboard hooks, but Qtx do not accept my version, but I REALLY need this, for an autoclicker project. Any lib is good to me, but it need to be multiplatform, and what's the best way to "click" in Qt?


Q: Linking CSS file in php document nested in pages folder Web development newbie here. My site is becoming large enough that recently took a few steps to help manage it including:

*

*Using a separate header.php; footer.php; and navigation.php file with an includes tag.

*Filed additional pages under root/pages. Below is a snapshot of my current folders:

*

*root

*

*pages

*assets

*images

*js

*php

My issue now that I have nested additional pages (other than index.html) in the pages folder. When coding these files, the link/include files are causing issues, because of the relative/absolute file reference. Through some research I was able to use this php code which seems to work for the header, footer, and navigation menu:
<?php
set_include_path( implode( PATH_SEPARATOR, array(
$_SERVER['DOCUMENT_ROOT'],
get_include_path()
) ) );

include 'root/assets/header.php';

?>

The issue I have now is the css link no longer works either:
 <link rel="stylesheet" href="css/style-services.css">

I have tried doing this with no luck:
<?php
set_include_path( implode( PATH_SEPARATOR, array(
$_SERVER['DOCUMENT_ROOT'],
get_include_path()
) ) );

include 'root/css/style-services.css';

?>

How do I insure the referenced css also gets included when using a file structure and php include functions?

A: Don't include the CSS file, just echo it. Like:
<?php
//
// your other cods here
//
$style_services = file_get_contents ("root/css/style-services.css");
echo $style_services;
//
// your other cods here
//
?>


Q: WinCE 6.0 device not responding to ping i am working on WinCE 6.0(On ARM9) based (Headless)Device.
i established a ethernet(EMACB1) connection between My Desktop(XP-SP3) and WinCE Device.
the device shows network established but wince device not respong to ping.
Below are my TCP/IP Settings:
Desktop:
IP Address:       192.168.1.176
SubnetMask:       255.255.255.0
Default Gateway : 192.168.1.1

WinCE Device:
IP Address:       192.168.1.21
SubnetMask:       255.255.255.0
Default Gateway : 192.168.1.1

and i had set same primery and Alternative DNS for both.
My aim is to collect any data from the WinCE device.
As Activesync is not secured (No Authentication), I wish to use Ethernet(TCPIP) Connection.
What am I missing?
also i have some doubts:
1) is NIC mondatory for TCPIP? as i am not using any NICs.
2) is there any way to give authorization for Activesync.
3) which protocol is better to communicate locally between PC and WinCE Device(Headless) over ethernet.(Like VPN or TFTP or TCPIP etc)
Any suggestions would be appreciated
Thanks in Advance
rocky

A: Your Linksys router at 192.168.1.1 could be blocking ActiveSync.
Also, make sure the USB connections in settings are set to ActiveSync (enable advanced network functionality), and not Mass Storage.
Here are some notes copied over from PocketPC FAQ: (re-posted here in case the website goes away)
You must follow a few preliminary steps before loading new components for Ethernet.

*

*Establish a serial cable, infrared, or USB connection to the PC with which you are going to use ActiveSync. This is required to put the PC's computer name in your Pocket PC for use with Ethernet.

*Install the Ethernet drivers from the Ethernet vendor's installation disk. This will add a Network Control Panel as well as other relevant files. This installation requires less than 250 kilobytes of free memory for storage. You may also use the built-in NE-2000 drivers if you prefer to save the storage space.

*Reset the device to load the new components.

Next, configure the Network Control Panel for Ethernet on your Pocket PC.

*

*Click Start.

*Click Settings.

*Click Network.

Figure 1: Example of the TCP/IP Properties for Socket's Low Power Ethernet CF+ Card.

*

*Enter the IP address for the Pocket PC. I suggest the TCP/IP address 192.168.1.2 with subnet mask 255.255.255.0, and the WINS server address, which is the PC's IP address (192.168.1.1 using my recommended setting).

*Leave the other fields blank.

Figure 2: Properly configured Network Control Panel settings on the Pocket PC.
Connecting

*

*Plug both the Pocket PC and the PC into the hub. (If you are using a crossover cable, you can connect the Pocket PC and PC directly without a hub.)

*Turn on the PC and the Pocket PC and plug the Ethernet PC card into your Pocket PC.

*To start an ActiveSync session, select ActiveSync on your Pocket PC (choose Start, then Programs, and then Connections). Make sure the Method is set to Network Connection and the Connect To matches the PC computer's name. Then click Connect to start ActiveSync communications.

If you enable continuous ActiveSync synchronization, your Pocket PC will stay up-to-date, downloading new e-mail, tasks, contacts, and other files and data whenever it's connected to your desktop PC.
Gotcha
After plugging your Ethernet PC card into your Pocket PC, check for a link light on the PC's Ethernet card. If it is not lit, you are having a cable or hub problem.

A: How are the network cables and devices connected? Did you use a hub or a switch (do they support MDI/X?). I ask, as normally you cannot simply connect two devices with a standard cable. Best is to use a small switch that support Auto-MDI/X and switches correctly to use normal or reversed cabling.


Q: Is there a way to wrap Erlang code to a certain character limit Suppose I have a method
timer:apply_after(timeout, module, method, [Hosts])

Is there a tool that can help format this into something like:
    timer:apply_after(
                      timeout,
                      module,
                      method,
                      [Hosts]
    )

I don't think erl_tidy does this.

A: You could give prettypr a try. I've never used it myself, and might not give the exact output you specified, but it does format the source code according to the available horizontal space.

A: It should be possible to do this through erl_tidy, by passing an option {printer, fun (Tree, Opts) -> erl_prettypr:format(Tree, [{paper, P}, {ribbon, R} | Opts]) end}.
See http://erlang.org/doc/man/erl_prettypr.html#format-2 for details about the ribbon and paper options, and http://erlang.org/doc/man/erl_tidy.html#file-2 for info about the printer option.


Q: Adding new fields to custom objects in managed package I am a newbie to salesforce and still evaluating the platform for building products.
The product needs to be sold as a managed package.
The product many need to be customized by the clients to suit their exact purpose. E.g. Adding additional fields to a custom object to store data, and display it on the pages. Is that possible with managed packages?
Also, is there a way to control which objects can be extended by adding fields?

A: Yes, custom fields can be added to objects in a managed package. No, you can't restrict an administrator's ability to do so.


Q: Adding delete button to a div I am going to add a delete button to new items made. This delete button removes the item my-item from the page without affecting others.
Code I have tried:
<!DOCTYPE HTML>

    <meta charset = "UTF-8">
    <title>Simple Demo</title>

Click Me!

My Text!

    <button id="divButton">Click!</button>
    <button id="deleteButton">Delete!</button>

I'll be glad if you can help me. :)

A: As simple as that :
$(".my-item").remove();

(if I understood your question correctly)

A: I have found some things which could be improved.
First of all. An id is unique, so whenever you start to clone elements, the id is cloned as well.
I made a few adjustments and this is how it works:
HTML

Click Me!

My Text!

  <button class="divButton">Click!</button>
  <button class="deleteButton">Delete!</button>

CSS (still the same)
.my-item {
  width: 250px;
  heigth: 180px;
  margin: 10px;
  padding: 20px;
  background: green;
  border: 2px solid black;
}

.item-header {
  width: 150px;
  heigth: 120px;
  margin: 5px;
  padding: 10px;
  background: yellow;
  border: 1px solid black;
}

.item-body {
  width: 70px;
  heigth: 50px;
  margin: 3px;
  padding: 5px;
  background: purple;
  border: 1px solid black;
}

jQuery
function addEvents() {
  $(".divButton").unbind("click").click(function() {
    $(this).parent().clone().appendTo($("body"));
    addEvents();
  });

  $(".deleteButton").unbind("click").click(function() {
    $(this).parent().remove();
  });
}

addEvents();

The reason why I put both click events in a separate function, is when the element is cloned, the events are not cloned. Therefor, you will have to rebind them. This doesn't have to happen when you delete an element.
I hope this solves your question
FIDDLE

A: Guess you mean something like this:
$("#deleteButton").click(function(){
   $(this).nextAll(".my-item").remove();
});

This will remove all .my-item after the delete button and not your template.
Just a notice, when you're cloning your .my-item element, you'll get multiple "toggle" IDs in the DOM, which is not good.

A: I recommend to use single instead of the double quotation marks for js:
$('selector');

The following line is wrong:
$(".my-item").append(".my-item"+ "button class="deleteButton">Delete</button>");

Correct is:
$(".my-item").append("<button class=\"deleteButton\">Delete</button>");

or
$('.my-item').append('<button class="deleteButton">Delete</button>');

Your code will not produce new elements by clicking on button "Click!" and adding new delete buttons by clicking on the "Delete"-Button.
I guess what you want to archive is to duplicate an Item and add a delete button to the item itself.
Just clone your element without appending and save it to a var.
( var newElement = $.('selectpr').clone(); )
Then append the delete button to the newElement object and append the object to the target.
Another approach would be appending the clone to a container and then selecting it by looking for the last element in the container. Then bind a click event to the delete button.
Please check jQuery and CSS manual for correct selectors.

A: Ok, here's a different solution for you with cached element and no duplicate IDs.

And here is your HTML body part:

Click Me!

My Text!

    <button id="divButton">Click!</button>


Q: Macbook Pro Retina Version (late 2013) - no sound or webcam on Ubuntu I have a new Macbook Pro retina (late 2013 model) running Ubuntu 13.10. I can't get the sound to work. I have tried the solution here , but it's not changing anything. I also tried the following series of commands, but they don't change anything, either:
sudo apt-get remove --purge alsa-base
sudo apt-get remove --purge pulseaudio
sudo apt-get install alsa-base
sudo apt-get install pulseaudio
sudo alsa force-reload

When I start the computer and the login screen appears, I hear one sound - the sound Ubuntu usually makes when there's an error. After I log in, however, I can't hear anything again. The sound works perfectly on OSX - it's only Ubuntu that seems to be having this problem. Is there anything else I can try to get the sound to work?

A: Have you checked to see if pulseaudio is actually using the correct sound card? I had a similar problem and solved it by reading the Arch Linux wiki

sometimes it thinks HDMI is the default sound card; to solve this problem, install pavucontrol and set Analog Stereo as the fallback device.

Alternatively you can do this via alsamixer and select the correct sound card via F6 (once you are inside alsamixer). If you have selected the correct sound card, a series of volume bars should appear, use the arrow keys to select "master" and adjust the volume with up and down arrow keys.
Hope that helps :)


Q: SQL query to group multiple groups I'm parsing some IIS server logs (with LogParser) and I'm having a little trouble creating a query that will give me the aggregate count of each type of browser (user agent).
Here is my query so far:
SELECT COUNT(*) as totalHits, CS(User-Agent) as browser
FROM E:\Logs\ex111101.log
WHERE (CS(User-Agent) LIKE '%ipad%'
       OR CS(User-Agent) LIKE '%iphone%'
       OR CS(User-Agent) LIKE '%blackberry%'
       OR CS(User-Agent) LIKE '%windows cs%'
       OR CS(User-Agent) LIKE '%android%')
AND cs-uri-stem LIKE '%.asp%'
GROUP BY browser
ORDER BY totalHits DESC

This givse me a list of user-agents like I want, and gives me a hit count for each group of browser:
Total Hits | Browser
467        | AndroidA
45         | AndroidB
23         | BlackberryC
233        | BlackberryD

What I want is THIS:
Total Hits | Browser
512        | Android
256        | Blackberry

Where All Android entries are counted and totaled under a generic Android row.  In this case Total Hits for Android would be 467 + 45, Blackberry would be 233 = 33, etc.
From there I would want to provide a Percent column for each browser so I can represent the total hits as a percentage.
Any help is appreciated. Thanks!
*UPDATE
Followed the suggestion below but had to make a few tweaks in order for it to be executed correctly by LogParser.  For some reason Log Parser didn't like the LIKE keyword in the CASE statement.  The following worked fine though:
select
case strcnt(TO_LOWERCASE(cs(user-agent)),'android') WHEN 1 THEN 'Android' else
case strcnt(TO_LOWERCASE(cs(user-agent)),'ipad') WHEN 1 THEN 'iPad' else
case strcnt(TO_LOWERCASE(cs(user-agent)),'blackberry') WHEN 1 THEN 'Blackberry' else
case strcnt(TO_LOWERCASE(cs(user-agent)),'windows ce') WHEN 1 THEN 'Windows' else
case strcnt(TO_LOWERCASE(cs(user-agent)),'iphone') WHEN 1 THEN 'iPhone'
ELSE 'Non-Mobile' End End End End End as Browser,
count(*) as TotalHits
from MYLOG
group by Browser
order by TotalHits desc

A: try
select
      case when cs(User-Agent) like "%android%" then "Android"
           when cs(User-Agent) like "%black%" then "Blackberry"
           when cs(User-Agent) like "%windows%" then "Windows"
           when cs(User-Agent) like "%iphone%" then "iPhone"
           else "Other" end as Browser,
      count(*) as TotalHits
   from
      YourTable.logFile
   group by
      Browser
   order by
      TotalHits desc

The group by and order by respect the ordinal column position instead of re-copying the entire case/when and count(*)... Since there's only two columns, no problem...


Q: javax.el.ELException: Property 'askQuestiοn' not found on type trainforjava.domain.Questiοn My problem is the following. I've a list which i s well created, but I can't manage to display it on my web page.
Here is the pojo :
package trainforjava.domain;

public class Question {

    public int id;
    public String askedQuestion;
    public String proposal;

    public Question() {
        super();

    }

    public Question(int id, String askedQuestion, String proposal) {
        super();
        this.id = id;
        this.askedQuestion = askedQuestion;
        this.proposal = proposal;
    }

    public int getId() {
        return id;
    }

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

    public void setAskedQuestion(String askedQuestion) {
        this.askedQuestion = askedQuestion;
    }

    public String getAskedQuestion() {
        return askedQuestion;
    }

    public void setQuestion(String askedQuestion) {
        this.askedQuestion = askedQuestion;
    }

    public String getProposal() {
        return proposal;
    }

    public void setProposal(String proposal) {
        this.proposal = proposal;
    }

    @Override
    public String toString() {
        return "Question [id=" + id + ", askedQuestion=" + askedQuestion + "]";
    }

}

Here is the managed bean :
package trainforjava.domain;
import java.util.List;
import java.util.Map;
import javax.faces.bean.ManagedBean;
import trainforjava.util.QuestionCreator;

@ManagedBean
public class QuestionBean {

    public List<String> proposals;
    public List<Question> questions;
    public QuestionCreator creator = new QuestionCreator();

    public QuestionBean() {

        System.out.println("beforecreate");
        questions = creator.createQuestions();
        System.out.println(questions);
//      proposals = creator.createProposals(0);

    }

    public List<String> getProposals() {
        return proposals;
    }
    public void setProposals(List<String> proposals) {
        this.proposals = proposals;
    }
    public List<Question> getQuestions() {
        return questions;
    }
    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }

}

Here is the pojo creating from a properties file :
package trainforjava.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.stereotype.Component;

import trainforjava.domain.Question;

public class QuestionCreator {

List<Question> questions =new ArrayList<Question>();
    List<String> proposals = new ArrayList<String>();

    public List<Question> createQuestions() {
        final Properties properties = new Properties();
        InputStream input = null;
        System.out.println("createQuestions");

        try {

            input = getClass().getResourceAsStream("/questions.properties");
            // load a properties file
            properties.load(input);

            // get the property value and print it out
            for (int i = 0; i < properties.size(); i++) {

                Question question = new Question();
                StringBuilder sb = new StringBuilder();
                sb.append("question-").append(i);
                String askedQuestion = properties.getProperty(sb.toString());
                question.setAskedQuestion(askedQuestion);
                question.setId(i);
                questions.add(question);

            }

        } catch (final IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return questions;

    }

    public List<String> createProposals(int key) {
        final Properties properties = new Properties();
        InputStream input = null;
        System.out.println("createProposals");
        try {

            input = getClass().getResourceAsStream("/proposals.properties");
            // load a properties file
            properties.load(input);

            for(int i =0 ; i < proposals.size(); i++){

            int idQuestion = key;
            System.out.println("createProposals id" + idQuestion);
            StringBuilder sb = new StringBuilder();
            sb.append("proposal-").append(idQuestion).append("-").append(i);
            String proposal = properties.getProperty(sb.toString());
            proposals.add(proposal);
            System.out.println(proposals);

            }

        } catch (final IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return proposals;

    }

}

The console print me the list created, which name is "questions", but also print me a stacktrace :
beforecreate
createQuestions
[Question [id=0, askedQuestion=Quelle interface est implémentée par la Classe ArrayList ?], Question [id=1, askedQuestion=Quelle interface est implémentée par la Classe HashMap ?], Question [id=2, askedQuestion=Quelle interface est implémentée par la Classe Vector ?]]
août 23, 2016 2:29:19 AM com.sun.faces.application.view.FaceletViewHandlingStrategy handleRenderException
GRAVE: Error Rendering View[/index.xhtml]
javax.el.ELException: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
    at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88)
    at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
    at com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:161)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

août 23, 2016 2:29:19 AM com.sun.faces.context.ExceptionHandlerImpl log
1100: JSF1073 : javax.el.ELException intercepté durant le traitement de RENDER_RESPONSE 6 : UIComponent-ClientId=, Message=/index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
août 23, 2016 2:29:19 AM com.sun.faces.context.ExceptionHandlerImpl log
1100: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
javax.el.ELException: /index.xhtml: Property 'askQuestion' not found on type trainforjava.domain.Question
    at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88)
    at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
    at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
    at com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385)
    at com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:161)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:176)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:890)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:458)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:521)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

And then, the index.xhtml which is supposed to display this list :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
    <title>Test</title>
</h:head>

<h:body>

    Question :
    <h:form>

        <h:dataTable value="#{questionBean.questions}" var="question">
            <h:column>
            #{question.askQuestion}
            </h:column>
        </h:dataTable>

    </h:form>

</h:body>
</html>

Can someone help me please ?

A: The property name is actually askedQuestion, and not askQuestion.


Q: Space Complexity of generating all possible binary search trees I used the following recursion algorithm to calculate the possible cases of binary search trees given its number of nodes being n
public List<TreeNode> generateTrees(int n) {
    if(n == 0){
        List<TreeNode> empty = new ArrayList<TreeNode>();
        return empty;
    }
    return recurHelper(1, n);
}
public List<TreeNode> recurHelper(int start, int end){
    if(start > end){
        TreeNode nan = null;
        List<TreeNode> empty = new ArrayList<TreeNode>();
        empty.add(nan);
        return empty;
    }
    List<TreeNode> result = new ArrayList<TreeNode>();
    for(int i = start; i <= end; i++){
        List<TreeNode> left = recurHelper(start, i-1);
        List<TreeNode> right = recurHelper(i+1, end);
        for(TreeNode leftBranch:left){
            for(TreeNode rightBranch:right){
                TreeNode tree = new TreeNode(i);
                tree.left = leftBranch;
                tree.right = rightBranch;
                result.add(tree);
            }
        }
    }
    return result;
}

I wonder what is the space complexity for the recursion, should it be O(h), where h is the height of the tree?
I do not think so because at each level we are storing a result consisting of O(lG_l) elements, where l stands for the level and G_l stands for the number of possible trees with l nodes.
Then it seems to me that the space complexity of the recursion should be nG_n + ... + 1G_1.


Q: zypper dependency resolution I am facing problem while installing an "Company-hardening-1.0-1.noarch.rpm" RPM through zypper. There are 2 systems involved. Both are SUSE-Linux-Enterprise-Server-11-SP3 VMs.
System 1: (working)
In this system I am able to install the rpm, in this case, zypper is automatically resolving the dependency.
susevm1:~ # zypper install Company-hardening-1.0-1.noarch.rpm
Loading repository data...
Reading installed packages...
Resolving package dependencies...

The following NEW packages are going to be installed:
  Company-hardening openscap-engine-sce

The following packages are not supported by their vendor:
  Company-hardening openscap-engine-sce

2 new packages to install.
Overall download size: 195.0 KiB. After the operation, additional 1.0 MiB will be used.
Continue? [y/n/?] (y): n

System 2: (Not working)
In this system RPM is not getting installed, as zypper is not able to resolve the dependency.
linux-g33k:~/Desktop/RPMS # zypper install Company-hardening-1.0-1.noarch.rpm
Loading repository data...
Reading installed packages...
Resolving package dependencies...

Problem: nothing provides openscap-engine-sce >= 1.2.5-2 needed by Company-hardening-1.0-1.noarch
 Solution 1: do not install Company-hardening-1.0-1.noarch
 Solution 2: break Company-hardening-1.0-1.noarch by ignoring some of its dependencies

Choose from above solutions by number or cancel [1/2/c] (c): c

Note that, both system are having same version of zypper. I know, this might a simple and silly question. :) This might be because  of some repository diff.
Thanks,
Hemant

A: It means you don't have the same repositories activated on both machines. Comparing the output of
zypper lr -u

on both machines should show you which repository to add or enable.


Q: Black bar when increasing window size in WPF I have a small program with two checkboxes.
The window height is 120. When one of them is checked the windows height should increase to 180. If both are checked it should increse to 220. If you uncheck them they should decrease to 180 for 1 checkbox and 120 if none are checked.
I make it smooth, that means i calculate the windowHeightOld and windowHeightNew difference, divide it through 30 and increase it in 30 small steps so it seems smooth.
The problem is that the decrease to a smaller window size looks great, the increase gives on the area that increases a black bar for a few milliseconds, then dissapears again. Sadly i could not make a screenshot because of how short its there.
I dont know where that comes from and how that could be fixed.
Here a code snipped from the increase/decrase of the window height:
private void CheckBoxSetup_Click(object sender, RoutedEventArgs e)
    {

if (CheckBoxSetup.IsChecked == false && CheckBoxUpdate.IsChecked == false)
{
    MainWindow1.MinHeight = 50;

    OldWindowHeight = MainWindow1.Height;
    int NewWindowHeigth = 180;
    WindowDiff = NewWindowHeigth - OldWindowHeight;
    WindowDiff = WindowDiff / 30;
    for (int a = 0; a < 30; a++)
    {
        OldWindowHeight = OldWindowHeight + WindowDiff;
        MainWindow1.Height = OldWindowHeight;
        MainWindow1.MinHeight = OldWindowHeight;

    }
}
if (CheckBoxSetup.IsChecked == true || CheckBoxUpdate.IsChecked == true)
{
    MainWindow1.MinHeight = 50;

    OldWindowHeight = MainWindow1.Height;
    int NewWindowHeigth = 220;
    WindowDiff = NewWindowHeigth - OldWindowHeight;
    WindowDiff = WindowDiff / 30;
    for (int a = 0; a < 30; a++)
    {
        OldWindowHeight = OldWindowHeight + WindowDiff;
        MainWindow1.Height = OldWindowHeight;
        MainWindow1.MinHeight = OldWindowHeight;

    }
    //MainWindow1.MinHeight = 220;

}
if (CheckBoxSetup.IsChecked == true && CheckBoxUpdate.IsChecked == true)
{
    MainWindow1.MinHeight = 50;

    OldWindowHeight = MainWindow1.Height;
    int NewWindowHeigth = 260;
    WindowDiff = NewWindowHeigth - OldWindowHeight;
    WindowDiff = WindowDiff / 30;
    for (int a = 0; a < 30; a++)
    {
        OldWindowHeight = OldWindowHeight + WindowDiff;
        MainWindow1.Height = OldWindowHeight;
        MainWindow1.MinHeight = OldWindowHeight;

    }
    //MainWindow1.MinHeight = 260;

}

if (CheckBoxSetup.IsChecked == true)
{
    LabelDestinationSetup.Visibility = Visibility.Visible;
    TextBoxDestinationpathSetup.Visibility = Visibility.Visible;
    CheckCountSetup++;
}
else
{
    LabelDestinationSetup.Visibility = Visibility.Hidden;
    TextBoxDestinationpathSetup.Visibility = Visibility.Hidden;
    CheckCountSetup--;
}
if (CheckCountSetup == 1)
{
    LabelDestinationSetup.Margin = new Thickness(24, thickTop1, 0, 0);
    TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop1, 0, 0);

    LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop2, 0, 0);
    TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop2, 0, 0);
}
if (CheckCountSetup == 0 && CheckCountUpdate == 1)
{
    LabelDestinationSetup.Margin = new Thickness(24, thickTop2, 0, 0);
    TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop2, 0, 0);

    LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop1, 0, 0);
    TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop1, 0, 0);
}
if (CheckCountSetup == 0)
{
    LabelDestinationSetup.Margin = new Thickness(24, thickTop2, 0, 0);
    TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop2, 0, 0);

    LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop1, 0, 0);
    TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop1, 0, 0);
}
}

private void CheckBoxUpdate_Click(object sender, RoutedEventArgs e)
{
if(CheckBoxUpdate.IsChecked == true && CheckBoxFTP.IsChecked == false){
    CheckBox64Bit.IsEnabled = true;
}else if(CheckBoxUpdate.IsChecked == false){
    CheckBox64Bit.IsEnabled = false;
    CheckBox64Bit.IsChecked = false;
}
if (CheckBoxSetup.IsChecked == false && CheckBoxUpdate.IsChecked == false)
{
    MainWindow1.MinHeight = 50;

    OldWindowHeight = MainWindow1.Height;
    int NewWindowHeigth = 180;
    WindowDiff = NewWindowHeigth - OldWindowHeight;
    WindowDiff = WindowDiff / 30;
    for (int a = 0; a < 30; a++)
    {
        OldWindowHeight = OldWindowHeight + WindowDiff;
        MainWindow1.Height = OldWindowHeight;
        MainWindow1.MinHeight = OldWindowHeight;

    }
    //MainWindow1.MinHeight = 180;

}
if (CheckBoxSetup.IsChecked == true || CheckBoxUpdate.IsChecked == true)
{
    MainWindow1.MinHeight = 50;

    OldWindowHeight = MainWindow1.Height;
    int NewWindowHeigth = 220;
    WindowDiff = NewWindowHeigth - OldWindowHeight;
    WindowDiff = WindowDiff / 30;
    for (int a = 0; a < 30; a++)
    {
        OldWindowHeight = OldWindowHeight + WindowDiff;
        MainWindow1.Height = OldWindowHeight;
        MainWindow1.MinHeight = OldWindowHeight;

    }
    //MainWindow1.MinHeight = 220;

}
if (CheckBoxSetup.IsChecked == true && CheckBoxUpdate.IsChecked == true)
{
    MainWindow1.MinHeight = 50;

    OldWindowHeight = MainWindow1.Height;
    int NewWindowHeigth = 260;
    WindowDiff = NewWindowHeigth - OldWindowHeight;
    WindowDiff = WindowDiff / 30;
    for (int a = 0; a < 30; a++)
    {
        OldWindowHeight = OldWindowHeight + WindowDiff;
        MainWindow1.Height = OldWindowHeight;
        MainWindow1.MinHeight = OldWindowHeight;

    }
    //MainWindow1.MinHeight = 260;

}
if (CheckBoxUpdate.IsChecked == true)
{
    LabelDestinationUpdatepackage.Visibility = Visibility.Visible;
    TextBoxDestinationpathUpdatePackage.Visibility = Visibility.Visible;
    CheckCountUpdate++;
}
else
{
    LabelDestinationUpdatepackage.Visibility = Visibility.Hidden;
    TextBoxDestinationpathUpdatePackage.Visibility = Visibility.Hidden;
    CheckCountUpdate--;
}
if (CheckCountUpdate == 1)
{
    LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop1, 0, 0);
    TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop1, 0, 0);

    LabelDestinationSetup.Margin = new Thickness(24, thickTop2, 0, 0);
    TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop2, 0, 0);
}
if (CheckCountSetup == 1 && CheckCountUpdate == 0)
{
    LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop2, 0, 0);
    TextBoxDestinationpathUpdatePackage.Margin = new Thickness(160, thickTop2, 0, 0);

    LabelDestinationSetup.Margin = new Thickness(24, thickTop1, 0, 0);
    TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop1, 0, 0);
}
if (CheckCountUpdate == 0)
{
    LabelDestinationUpdatepackage.Margin = new Thickness(24, thickTop2, 0, 0);
    TextBoxDestinationpathUpdatePackage.Margin = new Thickness(181, thickTop2, 0, 0);

    LabelDestinationSetup.Margin = new Thickness(24, thickTop1, 0, 0);
    TextBoxDestinationpathSetup.Margin = new Thickness(160, thickTop1, 0, 0);
}
}

Sorry for the long line of code but i thought it to be nessecary to have insight.
Basically it checks if these two are checked or not in different combinations. And increases or decreases the window height according to it. And because i also have textboxes there (thats the reason i do it. When checkboxes are checked i want to show the according textbox) which i set visible or invisible according to the checkboxes.
So basically its two methods (click Checkbox1 and click Checkbox2) and both are build the same. When one is clicked it checks for the combination, sets the window height accordingly and shows or sets the according textboxes invisible.
0 Checkboxes checked:

1 Checkbox checked:

2 Checkboxes checked:

I hope i explained it good enough.

A: XAML:
<Window x:Class=.........
        DataContext="{StaticResource MainViewModel}"
        Name="MyWindow"
        >

    <Window.Triggers >
        <EventTrigger  RoutedEvent="CheckBox.Unchecked" >
            <BeginStoryboard  >
                <Storyboard   >
                    <DoubleAnimation  Storyboard.TargetName="MyWindow" Storyboard.TargetProperty = "(Window.Height)" Duration="0:0:0.5" To="{Binding WindowHeight}"  RepeatBehavior="1x" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
        <EventTrigger  RoutedEvent="CheckBox.Checked"  >
            <BeginStoryboard  >
                <Storyboard   >
                    <DoubleAnimation  Storyboard.TargetName="MyWindow" Storyboard.TargetProperty = "(Window.Height)" Duration="0:0:0.5" To="{Binding WindowHeight}"  RepeatBehavior="1x" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Window.Triggers>

    <Grid Row="0" >
        ............
        <CheckBox   Grid.Column="4"
                    Content="UpadatePack"
                    IsChecked="{Binding PackegeCheck, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                    Name="CheckUpadatePack" />
        <CheckBox   Grid.Column="5"
                    Content="Setup"
                    IsChecked="{Binding SetupCheck, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}"
                    Name="CheckSetup"  />
        ......
    </Grid>
    <Grid Row="5" Visibility="{Binding SetupDestinationVisibility, Converter={StaticResource BoolToVisibilityConverter}}" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="120"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Content="Setup Destination" Margin="5" Grid.Column="0"/>
        <TextBox  Margin="5" Grid.Column="1"/>
    </Grid>
    <Grid Row="6" Visibility="{Binding PackageDestinationVisibility, Converter={StaticResource BoolToVisibilityConverter}}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="120"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Label Content="Package Destination" Margin="5" Grid.Column="0"/>
        <TextBox  Margin="5" Grid.Column="1"/>
    </Grid>

</Window>

MainViewModel:
public class MainViewModel : ViewModelBase
{

    private bool _sixtyFourBitCheck;
    private bool _packegeCheck;
    private bool _setupCheck;
    private bool _ftpUploadCheck;
    public int _windowHeight;
    public int _origSize = 200;

    public bool SixtyFourBitCheck
    {
        get => _sixtyFourBitCheck;
        set
        {
            if (value == _sixtyFourBitCheck) return;
            _sixtyFourBitCheck = value;
            OnPropertyChanged();
        }
    }

    public bool PackegeCheck
    {
        get => _packegeCheck;
        set
        {
            if (value == _packegeCheck) return;
            _packegeCheck = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(PackageDestinationVisibility));
            ChangeWindowsHeght();
        }
    }

    public bool SetupCheck
    {
        get => _setupCheck;
        set
        {
            if (value == _setupCheck) return;
            _setupCheck = value;
            OnPropertyChanged();
            OnPropertyChanged(nameof(SetupDestinationVisibility));
            ChangeWindowsHeght();
        }
    }

    public bool FtpUploadCheck
    {
        get => _ftpUploadCheck;
        set
        {
            if (value == _ftpUploadCheck) return;
            _ftpUploadCheck = value;
            OnPropertyChanged();
        }
    }

    public bool SetupDestinationVisibility => SetupCheck;

    public bool PackageDestinationVisibility => PackegeCheck;

    public int WindowHeight
    {
        get => _windowHeight;
        set
        {
            if (value == _windowHeight) return;
            _windowHeight = value;
            OnPropertyChanged();
        }
    }

    public MainViewModel()
    {
        WindowHeight = _origSize;
    }

    private void ChangeWindowsHeght()
    {
        WindowHeight = _origSize;
        if (PackageDestinationVisibility)
            WindowHeight += 35;
        if (SetupDestinationVisibility)
            WindowHeight += 35;
        OnPropertyChanged(nameof(WindowHeight));
    }
}


Q: Split from list in python In my list I have few items, i.e.,
List=['a/c/d/eww/d/df/rr/e.jpg', 'ss/dds/ert/eww/ees/err/err.jpg','fds/aaa/eww/err/dd.jpg']

I want to keep only from 'eww' till last '/'
Modified_list=['eww/d/df/rr/', 'eww/ees/err/err.jpg','eww/err/']

A: Use find(sub_str) function.
new_list = [item[item.find("eww"):] for item in List]
print(new_list)

Output:
['eww/d/df/rr/e.jpg', 'eww/ees/err/err.jpg', 'eww/err/dd.jpg']

A: new_list2=[item[item.find('eww'):item.rfind('/')+1] for item in List]
print(new_list2)

output=   ['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/']

A: Here are the steps I would do:

*

*split the string after eww
assuming that each string contains 'eww' you can split the string like this: split = 'eww'+string.split('eww')[1]

*Now, you have to loop over each character in the remaining string and save the index of the last /

*Remove everything after the last / with the index from step 3: split = split[:splitIndex]

*Now, you just have to put everything in a loop that iterates over the list and execute each of the steps above on each element of the list and save the modified string to the ModiefiedList list.

A: You can use a regex in a list comprehension.
A perfect use case for the new walrus operator (python ≥3.8):
List=['a/c/d/eww/d/df/rr/e.jpg',
      'ss/dds/ert/eww/ees/err/err.jpg',
      'fds/aaa/eww/err/dd.jpg']

import re
out = [m.group() if (m:=re.search('eww/(.*)/', s)) else s
       for s in List]

output:
['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/']

NB. this keeps the original string in case of no match, if you rather want to drop it:
out = [m.group() for s in List if (m:=re.search('eww/(.*)/', s))]


Q: One Click at .click(function() Not Working in Ajax I want to open another page on my site with this ajax:

OPEN

But these pages can only be loaded with a double-click. What is wrong in my code, can you help me? thanks ..

A: Change your code to this and it will work:

OPEN


Q: Neo4j 1 to 1 Relationship I have two nodes, "client" and "builder". I want to find only the relationships where the client only has 1 builder, and that builder only has that one client so a 1-1 relationship. So far my query is
MERGE(b:Person{name:csv.name)
MERGE(c:Person{name:csv.name})
WITH collect(distinct b) as builder, collect(distinct c) as client
UNWIND builder as builders
UNWIND client as clients
WITH builders, clients
WHERE builders = 1 and clients = 1
MATCH (builders:Person)-[bu:builder_for]->(clients:Person)
WITH builders,clients, count(distinct bu) as builds
WHERE builds=1

RETURN distinct builders, clients

This only returns though a 1 to many relationship and is still showing duplicates in my client list.
The highlighted are the ones I would want to return
UPDATE cybersam implementation worked, thank you so much!

A: Assuming you want to get all the builder/client pairs that only have a single builder_for relationship between them, this query uses the aggregating function COUNT to do that:
MATCH (builder:Person)-[rel:builder_for]->(client:Person)
WITH builder, client, COUNT(rel) AS rel_count
WHERE rel_count = 1
RETURN builder, client;

[UPDATE]
If, instead, you want builder/client pairs in which the builder has only that one client, and vice versa, then this query should work:
MATCH (builder:Person)
WHERE SIZE((builder)-[:builder_for]->()) = 1
MATCH (builder)-[:builder_for]->(client:Person)
WHERE SIZE(()-[:builder_for]->(client)) = 1
RETURN builder, client;

This query uses efficient relationship degree-ness checks (in the WHERE clauses) to ensure that the builder and client nodes only have, respectively, a single outgoing or incoming builder_for relationship.


Q: Open & write to a file-like object but avoid AttributeError about missing open() I want to have function that can write content into a file-like object. It accepts pathlib.Path objects or io.StringIO. The first one need to be open()'ed first, the second one not.
Because of that it seems to me I have to explicte type check the object to know if I have to call open() on it or not.
Is there an elegant and pythonic way to work around this?
Here is an MWE.
#!/usr/bin/env python3
import io
import pathlib
import typing

def foobar(file_like_obj: typing.Union[pathlib.Path, typing.IO]):
    with file_like_obj.open('w') as handle:
        handle.write('foobar')

if __name__ == '__main__':
    p = pathlib.Path.home() / 'my.txt'
    foobar(p)

    sio = io.StringIO()
    foobar(sio)

The second call of foobar() here cause this error:
AttributeError: '_io.StringIO' object has no attribute 'open'

One pythonic-like way I know to prevent explicit type checking is to use try-except blocks. But this would break my with block.

A: The comment from @tripleee inspired me to this approach which I wouldn't call a solution because it doesn't fit to all needs in my opening question. But it seems as a good compromise to me.
I combined recursive calls and a try..except block. The recursion is because I didn't want to separate the functionality into a second function.
#!/usr/bin/env python3
import io
import pathlib
import typing

def foobar(file_like_obj: typing.Union[pathlib.Path, typing.IO]):
    print('foobar(): called')

    try:

        with file_like_obj.open('w') as handle:
            print('re-call myself')

            foobar(handle)

    except AttributeError:
        file_like_obj.write('foobar')

if __name__ == '__main__':
    p = pathlib.Path.home() / 'my.txt'
    foobar(p)

    sio = io.StringIO()
    foobar(sio)

The output
foobar(): called
re-call myself
foobar(): called
foobar(): called


Q: Can i create new Web Application with Copy of existing Web Application Content database in Same SharePoint Farm? 1.I have one web application 'WebAppA.company1.com' in production SP Farm with a content database Wss_Content_DB1 and i taken backup and restored in staging as Wss_Content_DB2 and mounted to webapplication in staging.
2.In staging i modified the design,created new page layouts,master pages and created some sub sites
3.In Staging i taken backup of Content database 'Wss_Content_DB2' and restored in same Production SharePoint Farm SQL Instance as new content database Wss_Content_DB3_FromStaging'

*and now i want to create a new  Web Application with different host name 'WebApp2.Company1.com' in Same SP Production farm with 'Wss_Content_DB3_FromStaging' Content database

Can i do this step 4 successfully because WebApp2.company1.com content database is copy of Webapp1.company1.com database?

A: We can attach an existing content database to a web application.
To attach an existing content database to a web application:
1.Restore a backup copy of the database in SQL.
2.Use the following PowerShell to attach an existing content database to a web application:
Mount-SPContentDatabase "<ContentDb>" -DatabaseServer "<DbServer>" -WebApplication http://SiteName

Refer to the article about attach or detach content databases in SharePoint 2013:
https://technet.microsoft.com/en-us/library/ff628582.aspx


Q: std::ranges::find_if - no type in std::common_reference I'm using the SG14 flat_map as a container.
As per a standard map, it takes Key and Value template parameters.
Unlike a standard map, however, it doesn't store std::pair<Key, Value> in a binary search tree, but rather stores the keys and values in two separate containers (additional template arguments which default to std::vector)
template<
    class Key,
    class Mapped,
    class Compare = std::less<Key>,
    class KeyContainer = std::vector<Key>,
    class MappedContainer = std::vector<Mapped>
>
class flat_map

It then defines a number of types as follows:
using key_type = Key;
using mapped_type = Mapped;
using value_type = std::pair<const Key, Mapped>;
using key_compare = Compare;
using const_key_reference = typename KeyContainer::const_reference;
using mapped_reference = typename MappedContainer::reference;
using const_mapped_reference = typename MappedContainer::const_reference;
using reference = std::pair<const_key_reference, mapped_reference>;
using const_reference = std::pair<const_key_reference, const_mapped_reference>;

If I attempt to use std::ranges::find_if on the flat_map, I get an error:
error: no type named ‘type’ in
    ‘struct std::common_reference<std::pair<const Key&, const Value&>&&,
                                  std::pair<const Key, Value>&>’
  121 | auto it = std::ranges::find_if(map, [](auto& kv) { return kv.second.name == "foo"; });
      |           ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

If I use a non-range find_if, everything "just works"
auto it = std::find_if(map.begin(), map.end(), [](auto& kv) { return kv.second.name == "foo"; });

Why does the std::ranges::find_if not work?
Example on godbolt: https://godbolt.org/z/r93f7qozr
Edit:
@Brian provided an exemplar which successfully compiles - albeit with slight differences to mine - notably my map is const, and I take the lambda argument as a const ref...
This begs the questions:

*

*Why does the combination of const range and const auto& lambda argument fail to compile, while pasing a mutable range works and taking the lambda argument by value works?

*I believe it would be considered somewhat of an anti-pattern to take the non-range std::find_if algorithm's lambda arguments by value (auto as opposed to const auto&) as this will cause every element to be copied - and therefore using const auto& should be preferred... principle of least surprose means I assumed the same would be the case with std::ranges - is this not the case?

A:
Why does the combination of const range and const auto& lambda
argument fail to compile, while pasing a mutable range works and
taking the lambda argument by value works?

First, the operator*() of the iterator of flat_map is defined as follows:
reference operator*() const {
  return reference{*kit_, *vit_};
}

And the type of reference is pair, this means that operator*() will return a prvalue of pair, so the parameter type of the lambda cannot be auto&, that is, an lvalue reference, because it cannot bind rvalue.
Second, const flat_map does not model the input_range concept, that is, its iterator does not model input_iterator which requires indirectly_readable which requires common_reference_with<iter_reference_t<In>&&, iter_value_t<In>&>, the former is pair<const int&, const int&>&&, and the latter is pair<const int, int>&, there is no common_reference for the two.
The workaround is to just define common_reference for them, just like P2321 does (which also means that your code is well-formed in C++23):
template<class T1, class T2, class U1, class U2,
         template<class> class TQual, template<class> class UQual>
  requires requires { typename pair<common_reference_t<TQual<T1>, UQual<U1>>,
                                    common_reference_t<TQual<T2>, UQual<U2>>>; }
struct basic_common_reference<pair<T1, T2>, pair<U1, U2>, TQual, UQual> {
  using type = pair<common_reference_t<TQual<T1>, UQual<U1>>,
                    common_reference_t<TQual<T2>, UQual<U2>>>;
};

For details on common_reference, you can refer to this question.


Q: Installing ASP.net DNX with Powershell 2.0 I am trying to get an install of ASP.Net DNX on Windows. I followed the instructions at: https://github.com/aspnet/home#cmd
The problem is. when I run this, I get an error stating:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\parsonsjm0818\Desktop>@powershell -NoProfile -ExecutionPolicy unrestric
ted -Command "&{$Branch='dev';iex ((new-object net.webclient).DownloadString('ht
tps://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}"
Using temporary directory: C:\Users\PARSON~1\AppData\Local\Temp\dnvminstall
Downloading DNVM.ps1 to
Downloading DNVM.cmd to
Installing DNVM
The script 'dnvm.ps1' cannot be run because it contained a "#requires" statemen
t at line 2 for Windows PowerShell version 3.0. The version required by the scr
ipt does not match the currently running version of Windows PowerShell version
2.0.
At line:1 char:191
+ [System.Threading.Thread]::CurrentThread.CurrentCulture = ''; [System.Threadi
ng.Thread]::CurrentThread.CurrentUICulture = '';$CmdPathFile='C:\Users\parsonsj
m0818\.dnx\temp-set-envvars.cmd';& <<<<  'C:\Users\PARSON~1\AppData\Local\Temp\
dnvminstall\dnvm.ps1' setup
    + CategoryInfo          : ResourceUnavailable: (dnvm.ps1:String) [], Scrip
   tRequiresException
    + FullyQualifiedErrorId : ScriptRequiresUnmatchedPSVersion

C:\Users\parsonsjm0818\Desktop>

Can I install the DNX with only Powershell 2.0 or do I have to upgrade to 3.0?

A: The script 'dnvm.ps1' cannot be run because it contained a "#requires" statemen
t at line 2 for Windows PowerShell version 3.0.
If you want to be sure that the script will work, you'll have to use Powershell v3.0.  It is certainly possible to modify the script to remove the requirement, but it as probably put there for a good reason.  It would just be a roll of the dice if it would actually work if the requirement was removed.


Q: How to rearrange data from a set of columns to another set of columns in excel? Hey so I'm new to VBA and I'm trying to move data from a column to another column in a different format in the same worksheet.
So the original data looks like this:
  Type   Fx Fy Fz
1  DL     1  2  3
1  LL     4  5  6
1  C1     7  8  9
1  C2    10  11 12
2  DL    5   6  7
2  LL    6   8  4
2  C1    3   3  4
2  C2    1   2  3

I want to arrange this to another set of columns with a format similar to this:
       DL            LL             C1            C2
   Fx  Fy  Fz    Fx  Fy  Fz     Fz  Fy  Fz    Fx  Fy  Fz
1   1  2    3     4   5   6      7   8   9    10  11  12
2   5   6   7     6   8   4      3   3   4    1    2   3

I tried doing record macro for this and this is what the code looked like:
   Sub Macro2()
       Selection.Copy
        ActiveCell.Offset(-2, 7).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(2, -5).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-2, 6).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(3, -6).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-3, 9).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(4, -9).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-4, 12).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(5, -12).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-5, 15).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(6, -17).Range("A1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-5, 7).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(5, -5).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-5, 6).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(6, -6).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-6, 9).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(7, -9).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-7, 12).Range("A1").Select
        ActiveSheet.Paste
        ActiveCell.Offset(8, -12).Range("A1:C1").Select
        Application.CutCopyMode = False
        Selection.Copy
        ActiveCell.Offset(-8, 15).Range("A1").Select
        ActiveSheet.Paste
    End Sub

A: Sub moveit()

    Dim src As Worksheet, dest As Worksheet
    Dim c As Range, f As Range

    Set src = ThisWorkbook.Sheets("Sheet1")
    Set dest = ThisWorkbook.Sheets("Sheet2")

    dest.UsedRange.ClearContents 'start with empty sheet

    Set c = src.Range("a2")
    Do While Len(c.Value) > 0

        Set f = dest.Rows(1).Find(c.Value, LookIn:=xlValues, lookat:=xlWhole)
        If f Is Nothing Then
            Set f = dest.Cells(1, Columns.Count).End(xlToLeft)
            If Len(f.Value) > 0 Then Set f = f.Offset(0, 3)
            f.Value = c.Value
            src.Range("B1:D1").Copy f.Offset(1, 0)
        End If
        c.Offset(0, 1).Resize(1, 3).Copy dest.Cells(Rows.Count, f.Column).End(xlUp).Offset(1, 0)

        Set c = c.Offset(1, 0)

    Loop

End Sub


Q: Python remove all console output I want to erase all console output that was printed before each loop iteration.
Currently I have a code like this:
import sys
from time import sleep

def delete_last_printed_lines(n=1):
    CURSOR_UP_ONE = '\x1b[1A'
    ERASE_LINE = '\x1b[2K'

    for _ in range(n):
        sys.stdout.write(CURSOR_UP_ONE)
        sys.stdout.write(ERASE_LINE)

for x in range(1, 3):
    delete_last_printed_lines(3)

    print('')
    print('Some information #{0}'.format(x))
    print('And a lot of different prints')
    sleep(1)

But it is working not very well, it "move" console window and remove run command.
Is there is any way to fix it? If it will be Python 3+ only solution it is ok.

A: You can use subprocess :
# -*- coding: utf-8 -*-
import sys
import subprocess
from time import sleep

for x in range(1, 3):
    subprocess.call('clear')
    print('')
    print('Some information #{0}'.format(x))
    print('And a lot of different prints')
    sleep(1)

A: An Unbutu solution would be to call reset:
for x in range(1, 3):
    subprocess.call('reset')
    print('Some information #{0}'.format(x))
    print('And a lot of different prints')
    sleep(1)


Q: Copy files from pwd to another directory using Python I'd like to copy all files in my present working directory to another location.
I have tried variations of the below:
import shutil
shutil.copyfile('/*','/my/other/directory/location')

This gives the error: OSError: [Errno 2] No such file or directory: '/*'
I am thinking about using os.system and the cp command.
Has anyone got any better ideas?

A: I would use shutil. Is there a problem with that ?
Personally I tend to use:
shutil.copytree(src, dst, symlinks=False, ignore=None)

as it takes subdirs
update------
To get the current working directory use
os.getcwd()


Q: SFML with Code::Blocks - "undefined reference to sf::Texture::getSize()" I used this tutorial http://www.sfml-dev.org/tutorials/2.0/start-cb.php to add SFML to my Code::Blocks project, but I got errors like that:
undefined reference to sf::Texture::getSize() const
undefined reference to sf::Sprite::Sprite()
undefined reference to sf::Sprite::setTexture(sf::Texture const&, bool)

Here are the screenshots from my settings:
The liner settings:

The search directories for compiler:

The search directories for linker:

The compiler settings:

||=== Build: Release in Space (compiler: GNU GCC Compiler) ===|
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Sprite::Sprite()'
 undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)'
 undefined reference to `sf::Transformable::setPosition(float, float)'
 undefined reference to `sf::Sprite::Sprite()'
 undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)'
 undefined reference to `sf::Transformable::setPosition(float, float)'
 undefined reference to `sf::RenderStates::Default'
 undefined reference to `sf::RenderTarget::draw(sf::Drawable const&, sf::RenderStates const&)'
 undefined reference to `vtable for sf::Sprite'
 undefined reference to `vtable for sf::Sprite'
 undefined reference to `sf::Transformable::~Transformable()'
 (.text$_ZN2sf6SpriteD1Ev[__ZN2sf6SpriteD1Ev]+0x3e)
undefined reference to `vtable for sf::Sprite'
 (.text$_ZN2sf6SpriteD1Ev[__ZN2sf6SpriteD1Ev]+0x45)
undefined reference to `vtable for sf::Sprite'
 (.text$_ZN2sf6SpriteD1Ev[__ZN2sf6SpriteD1Ev]+0x57)
 undefined reference to `sf::Transformable::~Transformable()'|
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined references to `sf::Texture::getSize() const' follow
 undefined reference to `sf::Clock::Clock()'
 undefined reference to `sf::seconds(float)'
 undefined reference to `sf::Time::Time()'
 undefined reference to `sf::operator<(sf::Time, sf::Time)'
 undefined reference to `sf::Time::Zero'
 undefined reference to `sf::Time::Zero'
 undefined reference to `sf::Clock::restart()'
 undefined reference to `sf::operator+=(sf::Time&, sf::Time)'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Texture::getSize() const'
 undefined reference to `sf::Sprite::Sprite()'
 undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)'
 undefined reference to `sf::Transformable::setPosition(float, float)'
 undefined reference to `sf::Sprite::Sprite()'
 undefined reference to `sf::Sprite::setTexture(sf::Texture const&, bool)'
 undefined reference to `sf::Transformable::setPosition(float, float)'
 undefined reference to `sf::RenderStates::Default'
 undefined reference to `sf::RenderTarget::draw(sf::Drawable const&, sf::RenderStates  const&)'|
 undefined reference to `vtable for sf::Sprite'
 undefined reference to `vtable for sf::Sprite'
 undefined reference to `sf::Transformable::~Transformable()'
 undefined reference to `sf::Sprite::getGlobalBounds() const'
 undefined reference to `sf::Sprite::getTextureRect() const'
 undefined reference to `sf::Transformable::getScale() const'
 undefined reference to `sf::Transformable::getTransform() const'
 undefined reference to `sf::Sprite::getTextureRect() const'
||More errors follow but not being shown.|
||Edit the max errors limit in compiler options...|
||=== Build failed: 50 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|

A: I think I figured out your issue.  I suspect you need to download SFML GCC 4.7 TDM (SJLJ) - 32-bit from here http://www.sfml-dev.org/download/sfml/2.1/ - you were probably using the wrong version of the libs.


Q: Dynamic setTimeout causes "maximum call stack exceeded" error I am trying to create setTimeout that will call function and then function will call setTimeout again but with different interval value.
The issue is that it seems to fall into infinite loop.
These are starting variables:
var interval = 1500;
var elapsed = 0;
var totalTimer = 40000;
var startTime = null;

This is the function:
function playLights(){
        startTime = Date.now();
        interval = (totalTimer-elapsed) * 0.026;
        lights[0].color(0, 91, 68, 3500, 0);
        lights[1].color(0, 91, 68, 3500, 0);
        setTimeout(function(){
            lights[0].color(0, 100, 100, 3500, 0);
            lights[1].color(0, 100, 100, 3500, 0);
        }, 300);
        elapsed = Date.now() - startTime;
        if((Date.now() - startTime) < 37000){
            setTimeout(playLights(), interval.toFixed());
        }
        console.log("Interval: "+interval+" ,Elapsed: "+elapsed);
    }

When action happens I call playLights();
What's supposed to happen:
1) Bomb gets planted in game,
2) It must call playLights(),
3) It must get current time and save it,
4) It must determine interval, so since it's first call - it must be 1040 ms.
5) It must flicker colors. (Not important right now)
6) Then it must calculate how much time elapsed based on currentDate - storedDate.
7) Then it must check if elapsed time is more than 37000 ms (37 seconds)
If yes - setTimeout on itself.
If not - just nothing.
I keep getting maximum call stack exceeded by Node.js
Did I make mistake somewhere which causes it to fall into infinite loop?

A: There are several mistakes in your code, for example
 In your function you set startTime to Date.now() it's alright, BUT! at the very next moment you set elapsed to Date.now() - startTime so it will be always 0, because startTime equals Date.now().
 Then you just do the same thing in the statement of your if section, it will be always true.
  SO basicly nothing changes, and that leads to an infinite loop etc..
 Either you can set startTime in your main function, or pass it thru playLights() function.
 Finally you have to pass startTime to the callback function in setTimeout() you can do it like so:
`setTimeout(function() {playLights(startTime);}, interval.toFixed());`

so your code would look something like this:
function playLights(startTime) {
    interval = (totalTimer-elapsed) * 0.026;
    lights[0].color(0, 91, 68, 3500, 0);
    lights[1].color(0, 91, 68, 3500, 0);
    setTimeout(function() {
        lights[0].color(0, 100, 100, 3500, 0);
        lights[1].color(0, 100, 100, 3500, 0);
    }, 300);
    elapsed = Date.now() - startTime;
    if (elapsed < 37000) {
        setTimeout(function(){playLights(startTime)}, interval.toFixed());
    }
    console.log("Interval: "+interval+" ,Elapsed: "+elapsed);
}

And you can call it like this:
playLights(Date.now());


Q: Uploading a small .txt file and reading its line in Java Google App Engine I am trying to upload a small txt file with few lines and read it in my rest application. I am able to get it work on my local machine with GAE (1.9.25) run time on Jetty server. However when i deploy it to cloud  and try to upload a file it throws me a runtime exception as below.
Please note i have not enabled billing or blob store. and exception does not sate anything on these lines. So i am guessing it could not be related to it.
As i am not saving the file and only used to read it and no write operation .. does this feature supported by app engine ?
    Uncaught exception from servlet
javax.servlet.UnavailableException: java.lang.NoSuchMethodException: com.sun.jersey.multipart.impl.MultiPartReaderClientSide.<init>()
    at org.mortbay.jetty.servlet.ServletHolder.makeUnavailable(ServletHolder.java:415)
    at org.mortbay.jetty.servlet.ServletHolder.initServlet(ServletHolder.java:458)
    at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:263)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
    at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
    at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
    at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
    at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
    at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.createHandler(AppVersionHandlerMap.java:206)
    at com.google.apphosting.runtime.jetty.AppVersionHandlerMap.getHandler(AppVersionHandlerMap.java:179)
    at com.google.apphosting.runtime.jetty.JettyServletEngineAdapter.serviceRequest(JettyServletEngineAdapter.java:135)
    at com.google.apphosting.runtime.JavaRuntime$RequestRunnable.run(JavaRuntime.java:457)
    at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:437)
    at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:444)
    at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:230)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:308)
    at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:300)
    at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:441)
    at com.google.apphosting.runtime.ThreadGroupPool$PoolEntry.run(ThreadGroupPool.java:235)
    at java.lang.Thread.run(Thread.java:745)

Below is my HTML, Rest Controller and Web.xml
HTML
<form action="rest/locality/upload" method="post"
    enctype="multipart/form-data;charset=UTF-8">
    <p>
        Select a new file : <input type="file" name="file" />
    </p>
    <input type="submit" value="Upload File" />
</form>

Rest Controller
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
public String uploadFile(@FormDataParam("file") InputStream fis) {

    try (BufferedReader br = new BufferedReader(new InputStreamReader(fis))) {
        String strLine = null;

and Web.xml
<servlet-name>MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>jersey.config.server.provider.packages</param-name>
        <param-value>com.smart.win.controller</param-value>
    </init-param>
    <init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature
        </param-value>
    </init-param>

Hope i have provided enough information

A: Answered my question.
Resolved it using apache commons library.
http://www.webring.org/l/rd?ring=theshogiwebring;id=13;url=http%3A%2F%2Fshogi-software%2Eblogspot%2Ein%2F2009%2F04%2Fgoogle-app-engine-and-file-upload%2Ehtml


Q: Calculate the boundary point of the cost of two curves There is a function which indicates the cost per litre for a heat storage. When buying a larger storage tank, you get it at a lower price per litre. (left plot)
In addition, there is a function that indicates how the revenue of the system gets better with increasing size of the storage tank.(right plot)

Is there a method to calculate which storage size is the most economical?


Q: Attach author to POST request to create an object It's probably very basic, but I am starting to learn Django REST Framework. So far I've succeeded with read-only operations. And now I got stuck on this problem.
I have a model:
class PersonComment(AbstractComment):
    person = models.ForeignKey(Person, on_delete=models.PROTECT)
    author = models.ForeignKey('auth.User')
    body = models.TextField(default='', blank=False)

(Here author is the author of the comment and person is a person this comment relates to; it's a genealogical site.) And a related serialiser:
class PersonCommentSerialiser(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = PersonComment
        fields = ('url', 'body', 'person', 'author')

In my HTML page, I expect a user to submit a comment by providing "body", the rest should be auto-filled. What is the best practice for filling in the "author"? In my pre-DRF Django exercises, I was doing something like this in the view:
comment = PersonComment.objects.create(
    author=request.user,
    body=new_comment_body,
    person=person
)

But if I understand everything I've read so far, this is not the way in DRF. Any help is much appreciated.

A: I would do this using the default attribute in serializer fields.
class PersonCommentSerialiser(serializers.HyperlinkedModelSerializer):
    author = serializers.PrimaryKeyRelatedField(read_only=True, default=CurrentUserDefault())

    class Meta:
        model = PersonComment
        fields = ('url', 'body', 'person', 'author')

CurrentUserDefault is a class predefined in Django REST framework for exactly this purpose. This way you don't have to overwrite create in your own serializer.
I was not sure what is the difference between person and author. But you should be able to do something similar I suppose.


Q: How to actually reduce the AWS Elasticsearch cost with Ultrawarm setup? In my ES cluster, I was having 3 master nodes and 3 data (Hot) nodes with hundreds of indices. To reduce the cost, i added 2 Ultrawarm (warm) indices and migrated all my indices to warm nodes. But it seems like the price is not depend on the storage but the instance type. Then i tried to reduce the data count from 3 to 1. It didn't allow me to do that. Can u please suggest the proper way to achieve the cost reduction from Ultrawarm instances?
Hear is the domain config

A: when moving data from Hot to UltraWarm you incur cost because you have new UltraWarm nodes and S3 storage associated with it. However, this allows you to:

*

*use less EBS size

*have less data nodes (since the some of your queries will be now handled by the UltraWarm nodes)


Q: How can I rank a list of students and display their names in php Mysql table structure looks like this:
subject ca  quiz exam exam_cumulative positionineachcourse matric_no   name

Maths   10   20   34      64                                HT/001    John
Econs   14   14   40      68                                HT/002    Mark
History 20   30   60     110                                HT/003    Grace
Chem    15   15   50      80                                HT/004    Alice
Bio     12   13   60      85                                HT/005    Larry

How can get the position of each student in each course and then get also their overall positions like 1ST, SND, 3RD, 4TH and 5TH?


Q: Is there a way to switch Bash or zsh from Emacs mode to vi mode with a keystroke? I'd like to be able to switch temporarily from emacs mode to vi mode, since vi mode is sometimes better, but I'm usually half-way through typing something before I realize I want to use vi mode.
I don't want to switch permanently to vi mode, because I normally prefer emacs mode on the command line, mostly because it's what I'm used to, and over the years many of the keystrokes have become second nature. (As an editor I generally use emacs in viper mode, so that I can use both vi and emacs keystrokes, since I found myself accidentally using them in vi all the time, and screwing things up, and because in some cases I find vi keystrokes more memorable and handy, and in other cases emacs.)

A: Aha! I looked at the readline source, and found out that you can do this:
 "\M-v": vi-editing-mode
 "\M-e": emacs-editing-mode

There doesn't appear to be a toggle, but that's probably good enough!
For posterity's sake, here's my original answer, which could be useful for people trying to do things for which there is no readline function.
Here's a way you could set it up, clearing the current command line in the process. Not what you want, I know, but maybe it'll help someone else who finds this question. In ~/.inputrc:
"\M-v": "\C-k\C-uset -o vi\C-j" # alt (meta)-v: set vi mode
"\M-e": "\C-k\C-uset -o vi\C-j" # alt (meta)-e: set emacs mode

or to toggle...this should work:
"\M-t": "\C-k\C-u[[ \"$SHELLOPTS\" =~ '\\bemacs\\b' ]] && set -o vi || set -o emacs\C-j"

These are essentially aliases, taken one step farther to map to keys in readline so that you don't have to type an alias name and hit enter.

A: The following .inputrc lines allow Meta / Alt+E to switch between emacs and vi-insert modes.
Mooshing both j and k simultaneously will take you to vi-command mode.
Note: The only English word with "kj" is "blackjack", no words contain "jk")
set keymap emacs
"\ee": vi-editing-mode
"jk": "\eejk"
"kj": "\eejk"

set keymap vi-insert
"\ee": emacs-editing-mode
"jk": vi-movement-mode
"kj": vi-movement-mode

set keymap vi-command
"\ee": emacs-editing-mode

Note: If you add a binding under keymap emacs to vi-movement-mode to try to switch straight to vi-command mode, the prompt doesn't update if you have show-mode-in-prompt on, hence the above work-around is needed.

A: You can create a toggle since the key bindings are separate between vi mode and emacs mode.
$ set -o emacs
$ bind '"\ee": vi-editing-mode'
$ set -o vi
$ bind '"\ee": emacs-editing-mode'

Now Alt-e (or Esc e) will toggle between modes.
Add this somewhere in your definition for PS1 so you have an indicator in your prompt of which mode you're in. It won't show the change immediately when you toggle modes, but it will update when a new prompt is issued.
$(set -o | grep emacs.*on >/dev/null 2>&1 && echo E || echo V)

A: I finally found out how to toggle vi and emacs mode with a single key e.g. [alt]+[i] in zsh:
# in the .zshrc
# toggle vi and emacs mode
vi-mode() { set -o vi; }
emacs-mode() { set -o emacs; }
zle -N vi-mode
zle -N emacs-mode
bindkey '\ei' vi-mode              # switch to vi "insert" mode
bindkey -M viins 'jk' vi-cmd-mode  # (optionally) exit to vi "cmd" mode
bindkey -M viins '\ei' emacs-mode  # switch to emacs mode


Q: grails one-to-many dynamic form submitting I have the following domains in my application:
class Sport implements Serializable {

    Set terms

    static hasMany = [terms: Term]

    static mapping = {
        terms cascade: "all-delete-orphan"
    }
}

class Term implements Serializable {
    String term
    String tagCode
    Sport sport

    static constraints = {

        sport nullable: false

    }
    static belongsTo = [sport: Sport]
    static mapping = {
        table "terms"
        sport cascade: "save-update,merge"
    }

}

and SportController update method:
 @Transactional
    def update(Sport sport) {
        def sportInstance = sportService.update(sport)
        ....
    }

And I also have edit.gsp where I can dynamically add/delete terms via JavaScripts and I have the following naming convention for them:

       <g:textField id="term${i}" name="terms[${i}].term"
          required=""
          value="${term?.term}"/>

        <g:textField id="synonym${i}"
          name="terms[${i}].synonym"
          value="${term?.synonym}"/>

When I add new term and submit edit.gsp it all goes normally: within SportController.update() method sport.terms Set contains new Term instance and there are no problems with it. But when I delete one term from the edit page and submit the page then within SportController.update() method sport.terms Set still contains Term instance which was deleted on the page. I'm sure that this Term instance is not submitted (I checked request and It didn't contain it) so I suspect that Grails is fetching it along with Sport instance somehow but I don't ask to do this. Maybe you have similar experience? Could you help me with this, please? I've already spent about 5 hours resolving it. Thanks!

A: One of the options is to turn Set terms into List terms, that makes GORM delete and re-create the collection upon every save()


Q: Automate creation of SharePoint 2010 Search Profile Pages Does anybody have any lead on how to automate the configuration of External Content type Profile Page host site creation (Parameterized for the site URL) as well as default actions for each entity?
I really appreciate the help!
Thanks

A: You can provision a profile page anywhere you like, it does not have to be in the default location bdc/http_etc. All you need to do is provision a web part page with a Business Data Item Builder and a Business Data Item. The URL that you pass to the page does the rest. You should look at one of the MANY blog posts for provisioning a Web part page and the rest is pretty easy.


Q: Understanding the definition of the quotient stack $[X/G]$ I'm trying to understand the definition of the quotient stack $[X/G]$ as defined in Frank Neumann's Algebraic Stacks and Moduli of Vector Bundles.
Explicitly, let $G$ be an affine smooth group $S$-scheme with right action $\rho:X\times G\to X$ on a noetherian $S$-scheme $X$. The quotient stack $[X/G]$ is the pseudofunctor
$$
[X/G]:(\mathsf{Sch}/S)^{\operatorname{op}}\to\mathsf{Grpds}
$$
defined as follows.
For an $S$-scheme $U$ let $[X/G](U)$ be the category whose objects are diagrams
$$
U\xleftarrow{\pi}E\xrightarrow{\alpha}X
$$
where $\pi$ is a principal $G$-bundle and $\alpha$ is a $G$-equivariant morphism. The morphisms in $[X/G](U)$ are the isomorphisms of principal $G$-bundles commuting with the $G$-equivariant morphisms.
For a morphism of $S$-schemes $f:U^\prime\to U$ let
$$
[X/G](f):[X/G](U)\to[X/G](U^\prime)
$$
be the functor induced by pullbacks of principal $G$-bundles.
It is not clear to me how to determine when $[X/G]$ is representable in general. My questions are:
Question 1. Is there a sufficient condition we can impose on $\rho$ to ensure that $[X/G]$ is representable? The Wikipedia article on quotient stacks says something about when the categorical quotient $X/G$ exists the canonical map $[X/G]\to\operatorname{Hom}(-,X/G)$ need not necessarily be an isomorhpism. This is somewhat opaque to me as I'm not even sure how $[X/G]\to\operatorname{Hom}(-,X/G)$ is defined.
Question 2. What is an example where $[X/G]$ is not representable?
If these questions are too broad, I'd be very grateful if someone could point me in the direction of a good reference.

A: It follows from the definitions that $[X/G]$ is representable by a scheme $S$ if and only if $X$ is a $G$-torsor over $S$, i.e. the natural map $G\times X\rightarrow X\times _SX$  given by $(g,x)\mapsto (x,gx)$ is an isomorphism.
Example 0.4 (Chapter 0, §3, page 11 of 3rd edition) in Mumford's GIT is a variety $X$ with an action of $G=SL(2)$ with trivial stabilizers and geometric quotient $\mathbb{A}^1$, but such that $X$ is not a $G$-torsor over $\mathbb{A}^1$, so $[X/G]$ is not representable.

A: The functor $[X/G]$ is not representable whenever there is non-trivial isotropy of the action of $G$ on $X$.
Let us consider the most extreme case: when $X = \bullet$ is a point (the terminal object) and $G$ is any non-trivial group. In such a case, $Hom(-,\bullet/G)$ is a singleton, as $\bullet / G = \bullet$, which is still terminal.
However, $[\bullet / G]$ is much more interesting than that! If you trace through the definition provided above (which is worth doing at least once in your life), we find that $[\bullet / G](U)$ is the collection of principal $G$-bundles over $U$, which is non-trivial most of the time. Thus it follows that, as a stack, $[\bullet / G]$ is the classifying space of $G$.
Particular examples are $[\bullet / \mathbb{G}_m]$ being the collection of line bundles, etc.
As for the question about how the morphism $[X/G] \to Hom(-,X/G)$ is defined:
In your diagram, the morphism $\alpha : E \to X$ is equivariant. You can thus complete the diagram to
$$
\begin{array}{c c c}
E & \to & X \\
\downarrow & & \downarrow\\
U & \to & X/G
\end{array}
$$
which yields the desired map.


Q: Springmvc to raml document generation I want generate raml document using springmvc controller classes is there any already devloped source code exist or not if not ayone will please guide me how should i start it

A: There are a few options, but the most popular is using SpringFox: https://github.com/springfox/springfox
It's able to generate both Swagger and RAML compatible documentations.


Q: How to do a new data frame of the latest value reported in each column? I've got a table like this:
country    continent      date         n_case         Ex         TD         TC
--------------------------------------------------------------------------------
 Italy      Europe      2022-02-24        6           NA          2          90
 Italy      Europe      2022-01-17        12          87          2          86
 USA        America     2022-02-23        NA          NA          3          65
 USA        America     2022-01-08        6           NA          5          67
 USA        America     2022-01-04        6           7           7          87
etc etc...

What I wish is a new data frame with one row per country that for each country will store as columns the country name (column = country) and continent (column = continent), and also the latest date reported for each value in the column(date, n_case, Ex, TD, TC):
the desirable data frame:
country    continent      date         n_case         Ex         TD         TC
--------------------------------------------------------------------------------
 Italy      Europe      2022-02-24        6           87          2          90
 USA        America     2022-02-23        6           7           3          65
 etc etc..

values to ignore are either NA or " " (blank)

A: With dplyr, you can sort the data by dates decreasingly and then select the first non-NA value in each column.
library(dplyr)

df %>%
  group_by(country, continent) %>%
  arrange(desc(date), .by_group = TRUE) %>%
  summarise(across(everything(), ~ .x[!is.na(.x)][1])) %>%
  ungroup()

# # A tibble: 2 × 7
#   country continent date       n_case    Ex    TD    TC
#   <chr>   <chr>     <date>      <int> <int> <int> <int>
# 1 Italy   Europe    2022-02-24      6    87     2    90
# 2 USA     America   2022-02-23      6     7     3    65

Data
df <- structure(list(country = c("Italy", "Italy", "USA", "USA", "USA"),
continent = c("Europe", "Europe", "America", "America", "America"),
date = structure(c(19047, 19009, 19046, 19000, 18996), class = "Date"),
n_case = c(6L, 12L, NA, 6L, 6L), Ex = c(NA, 87L, NA, NA, 7L),
TD = c(2L, 2L, 3L, 5L, 7L), TC = c(90L, 86L, 65L, 67L, 87L)),
row.names = c(NA, -5L), class = "data.frame")