text:
Q: CSS : Background opacity is showing on text Take this Code for example

#backgroundimage {
  background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
  height: 50px
}

#container {
  background-color: #4C4C4C;
  opacity: 0.5;
}

#text {
  color: #ffffff;
  opacity: 1;
}

      Some text here

I want to make the text color white while keeping the background image and container opacity intact.

A: Have a look at the following example. Instead of opacity use rgba.
According to docs:

opacity applies to the element as a whole, including its contents, even though the value is not inherited by child elements. Thus, the element and its children all have the same opacity relative to the element's background, even if they have different opacities relative to one another.

#backgroundimage {
  background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
  height: 500px
}

#container {
  background-color: rgba(76,76,76,.5);
}

#text {
  color: #ffffff;
}

      Some text here

A: When you set the opacity of an element, it affects its children (and if you set an opacity of a child, it can't override the opacity of the parent.
What you need to do is not to set the opacity of the element, but set opacity only to the background - using rgba.

#backgroundimage {
  background: url("https://www.solidbackgrounds.com/images/640x480/640x480-aero-solid-color-background.jpg");
  height: 500px
}

#container {
  background-color: rgba(76, 76, 76, 0.5); /* #4C4C4C;*/
  /*opacity: 0.5;*/
}

#text {
  color: #ffffff;
  opacity: 1;
}

      Some text here

A: Make the background image (640x480-aero-solid-color-background.jpg) transparent and save it as .png or .gif format.
remove "opacity: 0.5" from "#container" class and "opacity: 1" from "#text" class


text:
Q: Why is tomcat looking for JSF classes? I am trying to get my development environment up and running, and I am having trouble with Tomcat trying to load JSF classes for some reason.  My application does not use JSF; in fact, I haven't even deployed my application to tomcat yet.  I am getting a number of stack traces in the startup logs and I cannot load the default tomcat homepage when I try to open http://localhost:8080 (I just get the tomcat 404 page).
Here is what the first stack trace is:
SEVERE: Error configuring application listener of class com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener
java.lang.ClassNotFoundException: com.sun.faces.util.ReflectionUtils$ReflectionUtilsListener
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3712)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4216)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544)
    at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626)
    at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553)
    at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488)
    at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150)
    at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
    at org.apache.catalina.core.StandardService.start(StandardService.java:448)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:552)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)

I also get similar stack traces for the following other classes:
com.sun.faces.config.ConfigureListener
com.sun.faces.application.WebappLifecycleListener

I'm not sure if this is relevant, but I am running Tomcat 5.5.27 with the 1.4 compatibility pack installed, with Java 1.4.2, on Mas OS 10.5.
Thanks for any ideas!
EDIT: It seems that each of the default applications that come with Tomcat (host-manager, balancer, tomcat-docs, jsp-examples, etc) was relying on these JSF classes.  I removed these default applications, and everything seems to be working.
So, my question is now:
Why does tomcat come with applications that don't include their dependencies, and what do I need to do to make those default applicaitons work?

A: Is your tomcat installation totally clean, or is it one you have inherited?
Check if the webapps contains existing wars/directories which may be referencing JSF classes?
UPDATE: Ah -- I see you found this was the case :-)
Not sure why tomcat doesn't include all its dependencies. Perhaps you downloaded a developer release instead of a stable one?

A: You might have to clean the Tomcat work directory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error message: "Exception: Function ("DressPerPrice") is not a valid method for this service"-SOAP Web service I'm trying to create a simple web service to retrieve the name of the dress(just for trying) based on the price inputted by the user but i'm getting the error message

Exception: Function ("DressPerPrice") is not a valid method for this service

I did some research and i found that it could be because of cache but in my server i have already specified to disable caching:
The server.php file:
<?php

header("Cache-Control: no-cache");

header("Pragma: no-cache");

require_once('dbconnect.class.php');
require_once('PriceHandler.class.php');

dbconnect::initialise();

ini_set("soap.wsdl_cache_enabled","0"); //disable caching
$server = new SoapServer('http://localhost/WebService/UDDI/90210Store.wsdl');

$server->setClass('PriceHandler');
$server->setPersistence(SOAP_PERSISTENCE_REQUEST);

$server->handle();

dbconnect::close();
?>

The WSDL 90210Store.wsdl:
<?xml version="1.0" encoding="UTF-8"?>

<definitions targetNamespace="http://www.shehzad.edu/webservice" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:this="http://www.shehzad.edu/webservice" xmlns="http://schemas.xmlsoap.org/wsdl/" xsi:schemaLocation="http://schemas.xmlsoap.org/wsdl/ http://schemas.xmlsoap.org/wsdl/wsdl.xsd http://www.w3.org/2001/XMLSchema http://www.w3.org/2001/XMLSchema.xsd">

<types>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.shehzad.edu/webservice" elementFormDefault="qualified">
<xs:element name="Input" type="xs:string"/>
<xs:complexType name="DressType">
     <xs:sequence>
         <xs:element name="Name" type="xs:string"/>
         <xs:element name="Price" type="xs:integer"/>
     </xs:sequence>
</xs:complexType>

<xs:complexType name="ArrayOfDresses">
     <xs:sequence>
         <xs:element name="DressPerPrice" minOccurs="1" maxOccurs="unbounded" type="this:DressType"/>
     </xs:sequence>
</xs:complexType>
<xs:element name="Result" type="this:ArrayOfDresses"/>
</xs:schema>
</types>

<message name="getDressPerPriceRequest">
     <part name="input" element="this:Input"/>
</message>

<message name="getDressPerPriceResponse">
     <part name="result" element="this:Result"/>
</message>

<portType name="DressPerPricePortType">
     <operation name="viewDressPerPrice">
         <input message="this:getDressPerPriceRequest"/>
         <output message="this:getDressPerPriceResponse"/>
     </operation>
</portType>

<binding name="DressPerPriceBinding" type="this:DressPerPricePortType">
     <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
     <operation name="viewDressPerPrice">
         <soap:operation soapAction="http://www.shehzad.edu/webservice"/>
         <input><soap:body use="literal"/></input>
         <output><soap:body use="literal"/></output>
     </operation>
</binding>

<service name="DressPerPriceService">
     <port name="DressPerPricePort" binding="this:DressPerPriceBinding">
         <soap:address location="http://localhost/WebService/Server/Server.php"/>
     </port>
</service>

The class which keeps the method/function used by the server(PriceHandler.class.php):
<?php

class PriceHandler{

public function dressPerPrice($param)
{
    $sql = "SELECT (name,price) FROM product WHERE
            price LIKE '%".$param."%';";

    $db_result = mysql_query($sql);
    if(!db_result)
    {
        echo ("Query failed: ".mysql_error());
    }

    $ns = "http://www.shehzad.edu/webservice";

    $dressPerPrice = array();
    $result = array();

    if(mysql_num_rows($db_result) > 0)
    {
        while($row = mysql_fetch_assoc($db_result))
        {
            $dressPerPrice[] = array('Name' => $row['name'] , 'Price' => $row['price']);
        }
        mysql_free_result($db_result);
        $result = array('DressPerPrice'=>$dressPerPrice);
    }
    return $result;
}
}
?>

The category.html file(where the form is):
<!DOCTYPE HTML>

Dresses

    <form id = "get_dress" action="Client.php" method="post">

Getting dresses per price

Enter field to search for:
            <input type="text" name="search_input">

<input type="submit" value="SUBMIT" name="submit">

    </form>

If you need any other codes please let me know.
I don't really know what could be causing the error. I'm new to web services please be lenient. Thanks.


text:
Q: Is it safe to manually start a new thread in Java EE? I could not find a definitive answer to whether it is safe to spawn threads within session-scoped JSF managed beans. The thread needs to call methods on the stateless EJB instance (that was dependency-injected to the managed bean).
The background is that we have a report that takes a long time to generate. This caused the HTTP request to time-out due to server settings we can't change. So the idea is to start a new thread and let it generate the report and to temporarily store it. In the meantime the JSF page shows a progress bar, polls the managed bean till the generation is complete and then makes a second request to download the stored report. This seems to work, but I would like to be sure what I'm doing is not a hack.

A: Check out EJB 3.1 @Asynchronous methods.  This is exactly what they are for.
Small example that uses OpenEJB 4.0.0-SNAPSHOTs.  Here we have a @Singleton bean with one method marked @Asynchronous.  Every time that method is invoked by anyone, in this case your JSF managed bean, it will immediately return regardless of how long the method actually takes.
@Singleton
public class JobProcessor {

    @Asynchronous
    @Lock(READ)
    @AccessTimeout(-1)
    public Future<String> addJob(String jobName) {

        // Pretend this job takes a while
        doSomeHeavyLifting();

        // Return our result
        return new AsyncResult<String>(jobName);
    }

    private void doSomeHeavyLifting() {
        try {
            Thread.sleep(SECONDS.toMillis(10));
        } catch (InterruptedException e) {
            Thread.interrupted();
            throw new IllegalStateException(e);
        }
    }
}

Here's a little testcase that invokes that @Asynchronous method several times in a row.
Each invocation returns a Future object that essentially starts out empty and will later have its value filled in by the container when the related method call actually completes.
import javax.ejb.embeddable.EJBContainer;
import javax.naming.Context;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class JobProcessorTest extends TestCase {

    public void test() throws Exception {

        final Context context = EJBContainer.createEJBContainer().getContext();

        final JobProcessor processor = (JobProcessor) context.lookup("java:global/async-methods/JobProcessor");

        final long start = System.nanoTime();

        // Queue up a bunch of work
        final Future<String> red = processor.addJob("red");
        final Future<String> orange = processor.addJob("orange");
        final Future<String> yellow = processor.addJob("yellow");
        final Future<String> green = processor.addJob("green");
        final Future<String> blue = processor.addJob("blue");
        final Future<String> violet = processor.addJob("violet");

        // Wait for the result -- 1 minute worth of work
        assertEquals("blue", blue.get());
        assertEquals("orange", orange.get());
        assertEquals("green", green.get());
        assertEquals("red", red.get());
        assertEquals("yellow", yellow.get());
        assertEquals("violet", violet.get());

        // How long did it take?
        final long total = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start);

        // Execution should be around 9 - 21 seconds
        assertTrue("" + total, total > 9);
        assertTrue("" + total, total < 21);
    }
}

Example source code
Under the covers what makes this work is:

*

*The JobProcessor the caller sees is not actually an instance of JobProcessor.  Rather it's a subclass or proxy that has all the methods overridden.  Methods that are supposed to be asynchronous are handled differently.

*Calls to an asynchronous method simply result in a Runnable being created that wraps the method and parameters you gave.  This runnable is given to an Executor which is simply a work queue attached to a thread pool.

*After adding the work to the queue, the proxied version of the method returns an implementation of Future that is linked to the Runnable which is now waiting on the queue.

*When the Runnable finally executes the method on the real JobProcessor instance, it will take the return value and set it into the Future making it available to the caller.

Important to note that the AsyncResult object the JobProcessor returns is not the same Future object the caller is holding.  It would have been neat if the real JobProcessor could just return String and the caller's version of JobProcessor could return Future<String>, but we didn't see any way to do that without adding more complexity.  So the AsyncResult is a simple wrapper object.  The container will pull the String out, throw the AsyncResult away, then put the String in the real Future that the caller is holding.
To get progress along the way, simply pass a thread-safe object like AtomicInteger to the @Asynchronous method and have the bean code periodically update it with the percent complete.

A: Introduction
Spawning threads from within a session scoped managed bean is not necessarily a hack as long as it does the job you want. But spawning threads at its own needs to be done with extreme care. The code should not be written that way that a single user can for example spawn an unlimited amount of threads per session and/or that the threads continue running even after the session get destroyed. It would blow up your application sooner or later.
The code needs to be written that way that you can ensure that an user can for example never spawn more than one background thread per session and that the thread is guaranteed to get interrupted whenever the session get destroyed. For multiple tasks within a session you need to queue the tasks.
Also, all those threads should preferably be served by a common thread pool so that you can put a limit on the total amount of spawned threads at application level.
Managing threads is thus a very delicate task. That's why you'd better use the built-in facilities rather than homegrowing your own with new Thread() and friends. The average Java EE application server offers a container managed thread pool which you can utilize via among others EJB's @Asynchronous and @Schedule. To be container independent (read: Tomcat-friendly), you can also use the Java 1.5's Util Concurrent ExecutorService and ScheduledExecutorService for this.
Below examples assume Java EE 6+ with EJB.
Fire and forget a task on form submit
@Named
@RequestScoped // Or @ViewScoped
public class Bean {

    @EJB
    private SomeService someService;

    public void submit() {
        someService.asyncTask();
        // ... (this code will immediately continue without waiting)
    }

}

@Stateless
public class SomeService {

    @Asynchronous
    public void asyncTask() {
        // ...
    }

}

Asynchronously fetch the model on page load
@Named
@RequestScoped // Or @ViewScoped
public class Bean {

    private Future<List<Entity>> asyncEntities;

    @EJB
    private EntityService entityService;

    @PostConstruct
    public void init() {
        asyncEntities = entityService.asyncList();
        // ... (this code will immediately continue without waiting)
    }

    public List<Entity> getEntities() {
        try {
            return asyncEntities.get();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new FacesException(e);
        } catch (ExecutionException e) {
            throw new FacesException(e);
        }
    }
}

@Stateless
public class EntityService {

    @PersistenceContext
    private EntityManager entityManager;

    @Asynchronous
    public Future<List<Entity>> asyncList() {
        List<Entity> entities = entityManager
            .createQuery("SELECT e FROM Entity e", Entity.class)
            .getResultList();
        return new AsyncResult<>(entities);
    }

}

In case you're using JSF utility library OmniFaces, this could be done even faster if you annotate the managed bean with @Eager.
Schedule background jobs on application start
@Singleton
public class BackgroundJobManager {

    @Schedule(hour="0", minute="0", second="0", persistent=false)
    public void someDailyJob() {
        // ... (runs every start of day)
    }

    @Schedule(hour="*/1", minute="0", second="0", persistent=false)
    public void someHourlyJob() {
        // ... (runs every hour of day)
    }

    @Schedule(hour="*", minute="*/15", second="0", persistent=false)
    public void someQuarterlyJob() {
        // ... (runs every 15th minute of hour)
    }

    @Schedule(hour="*", minute="*", second="*/30", persistent=false)
    public void someHalfminutelyJob() {
        // ... (runs every 30th second of minute)
    }

}

Continuously update application wide model in background
@Named
@RequestScoped // Or @ViewScoped
public class Bean {

    @EJB
    private SomeTop100Manager someTop100Manager;

    public List<Some> getSomeTop100() {
        return someTop100Manager.list();
    }

}

@Singleton
@ConcurrencyManagement(BEAN)
public class SomeTop100Manager {

    @PersistenceContext
    private EntityManager entityManager;

    private List<Some> top100;

    @PostConstruct
    @Schedule(hour="*", minute="*/1", second="0", persistent=false)
    public void load() {
        top100 = entityManager
            .createNamedQuery("Some.top100", Some.class)
            .getResultList();
    }

    public List<Some> list() {
        return top100;
    }

}

See also:

*

*Spawning threads in a JSF managed bean for scheduled tasks using a timer

A: I tried this and works great from my JSF managed bean
ExecutorService executor = Executors.newFixedThreadPool(1);

@EJB
private IMaterialSvc materialSvc;

private void updateMaterial(Material material, String status,  Location position) {

    executor.execute(new Runnable() {
        public void run() {
            synchronized (position) {
                // TODO update material in audit? do we need materials in audit?
                int index = position.getMaterials().indexOf(material);
                Material m = materialSvc.getById(material.getId());
                m.setStatus(status);
                m = materialSvc.update(m);
                if (index != -1) {
                    position.getMaterials().set(index, m);
                }

            }
        }
    });

}

@PreDestroy
public void destory() {
    executor.shutdown();
}


text:
Q: What does Static mean in VB? What does Static mean in VB?
EDIT - Code sample for reference
Module Module1

    Sub Main()
        Dim a = New Foo
        Dim b = New Foo
        Console.WriteLine(a.Boom)
        Console.WriteLine(a.Boom)
        Console.WriteLine(a.Boom)
        Console.WriteLine(b.Boom)
    End Sub

End Module

Class Foo
    Function Boom() As Integer
        Static callCount As Integer = 0
        callCount += 1
        Return callCount
    End Function
End Class

A: It's a way of having fields that are local to a method.  Basically, the value is maintained between calls but not accessible in other parts of the class.  See Static Local Variables in VB.NET for some implementation information.
EDIT: Jonathan, you're right that the fields don't have to be Shared/static.   If the function/sub is declared Shared, it will be a Shared/static field.  Otherwise, it will be a instance field.  Either way, it is persistent across calls and local to the method.  The below example (to continue a theme) shows both behaviors clearly:
Class Fibonacci

    Public Function FibonacciInstance() as Integer
           Static i as Integer = -1
           Static j as Integer = 1
           Dim k as Integer

           k = i + j
           i = j
           j = k

           return k
    End Function

    Public Shared Function FibonacciShared() as Integer
           Static i as Integer = -1
           Static j as Integer = 1
           Dim k as Integer

           k = i + j
           i = j
           j = k

           return k
    End Function

    Shared Sub Main()
        Dim d as Integer
        Dim a = New Fibonacci
        Dim b = New Fibonacci
        For d = 0 to 10
            System.Console.WriteLine("a.FibonacciInstance: " & a.FibonacciInstance())
            System.Console.WriteLine("b.FibonacciInstance: " & b.FibonacciInstance())
            System.Console.WriteLine("a.FibonacciShared: " & a.FibonacciShared())
            System.Console.WriteLine("b.FibonacciShared: " & b.FibonacciShared())
        Next d
    End Sub

End Class


text:
Q: Check if a popup window is closed I am opening a popup window with
var popup = window.open('...', '...');

This javascript is defined in a control. This control is then used from a web page. I want to reload the page which opens this popup when the popup is closed.
Basically user is required to input some denominations in the popup window and submit. These denominations are then stored in user sessions. And when user clicks submit I am closing the popup window and at the same time want to refresh the window which opens this popup to refetch the updates which user made in the popup.
I am trying to do
var popup = window.open('...','...');
if (popup) {
  popup.onClose = function () { popup.opener.location.reload(); }
}

I guess I am doing it wrong coz this isn't seems to be working.
For testing the issue I've even tried this but no alert appeared.
if (popup) {
  popup.onclose = function() {
    alert("1.InsideHandler");
    if (opener && !opener.closed) {
      alert("2.Executed.");
      opener.location.reload(true);
    } else {
      alert("3.NotExecuted.");
    }
  }
}

A: Here's what I suggest.
in the popup you should have:
<script type="text/javascript">

function reloadOpener() {
  if (top.opener && !top.opener.closed) {
    try {
      opener.location.reload(1);
    }
    catch(e) {
    }
    window.close();
  }
}
window.onunload=function() {
  reloadOpener();
}
</script>

<form action="..." target="hiddenFrame">
</form>
<iframe style="width:10px; height:10px; display:none" name="hiddenFrame" src="about:blank"></iframe>

then in the server process you can return
<script>
   top.close();
</script>

Old suggestions
There is no variable called popup in the popup window.
try
var popup = window.open('...','...');
if (popup) {
  popup.onclose = function () { opener.location.reload(); }
}

or with a test:
popup.onclose = function () { if (opener && !opener.closed) opener.location.reload(); }

PS: onclose is not supported by all browsers
PPS: location.reload takes a boolean, add true if you want to not load from cache
as in opener.location.reload(1);

A: Try this:
window.opener.location.reload(true);

or
Into the popup before closing
window.opener.location.href = window.opener.location.href;
window.close();

A: Solution for same origin popups
If your popup is from the same origin as the opener, you can attach an event listener to the popup like this:
const popup = window.open('...', '...');

popup.window.addEventListener('load', () => {
    popup.window.addEventListener('unload', () => {
        console.log('> Popup Closed');
        // window.location.reload();
    });
});

Note that the unload event listener needs to be added once the popup is loaded. This is because the unload event fires also on page load in popups.
Solutions for different origin popups
If your popup is not from the same origin as the opener, you will receive an error like this: Blocked a frame with origin from accessing a cross-origin frame. For security reasons, you can only access a limited set of properies from both opener and the opened window.
More about that here.
Solution 1
You have to create the unload event listener in your popup and call window.opener.location.replace(OPENER_URL). The drawback of this is that you need the opener's url. Instead of harcoding, you could pass the url as a query string to the popup.
Note that window.opener.location.reload() is not allowed in a cross-origin scenario.
Solution 2
Alternatively, you could create an interval in the opener to periodically check wheter the window is open or not with the window.closed property.
const popup = window.open('...', '...');

const interval = setInterval(() => {
    if (popup.closed) {
        clearInterval(interval);
        console.log('> Popup Closed');
        // window.location.reload();
    }
}, 500);

A: Instead you should use a modal dialog like so
var popup = window.showModalDialog("page.html", "", params);

This would stop your at this line until the dialog is closed.
Somewhere in your page.html you would then code some javascript to set the window.returnValue which is what will be place the the popup variable.
Update
Window.showModalDialog() is now obsolete.

A: Ok so what you do is as follows.
create a method "setWindowObjectInParent" then call that in the popup.
var popupwindow;
function setWindowObjectInParent(obj)
{
popupwindow = obj;
}

Now you have an object that you can call focus on.
So in the popup add
$(window).unload(function(){
window.opener.setWindowObjectInParent();
});
window.opener.setWindowObjectInParent(window);

This will unset the obj when the popup is closed and set the object when it is opened.
Thus you can check if your popup is defined and then call focus.


text:
Q: Using mod_rewrite to update urls after ViewVC migration At work we have a ViewVC system which has been migrated from one machine to another. The version has also been upgraded. The old system used /cgi-bin/viewvc.cgi as the base of all its urls and the new system uses /viewvc. The hostname remains the same.
We have a lot of documentation which has ViewVC links and I would like those to still work as before. I'm a software developer by day so not an expert on apache but I thought that mod_rewrite would be the right route. Unfortunately I can't seem to get it to do what I want.
Without any changes, when I go to the url /cgi-bin/viewvc.cgi I get a 404. Here's what I see in the apache logs:
==> /var/log/httpd/error_log <==
[Thu May 31 03:13:10 2012] [error] [client 172.16.3.52] script not found or unable to stat: /var/www/cgi-bin/viewvc.cgi

==> /var/log/httpd/access_log <==
172.16.3.52 - - [31/May/2012:03:13:10 +0100] "GET /cgi-bin/viewvc.cgi HTTP/1.1" 404 289 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.17 Safari/536.11"

When I add the RewriteEngine/RewriteRule entries to /etc/httpd/httpd.conf as below ...
<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all

    RewriteEngine on
    RewriteRule ^/cgi-bin/viewvc.cgi(.*) /viewvc$1
</Directory>

I get a 403. Here's what's in the logs:
==> /var/log/httpd/error_log <==
[Thu May 31 03:15:35 2012] [error] [client 172.16.3.52] Options FollowSymLinks or SymLinksIfOwnerMatch is off which implies that RewriteRule directive is forbidden: /var/www/cgi-bin/viewvc.cgi

==> /var/log/httpd/access_log <==
172.16.3.52 - - [31/May/2012:03:15:35 +0100] "GET /cgi-bin/viewvc.cgi HTTP/1.1" 403 293 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.17 Safari/536.11"

If I edit the Options line above to include FollowSymLinks and SymLinksIfOwnerMatch I'm back to a 404.
==> /var/log/httpd/error_log <==
[Thu May 31 03:17:20 2012] [error] [client 172.16.3.52] script not found or unable to stat: /var/www/cgi-bin/viewvc.cgi

==> /var/log/httpd/access_log <==
172.16.3.52 - - [31/May/2012:03:17:20 +0100] "GET /cgi-bin/viewvc.cgi HTTP/1.1" 404 289 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.17 Safari/536.11"

What am I doing wrong? Do I have the rule wrong or have it put it in the wrong place? Is mod_rewrite even he correct approach?
Versions: In case it is important, I am on a Fedora 17 machine with the following packages:

*

*httpd-2.2.22-4.fc17.x86_64

*viewvc-1.1.13-2.fc17.noarch

*viewvc-httpd-wsgi-1.1.13-2.fc17.noarch

A: To answer my own question, the problem was that 1) the period in the pattern match needed escaping and 2) I put the rule in the wrong place. I should have put it at the top level rather than under cgi-bin.

For completion, here's how I worked it out:
I turned on rewrite logging so I could see exactly what the rewrite engine was doing:
RewriteLog /tmp/rewrite.log
RewriteLogLevel 9

Using the original rewrite rule, I get this being logged:
127.0.0.1 - - [02/Jun/2012:23:43:49 +0100] [localhost/sid#b76f4018][rid#b6d4a058/initial] (2) init rewrite engine with requested uri /cgi-bin/viewcvs.cgi
127.0.0.1 - - [02/Jun/2012:23:43:49 +0100] [localhost/sid#b76f4018][rid#b6d4a058/initial] (3) applying pattern '^/cgi-bin/viewvc.cgi(.*)' to uri '/cgi-bin/viewcvs.cgi'
127.0.0.1 - - [02/Jun/2012:23:43:49 +0100] [localhost/sid#b76f4018][rid#b6d4a058/initial] (1) pass through /cgi-bin/viewcvs.cgi

When I changed the rule to escape the period:
RewriteRule ^/cgi-bin/viewvc\.cgi(.*) /viewvc$1

I got this logged.
192.168.1.64 - - [03/Jun/2012:00:08:53 +0100] [192.168.1.128/sid#b76ed018][rid#b6d39058/initial] (2) init rewrite engine with requested uri /cgi-bin/viewvc.cgi/
192.168.1.64 - - [03/Jun/2012:00:08:53 +0100] [192.168.1.128/sid#b76ed018][rid#b6d39058/initial] (3) applying pattern '^/cgi-bin/viewvc\.cgi(.*)' to uri '/cgi-bin/viewvc.cgi/'
192.168.1.64 - - [03/Jun/2012:00:08:53 +0100] [192.168.1.128/sid#b76ed018][rid#b6d39058/initial] (2) rewrite '/cgi-bin/viewvc.cgi/' -> '/viewvc/'

So it was the bare "." that was making it not match. But this is "Any single character" according to the documentation, so it was unclear to me why it didn't work.
The rewriting guide escapes them all over the place, but with no indication that it is required or why, which is a shame.


text:
Q: How to add logic to a powershell script? Need help in sorting out a data from my output, I want to show only a output saying ALL OK when STATE is RUNNING, and NOT OK if the STATE is Faulted (or any other string).
How can I achieve this?
Invoke-Command -ComputerName XXXXX,XXXX -ScriptBlock { hastatus -sum; VXPRINT -VPl } -credential XXXXX

Output:
-- SYSTEM STATE
-- System               State                Frozen

A  XXXXXXXXXXXXX        RUNNING              0
A  XXXXXXXXXXXXX        RUNNING              0

A: Just following your output, I think something like this is what you want?
$output = @"
-- SYSTEM STATE
-- System               State                Frozen

A  XXXXXXXXXXXXX        RUNNING              0
A  XXXXXXXXXXXXX        RUNNING              0
A  XXXXXXXXXXXXX        ANYTHINGBUTRUNNING   0
"@

($output -split '\r?\n') | ForEach-Object {
    if ($_ -match '^[A-Z]\s+\w+') {
        $system = $matches[0]
        if ($_ -match '\bRUNNING\b') {
            "$system  ALL OK"
        }
        else {
            "$system  NOT OK"
        }
    }
}

The resulting PowerShell console output will be:
A  XXXXXXXXXXXXX  ALL OK
A  XXXXXXXXXXXXX  ALL OK
A  XXXXXXXXXXXXX  NOT OK


text:
Q: dynamic javascript/jquery form submission with results from php/mysql I would like to create a search page which allows somebody to select a number of options (check boxes) which in turn creates multiple WHERE clauses in a SQL statement but not sure how to go about this.
In simple terms - if I check the boxes for: "pending", "submited", "processed" then hit submit on my form, a sql statement is created which basically says:
"SELECT * FROM table.tablename WHERE (pending="Y", submitted="Y", processed="Y")... and so on.
The items in the parenthesis will be dynamic so the sql statement will not always be the same and the values do not necessarily equal Y (i would like to use prepared statements in PDO for this).
any ideas?
EDIT
based on responses it seems some are assuming the fieldnames in the WHERE clause are known. As I mention in another comment below, there could be 2 or 2000 fieldnames in this clause, none of which are known to the system ahead of time (if checkbox A is checked, include it, if not, dont...)
SELECT * FROM table WHERE ($whereclause_string)
where
$whereclausestring = "unknown_field1=unknownvalue1, unknown_field2=unknownvalue2, unknown_field3=unknownvalue3..."

A: I am assuming this is a web page (as you are talking about checkboxes, search &c., and that it is tagged with javascript and PHP.)
These checkboxes must, then, be part of a form. I would think you need to harvest the submitted data (which would be as name=value pairs), and insert the variables as you construct the query.
How you do this would depend on the context of the SQL query, but, I think the simplest way, if not the most secure, would be to construct the query as follows (in your PHP script):
"SELECT * FROM table.tablename WHERE ('pending = ' . $_POST['pending'] . ', submitted = ' . $_POST['submitted'] . ', processed = ' . $_POST['processed']);"

'POST' can be substitued with 'GET', if necessary, or even 'COOKIE' or 'REQUEST', although, you probably want to be more sure what you are getting.
Also in terms of security, it would be extremely wise to check that the values are what you expect them to be, in order to prevent SQL injection. You can do this by checking the values against certain conditions (using conditional loops), and assigning them to a local variable if the checks prove successful.
Hope this helps you.
Chops

A: Create PHP script with MySQL connection and query. Then use jQuery to make AJAX or JSON request to PHP script.
PHP:
header('content-type:application/json;charset=utf-8');
$defaults = array('pending' => 'Y','submitted' => 'Y','processed' => 'Y');
$pending = ($_GET['pending']) ? $_GET['pending'] : $defaults['pending'];
$submitted = ($_GET['submitted']) ? $_GET['submitted'] : $defaults['submitted'];
$processed = ($_GET['processed']) ? $_GET['processed'] : $defaults['processed'];

$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$db = mysql_select_db('foo', $link);
$query = mysql_query('SELECT * FROM table.tablename WHERE (pending="'.$penging.'", submitted="'.$submitted.'", processed="'.$processed.'")');
$result = array();

if (!$link) {
    die('Could not connect: '.mysql_error());
}

if (!$db_selected) {
    die ('Can\'t use foo : '.mysql_error());
}

if (!$result) {
    die('Invalid query: '.mysql_error());
}

$i = 0;
while ($row = mysql_fetch_assoc($result)) {
    $result[$i]['row-name'] = $row['row-name'];
    $i++;
}

mysql_close($link);

return json_encode($result);

jQuery:
$('#some-submit-button').click(function(){
    var pending = $('#some-pending-input').val(),
    submitted = $('#some-submitted-input').val(),
    processed = $('#some-processed-input').val();

    $.getJSON('/path/to/script.php?pending=' + pending + '&submitted=' + submitted + '&processed=' + processed,function(data){
        $.each(data,function(i){
            $('#some-block-for-results').append('Getting data from MySQL never been so easy: ' + data[i].some-row-name + ', ' + data[i].some-other-row-name);
        });
    });
    return false;
});

This is just a quick example. Change PHP/jQ for your needs.

A: Perhaps something like this?
<?php
// construction
$options = array('foo', 'bar');
foreach ($options as $option)
    printf('%s: <input type="checkbox" value="%s" />%s', $option, $option, PHP_EOL);

// submission
$wheres = array();
foreach ($options as $option)
    if (isset($_POST[$option])) // should only be present if "checked"
        $wheres[] = sprintf('%s = "%s"', $option, mysql_real_escape_string($_POST[$option])); // sanitize!!

$where = implode(', ', $wheres); // foo = "yes", bar = "yes"
?>

EDIT: The jQuery should be easy for this, using a selector such as 'input:checked' to gather all of the checked options.


text:
Q: System wide variables not accessible by System V init scripts I have a script in /etc/init.d/ called foo.sh that runs six (JAVA) Spring Boot jars. All of the jars require environmental variables to run. This script was added to rc.d via update-rc.d foo.sh defaults. Environmental variables needed were added to /etc/environment/.
Whenever I reboot the server, the script runs but one of the java modules cannot find env variables, the other 5 run correctly. If I try to run the script manually, it has no issues at all. I have ran this a million ways in order to determine if the problem is in the java code, but it is not.
What exactly is happening here and how could I solve it so that on a reboot all jars can access global environmental variables?

A: I cannot tell you exactly why that's happening but I can suggest a couple things.
You can always create a simple test script in that directory and invoke it the same way as the other jars, that simply displays the environment:
#!/bin/sh
echo "$(env)" >/tmp/env-test

Secondly, you can always prepend any environment variables that you want available to a command, like:
FOO=bar mycommand
This is often useful for temporarily running a command using a variable without having to set it.


text:
Q: How put the free memory info in a texview How can i put this in a textview?
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
memoryInfo.availMem;

the textview id is for example freemem. The textview is in a second tab of a swipeview.thans

A: Put this in your layout XML
  <TextView android:id="@+id/myTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

and this in your activity:
   TextView myTextView = (TextView)findViewById(R.id.myTextView);
    ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
    activityManager.getMemoryInfo(memoryInfo);
    myTextView.setText("" + memoryInfo.availMem);

memoryInfo.availMem is the available memory on the system.
 memoryInfo.totalMem is the total memory accessible by the kernel.
Here is a link to a good answer about memory availability.


text:
Q: Trying to start Stopwatch based off of old split saved in .txt file The closest I have gotten is to get the last line in the .txt file (there are a bunch of splits saved), and then add that to the current elapsed time, and then display THAT in the label box:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick

    Dim lines() As String = IO.File.ReadAllLines(filepath)
    Dim lastline As String

    lastline = lines(lines.Length - 1)

    Dim elapsed As TimeSpan = Me.stopwatch.Elapsed
    Dim pastHours As String
    pastHours = lastline.Substring(0, 2)
    Dim currentHours As Double = elapsed.Hours + pastHours

    Dim pastMinutes As String
    pastMinutes = lastline.Substring(3, 2)
    Dim currentMinutes As Double = elapsed.Minutes + pastMinutes

    Dim pastSeconds As String
    pastSeconds = lastline.Substring(6, 2)
    Dim currentSeconds As Double = elapsed.Seconds + pastSeconds

    Dim pastMilliseconds As String
    pastMilliseconds = lastline.Substring(9, 3)
    Dim currentMilliseconds As Double = elapsed.Milliseconds + pastMilliseconds

    Label1.Text = Format(currentHours, "00") & ":" & Format(currentMinutes, "00") & ":" & Format(currentSeconds, "00") & "." & (currentMilliseconds)
End Sub

The only problem with that, is that instead of having 1000 milliseconds in a second, 60 seconds in a minute, etc, it will go up to 60 PLUS whatever that last split has saved. For example, if the last split saved was 34 seconds, it will take until a displayed amount of 94 seconds before it ticks up a minute, and even then it will start the seconds over at 34 seconds.

A: You can add TimeSpan values to each other. In your case, you could do:
Dim pastElapsed As TimeSpan = New TimeSpan(0, pastHours, pastMinutes, pastSeconds, pastMilliseconds)
Dim currentElapsed As TimeSpan = elapsed + pastElapsed
Dim formatted As String = Format(currentElapsed.Hours, "00") & ":" & Format(currentElapsed.Minutes, "00") & ":" & Format(currentElapsed.Seconds, "00") & "." & Format(currentElapsed.Milliseconds, "000")
Label1.Text = formatted


text:
Q: can't write unknown attribute `example` typed_store - Rails I have this models where I wanna update my typestored columns using update_columns active record
I have searched numerous answers in stack, doesn't seems to have lot of resources regarding typestored.
show.html.erb
<%= form_tag print_booking_path(@booking), method: 'post' do %>
 <%= label_tag :name %>
 <%= text_field_tag :name, '', class: 'form-control' %>
 <%= label_tag :age %>
 <%= text_field_tag :age, '', class: 'form-control' %>
 <%= submit_tag "Print", class: "btn btn-default" %>
 <%= link_to 'Cancel', '#', class: 'btn btn-default', data: { dismiss: 'modal' } %>
<% end %>

bookings_controller
def print
    @booking = Booking.find(params[:id])
    if @booking.print_model(current_user, params[:name], params[:age])
      render :print
    else
      render :print
    end
  end

booking model
def print_model(user, name_test, age_test)
 self.update_columns(name: name_test, age: age_test)
end

typestore under booking model
typed_store :profile, coder: PostgresCoder do |i|
 i.string :name, default: ""
 i.integer :age, default: 0
end

the error appeared to be like this
can't write unknown attribute name
it's same like if I wanna to update like this self.increment!(:age)

A: I made a few tests here, and I don't know if it makes sense, but in case of updating stores, all the typestored columns are inside just one real column in the database (that are a normally in hash or Json).
So the straight foward way to do it is to wrap in brackets.
Try changing:
self.update_columns( name: name_test, age: age_test )

To:
self.update_columns( profile: { name: name_test, age: age_test} )


text:
Q: IF DENTRO DE UM SELECT     SELECT  @VL_RET_INSS                = SUM(VL_RET_INSS),
            @VL_RET_IRRF                = SUM(VL_RET_IRRF),
      FROM  TABELA WHERE VALOR_TABELA > 0

Gostaria de que quando o valor VL_RET_IRRF fosse menor que 10 o campo @VL_RET_IRRF recebesse 0 e quando fosse maior que 10 recebesse como eu fiz hoje, poderiam me ajudar?
Não sei se deveria usar um if ou qual a melhor forma, obrigado.

A: Você pode usar CASE WHEN
SELECT CASE WHEN @VL_RET_IRRF > 10 THEN 10 ELSE @VL_RET_IRRF END AS Result FROM Tabela

No SQL acima verifica se o @VL_RET_IRRF é menor que 10, se for mostra 10 senão mostra @VL_RET_IRRF
Também é possível utilizar o comando IF dentro do SQL. Falando em SQL Server, nas versão mais novas a partir do SQL Server 2012 tem a função IIF que é uma abreviação da função IF ELSE. Veja um exemplo;
SELECT IIF(@VL_RET_IRRF > 10,10,@VL_RET_IRRF) AS Result FROM Tabela

Pra entender melhor a função IIF:
IIF(Expressão de comparação, resultado se for verdadeiro, resultado se for falso)

A: Simples:
SELECT
CASE WHEN @VL_RET_IRRF > 10 THEN 10 ELSE @VL_RET_IRRF END AS Result
FROM Tabela

Múltiplos:
SELECT
(CASE WHEN @VL_RET_IRRF >= 10 THEN 10 ELSE
(CASE WHEN @VL_RET_IRRF >= 20 THEN 20 ELSE
(CASE WHEN @VL_RET_IRRF >= 30 THEN 30 ELSE @VL_RET_IRRF END)
END) END) AS Result
FROM Tabela

Documentação: Aqui


text:
Q: Filtering by a Family in Revit API For a while now I have been looking for a way to filter elements by their family. For example, I want all of the elements that are of family Junction Boxes - Load. I am somewhat new to the Revit API, and I do know about category filters and even a family instance filter. But I do not understand how I get the family symbol for the Junction Boxes - Load family, for example. Is there even a good way of doing this? Or am I better off filtering specific Types within the family? If so, how would I go about doing this?

A: Welcome to Revit programming!
The most effective way to get started learning and programming with the Revit API, including installation and use of the SDK, is to work through the getting started material, especially the step-by-step instructions provided by the DevTV and My First Revit Plugin video tutorials:
http://thebuildingcoder.typepad.com/blog/about-the-author.html#2
To answer your question: you use filtered element collectors to retrieve elements from the Revit database:
http://www.revitapidocs.com/2017/263cf06b-98be-6f91-c4da-fb47d01688f3.htm
You can apply many filters to them. In your case, you can directly filter for FamilySymbol instances.
There are two ways to limit the search further to retrieve only those you are interested in, named "Junction Boxes - Load":

*

*Efficient: use a parameter filter

*Simple: use .NET post-processing or LINQ

More details are provided abundantly by The Building Coder in the topic group on Retrieving Elements Using FilteredElementCollector.

A: Jacob,
Jeremy's answer is the right one. Here's an example of code that could be used to get all Family Instances of certain Family name:
The efficient way that Jeremy mentioned would be to use the Parameter Filter:
var famType = new FilteredElementCollector(m_doc)
    .OfClass(typeof(Family)) // This is called a class filter
    .FirstOrDefault(x => x.Name == "YourFamilyName");

if (famType != null)
{
    const BuiltInParameter testParam = BuiltInParameter.ELEM_FAMILY_PARAM;
    var pvp = new ParameterValueProvider(new ElementId((int)testParam));
    var fnrv = new FilterNumericEquals();
    var ruleValId = famType.Id;
    var paramFr = new FilterElementIdRule(pvp, fnrv, ruleValId);
    var epf = new ElementParameterFilter(paramFr);

    var results = new FilteredElementCollector(m_doc)
        .OfClass(typeof(FamilyInstance))
        .WherePasses(epf)
        .ToElements();
}

The less efficient way would be to do this:
var result = new FilteredElementCollector(m_doc)
    .OfClass(typeof(FamilyInstance))
    .Cast<FamilyInstance>()
    .Where(x => x.get_Parameter(BuiltInParameter.ELEM_FAMILY_PARAM).AsValueString() == "YourFamilyName");

I know that Jeremy mentioned that the second method would be less efficient, but I am personally not entirely sure. The ElementParameterFilter is a Slow Filter which expands all of the elements in memory anyways. Event though it's coupled with two Quick Filters for Family and FamilyInstance selection, that's still a considerable overhead as opposed to the more direct approach that you can take using LINQ.
You also asked about being able to select FamilySymbol
var famType = new FilteredElementCollector(m_doc)
        .OfClass(typeof(FamilySymbol))
        .FirstOrDefault(x => x.Name == "YourFamilyTypeName");


text:
Q: Pass hosting environment for self-hosting I'm trying to run ASP.NET Core (.NET 4.6.1) application as self hosting by means of weblistener
I've add a command:
"commands": {
    "web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
},

and necessary dependencies in project.json
When I start my application via Visual Studio it's works fine
src\ProjectName\bin\Release\net461\win7-x64\ProjectName.exe

ProjectName.exe starts as web server with Hosting environment: Development
But when I run it by hand ProjectName.exe runs with Hosting environment: Production and it's not working properly.
First of all I want find way to run application by hand with Development environment
In VS I have this option:

A: When you start the application Visual Studio will automatically set the environment variables for you (based on settings from launchSettings.json in the properties folder).
When you run from commandline or double-click, you need to set the environment variable yourself using setx ASPNETCORE_ENVIRONMENT "Development" (Commandline) or $Env:ASPNETCORE_ENVIRONMENT = "Development" (Powershell).


text:
Q: Matrices problem? Does anyone know how to do this?
1.) Write two matrices A and B such that AB = BA, but neither A nor B is the identity matrix.

A: Take any polynomial $P$ and let $B=P(A)$ then clearly
$$AP(A)=P(A)A$$
since $A$ commutes with $I$ and with itself.


text:
Q: How on list item pass Data to another Activity? I have in my php a request that get hospital patients information, in my list Item i have then patients names. I'd like to know, how can get the data that belong to one of the Patient Item clicked, appaering in a new activity ?

A: You can add extras to an intent, then inside of the new activity you can pull those extras out.
Inside the first Activity:
Intent i = new Intent(this, SomeOtherActivity.class);
i.putExtra("key", "value");
startActivity(i);

Inside the other activity:
String mValue = this.getIntent().getStringExtra("key");
// mValue will now be set to the string "value"

You can add more than one extra if you need to and you can always look them up using the same key that you added them with.


text:
Q: Stack Overflow in XmlReader C# this code throws me an error.
I explain the error in the code:
public partial class Util
{
    public string LoadFunctions()
    {

        string codeFunctionsString = "";

        XmlReader reader = XmlReader.Create("fname2.xml");
        //The line above throws an error:
        //"An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll"
        //The file DOES exist, so I don't know what the problem is.

        reader.Read();
        while (reader.Read())
        {

            reader.ReadToFollowing("item");
            //reader.
            codeFunctionsString += reader.Value + "|";

            Form1 win = new Form1();

            win.CodeInput.Text += reader.Value + " ";

        }
        return codeFunctionsString;
    }
}

A: Based on your reply to my comment-based question, here's what's going on.
class Form1 : Form {
    public Form1() {
        InitializeComponents();

        Util u = new Util();
        string functions = u.LoadFunctions();
    }
}

In this case, I'm guessing that the call is in either the constructor (as above), or in Form1_Load (not shown, but same idea).
Well, what happens is that when you call LoadFunctions, it creates a Form1, which calls LoadFunctions, which creates a Form1, which calls LoadFunctions, which creates a Form1, which calls LoadFunctions, which creates a Form1, which calls LoadFunctions, which creates a Form1, which calls LoadFunctions, which creates a Form1, which-ERROR: StackOverflowException
The resolution is to either not create a form in LoadFunctions (perhaps, make it an argument you pass in?), or don't call LoadFunctions in Form1.


text:
Q: Unit testing: TDD with POCO Objects with navigation properties (relationship fixup) I've been trying to find a good solution to this but with no luck, so either I'm not searching for the right keywords, or we're doing things wrong from the start so the problem shouldn't really exist.
Update for clarification: I would like this to work as a unit test rather than as an integration test, so I don't want this to hit the database, but I want to mock the associations made when EF persists changes in my unit test.
Original question:
Say you are testing a service method like so:
[Test]
public void AssignAuthorToBook_NewBookNewAuthor_SuccessfullyAssigned()
{
  IBookService service = new BookService();

  var book = new Book();

  var Author = new Author() { Id = 123 };

  service.AssignAuthorToBook(book, author);

  Assert.AreEqual(book.AuthorId, 123);
}

Now lets say that this test fails because AssignAuthorToBook actually works using the code book.Author = author; so it is not assigning the AuthorId, it is assigning the entity. When this is persisted using the Entity Framework SaveChanges() method on the context it will associate the entities and the IDs will correlate. However, in my example above the logic of Entity Framework would not have been applied. What I am saying is the code will work once SaveChanges() has been called, but the unit test will fail.
In this simple example, you'd probably know straight away why your test had failed as you had just written the test immediately before the code and could easily fix it. However, for  more complicated operations and for operations where future changes that may change the way entities are associated, which will break tests but may not break functionality, how is unit testing best approached?
My thoughts are:

*

*The service layer should be ignorant of the persistence layer - should we mock the Data Context in the unit tests to mock the manner that it works? Is there an easy way to do this that will automatically tie up the associations (i.e. assign to correct  entity if Id is used or assign the correct Id if the entity is used)?

*Or should the tests be structured in a slightly different manner?

The tests that exist in the current project I have inherited work as in my example above, but it niggles with me that there is something wrong with the approach and that I haven't managed to find a simple solution to a possibly common problem. I believe the Data Context should be mocked, but this seems like a lot of code will need to be added to the mock to dynamically create the associations - surely this has already been solved?
Update: These are the closest answers I've found so far, but they're not quite what I'm after. I don't want to test EF as such, I just wondered what was best practise for testing service methods that access repositories (either directly or via navigation properties through other repositories sharing the same context).
How Do I Mock Entity Framework's Navigational Property Intelligence?
Mocked datacontext and foreign keys/navigation properties
Fake DbContext of Entity Framework 4.1 to Test
Navigation properties not set when using ADO.NET Mocking Context Generator
Conclusion so far: That this is not possible using unit testing, and only possible using integration testing with a real DB. You can get close and probably code something to dynamically associate the navigation properties, but your mock data context will never quite replicate the real context. I would be happy if any solution enabled me to automatically associate the navigation properties which would allow my unit tests to be better, if not perfect (the nature of a successful unit test  doesn't by any means guarantee functionality anyway)  The ADO.NET Mocking Context Generator comes close, but it appears that I'll have to have a mock version of every entity which will not work for me in case functioanlity is added to them using partial classes in my implementation.

A: I'd argue that you are expecting a result from your test that implies the use of several dependencies, arguably not qualifying it as a unit test, especially because of an implied dependency on EF.
The idea here is that if you acknowledge that your BookService has a dependency on EF you should use a mock to assert it interacts correctly with it, unfortunately EF doesn't seem to like to be mocked, so we can always put it under a repository, here's an example of how that test could be written using Moq:
[Test]
public void AssignAuthorToBook_NewBookNewAuthor_CreatesNewBookAndAuthorAndAssociatesThem()
{
  var bookRepositoryMock = new Mock<IBookRepository>(MockBehavior.Loose);
  IBookService service = new BookService(bookRepositoryMock.Object);
  var book = new Book() {Id = 0}
  var author = new Author() {Id = 0};

  service.AssignAuthorToBook(book, author);

  bookRepositoryMock.Verify(repo => repo.AddNewBook(book));
  bookRepositoryMock.Verify(repo => repo.AddNewAuthor(author));
  bookRepositoryMock.Verfify(repo => repo.AssignAuthorToBook(book, author));
}

The id being set is something that you would use an integration test for, but I'd argue that you shouldn't worry about the EF failing to set the Id, I say this for the same reason you should not worry about testing if the .net framework does what it's supposed to do.
I've written about interaction testing in the past (which I think is the right way to go in this scenario, you are testing the interaction between the BookService and the Repository), hope it helps: http://blinkingcaret.wordpress.com/2012/11/20/interaction-testing-fakes-mocks-and-stubs/

A: I was having the same problem as you and came across your post.  What I found after was a in memory database called Effort.
Take a look at Effort
The following test works correctly
        EntityConnection conn = Effort.EntityConnectionFactory.CreateTransient("name=MyEntities");

        MyEntities ctx = new MyEntities(conn);

        JobStatus js = new JobStatus();
        js.JobStatusId = 1;
        js.Description= "New";

        ctx.JobStatuses.Add(js);

        Job j = new Job();
        j.JobId = 1;
        j.JobStatus = js;
        ctx.Jobs.Add(j);

        ctx.SaveChanges();

        Assert.AreEqual(j.JobStatusId, 1);

Where MyEntities is a DbContext created with a Effort connection string.
You still need to create you in memory objects, but, save changes on the context sets the objects associations as a database does.

A: That will never work the way you have it. The data context is wrapped up behind the scenes in your service layer, and the association of the BookID is never going to get updated on your local variable.
When I have done TDD on something using EF, I generally wrap up all my EF logic into some kind of DAO and have CRUD methods for the entities.
Then you could do something like this:
[Test]
public void AssignAuthorToBook_NewBookNewAuthor_SuccessfullyAssigned()
{
  IBookService service = new BookService();

  var book = new Book();
  var bookID = 122;
  book.ID = bookId;
  var Author = new Author() { Id = 123 };

  service.AssignAuthorToBook(book, author);

//ask the service for the book, which uses EF to get the book and populate the navigational properties, etc...
  book = service.GetBook(bookID)

  Assert.AreEqual(book.AuthorId, 123);
}

A: Your question is: if you mock database operation, you cannot test the correct function of AssignAuthorToBook because this class is high coupled to Entity Framework and the behaviour will change.
So my solution:
Decouple the classes (using a DAO, an interface with all database operations), now AssignAuthorToBook is easy to test because use functions of SetBook / GetBookId.
And do a test for your operations (SetBook / GetBookId) testing the database (ok, it's not a clear unittesting, but your question is exactly this: who can I test a database operation?, so... testing it, but in a separate test.

A: The general solution is to split it into layers.

*

*The persistence layer / repository pattern is in charge of writing out/reading in information from whatever store you choose. ORMs are supposed to be boxed inside the persistance layer. Above this layer, there should be no trace of the ORM. This layer returns entities/value objects as defined in the DDD book (I dont intend anything related to the EF)

*Next the service layer calls onto the Repository interface to obtain these POCO entities/value objects and is in charge of domain/business logic.

As for the testing,

*

*the basic purpose of the persistence layer is to persist the desired information.. e.g. write customer information to a file or DB. Hence integration testing this layer with the implementation specific tech (e.g. SQL) makes the most sense. If the tests pass but the layer isn't able to read/write to the actual SQL DB.. they are useless.

*The service layer tests can mock the persistence layer entry interface (e.g. Repository interface) and verify the domain logic without any dependency on the persistence tech - which is the way it should be. Unit tests here.

A: If you want to test that the "AssignAuthorToBook" works as expected then you can do it being completely DB ignorant - you a mock of the Book object and verify that the correct setter was called with correct value. Everything persistence related should be stubbed. To verify that a setter or a method was called you can use Moq or RhinoMocks.
An example can be found here: Rhino Mocks: AAA Synax: Assert property was set with a given type
Here is an example of how to verify alternative expectations: Using RhinoMocks, how can I assert that one of several methods was called?

A: I may be wrong, but as far as I know your domain model should be consistent even without a persistence layer.
So, in this case, your service, should ensure that the property AuthorID is equal to the Assigned Author class, even before persisting it to the database. Or your Book AuthorID property getter get that info from its inner Author class ID property assigned by the service.
public class Book {
    public Author Author { get; set; }
    public int AuthorId {
        get { return Author.ID; }
        set { Author.ID = value; }
    }
}

public class Author {
    public int Id { get; set; }
}

public class BookService {
    public void AssignAuthorToBook(Book book, Author author)
    {
        book.Author = author;
    }
}


text:
Q: SSRS multiple reports per PDF? I have a task that needs to create a 6-page SSRS report in PDF format.  Each page will have a different dataset and SQL query, and I need to include them in one report in separate pages with page numbers.
I have created the 6 separate reports, but I am not sure how to create one PDF with each report on its own page.

A: You could just create another report with all the reports compiled in it as SubReports, and enable "add a page break after" after each Subreport.
Adding the Page number is as simples as adding a text to your footer with Globals!TotalPages


text:
Q: How to dissolve polygons that overlap both on each other in QGIS? I have two layers of polygons with landcover classes(meadows, cropland, forest, ect) They overlap in both directions, i.e like a zipper. I need to dissolve them by one attribute (Class) so I can have the total area of each polygon... but in the overlapping sections sometimes the landcover classes don´t match.
If I try UNION, the algorithm creates new features for this overlapping regions, but also creates another AREA column and in some cases I have values for both columns simultaneously (I have now 2 AREA columns: one for each layer I "unioned").
I also tried the merge layers of the MMQGIS plugin, but the attributes are not summed up. And dissolving by class just creates an empty layer.
(The image is the union of the two layers. The arrows indicate which layer is overlapping over the other. Both images are corrected in terms of projection)
Does someone knows how to do something like this?
I work on QGIS 2.12.3 on a PC.

A: After hours of trial and error, I found a solution that I answered here: How to merge and dissolve adjacent polygons and sum up their attributes in QGIS?


text:
Q: IE Postbacks Fail After a Few Seconds When Connecting to ASP.Net 4.0 in Localhost I noticed an odd problem when developing a web site project on localhost using ASP.Net 4.0, IIS 7.0, and IE8.  Postbacks do not work after the page has been idle for a few seconds, like 30 seconds or less.  If I load the page, enter some data, and click the submit button immediately, the postback works perfectly, but if I let the page sit for not more than 30 seconds, the progress bar and the little preloader circle on the tab churn endlessly and the response never occurs.
I am unable (or don't know how) to use Wireshark in Windows to see what is actually happening on the network.
There is an exact copy of the web site on a remote server, and when connecting to that site, the problem does not occur.
Furthermore, when connecting to the site on localhost using Firefox, the problem does not occur.
Finally, when connecting to an ASP 2.0 web site on localhost using IE 8, there is no problem.  The page can sit for an hour and a postback will still work.
Anyone have any ideas?

A: Oh wow. I think I've finally found it. It seems to be AVG. I disabled AVG entirely, and the form post works. I re-enable it, and the form submit hangs / HTTP 504 timeout occurs.
I narrowed it down by disabling the email scanner for incoming messages - that seems to be the culprit (I have outgoing disabled anyway, so that might also be an issue).
I suspect Outlook's automatic send/receive (every 30 seconds or so) triggers the AVG email scanner, which for some reason prevents any subsequent form submissions from reaching the server, even though Fiddler shows it being posted correctly from the browser.
So glad I have found it! :)


text:
Q: Finding intersection topology errors in QGIS I would like to find the intersection topology errors in a line layer using QGIS 2.18. In the topology checker I found no intersection errors. I know GRASS v.clean and v.build commands can solve these errors. I found that the Merge selected features tool from advanced editing toolbar (as a side effect) breaks intersecting lines and then using Multipart to singleparts from vector menu gives back the original single line features, but this way the attributes are lost.

After selecting all lines and merge them the intersecting lines are broken.

I would like to find a the intersection errors without automatically breaking the lines using QGIS. I need something similar to Topology checker.

A: I found a solution to have a point layer showing the intersection of lines in a layer.

*

*make a copy of the original line layer

*make the copy layer editable and select all features and merge them using the advanced editing toolbar merge selected feature tool

*extract nodes from the merged layer using Vector/Geometry tools/Extract nodes from the menu

*extract nodes from the original line layer

*make a symmetric difference of the two node layers, only the intersections of the original line layer left in the result


text:
Q: C++: A misguided case of function overloading I wrote and  executed the following code in c++:
    int calc(int x=10,int y=100);int a,b,s,p,m;void main()
{clrscr();cout<<"enter the two numbers:";cin>>a>>b;s=calc(a,b);p=calc(a);`m=calc();cout<<"\n sum:"<<s;cout<<"\n product:"<<p;cout<<"\n subtraction:"<<m;getch();}
int calc(int a)
{int t;b=100;t=a*b;return t;}
int calc(int a,int b)
{int t;t=a+b;return t;}
int calc()
{int t;t=b-a;return t;}

I See that only one function is being called and is giving the correct output. For example: 3 and 4 will give 7, but from multiply it will be 101. I am  not very good with c++ concepts. An explanation would be useful.
Regards.

A: Point is
s=calc(a,b);
p=calc(a);
m=calc();

All match function
int calc(int a, int b)
  {
  int t;
  t=a+b;
 return t;
  }

Because it has defined default values, in case you don's specify input:
int calc(int x=10, int y=100);

It means that if you use
calc(1);

It will use
calc(1, 100);

BTW, this does not even compile on VisualStudio 2015, because with error:
error C2668: 'calc': ambiguous call to overloaded function

A: because you gave default values. When you call calc(a) with a=3, your prgramm actually runs calc(3,100)

A: Code is so strange at my first sight.
First of all, you should know global a = 3, b = 4 all the time.
both parameters are provided the first time call calc so the result is 7.
the second time, only one paramter provided, so a = 3, b = 100
and the last time no paramater, a = 10, b = 100.
int calc(int x = 10, int y = 100)
{
    int t;
    t = x + y;
    return t;
}

this may be easier to understand?


text:
Q: How to combine same result into one row after inner join in LINQ I'm new in ASP.NET and LINQ. I want to display book name, publisher name, and author name in index page. One book can have more than one author.
my query for display the result is like this
var query = BookAuthors.Join(Authors,
            bookAuthor => bookAuthor.AuthorId,
            author => author.Id,
            (bookAuthor, author) => new { bookAuthor = bookAuthor, AuthorName = author.Name })
                .Join(Books,
                ba => ba.bookAuthor.BookId,
                book => book.Id,
                (ba, book) => new { book = book, AuthorName = ba.AuthorName })
                    .Join(Publishers,
                    book => book.book.PublisherId,
                    publisher => publisher.Id,
                    (book, publisher) => new { BookId = book.book.Id , BookName = book.book.Name, AuthorName = book.AuthorName,  PublisherName = publisher.Name});

Then i create the viewModel for displaying the result, the viewModel code look like this
foreach (var obj in query)
        {

            viewModel.Add(new TestViewModel
            {
                BookId = obj.BookId,
                BookName = obj.BookName,
                AuthorName = obj.AuthorName,
                PublisherName = obj.PublisherName
            });
        }
        return View(viewModel);

using Join() method it works like Inner Join in SQL, the result of query is like this
| BookName | PublisherName | Author             |

| Book A   | Publisher B   | Author A           |

| Book B   | Publisher A   | Author A           |

| Book B   | Publisher A   | Author B           |

| Book C   | Publisher B   | Author C           |

But I expect the output of query to be like this
| BookName | PublisherName | Author             |

| Book A   | Publisher B   | Author A           |

| Book B   | Publisher A   | Author A, Author B |

| Book C   | Publisher B   | Author C           |

How to join the author value to the same row when it have the same value on book id? Is there any LINQ method to combining it?

A: You can group your query by book and publisher and use string.Join to concat the authors name
var result = query.GroupBy(x => new
    {
        x.BookName,
        x.PublisherName
    })
    .Select(x => new
    {
        x.Key.BookName,
        x.Key.PublisherName,
        AuthorName = string.Join(", ", x.Select(y => y.AuthorName))
    });


text:
Q: Changing wo-rds into words without dash I want to replace words at the end of the line separated with "-" like:
blah blah bl-
ah blah

into just:
blah blah
blah blah

Should I just find and replace "-" with ""? (This would replace wanted dashes as well.)
Edit for Hambone:
The strings are something like this:
"prior permis- sion of the publishers"

A: While you certainly can use VBA, you actually don't even need it for this.  Microsoft Word support regular expressions in the find/replace dialog.
To enable regex, just ensure the "Use WildCards" flag is turned on in the find/replace dialog.  From there, you can use Regex.  Here is an example of something that would replace a series of characters followed by a hyphen and another series of characters to the hyphen-less version:

If you are not familiar with Regex:

*

*( ) captures a match

*[ ] means "any of these"

*\1 = returns the first match (first group of parentheses)

If, for example, you wanted letters and numbers, it would look like this:
(a-zA-Z0-9)-(a-zA-Z0-9)

Also, if you really want VBA for this, you can either use the VBScript Regular Expression library, or you can record these steps as a macro and clean it up to suit your needs.


text:
Q: This fuctions get injectivity in the intervals of the form $(k-1,k)$ I want to prove that $f:\mathbb{R} \rightarrow \mathbb{S}^1$ $f(t) = (\cos(2\pi t), \sin(2\pi t$)) where $\mathbb{S}^1$ is the unit sphere, is a local homeomorphism. I know that $f$ is continuous and surjective in all $\mathbb{R}$. The problem is the injectivity, but for all $x \in \mathbb{R}$ exist a $k \in \mathbb{Z}$ such that $x \in (k-1,k)$ and $f$ restricted to this set is injective and then I get the local homeomorphism.
Is my logic correct?


text:
Q: Template argument deduction failed, trying with std::variant I have the following program similar with my problem. I need to get the specific class from a method like getClass and after that pass the object and call similar defined method. I can't use polymorphism.
#include <variant>
#include <optional>
#include <iostream>
using namespace std;

class A{
    public:
    void foo() const {
        std::cout << "A";
    }
};

class B{
    public:
    void foo() const {
        std::cout << "B";
    }
};

class C {
    public:
    void foo() const {
        std::cout << "C";
    }
};

using Object = std::variant<A,B,C>;

std::optional<Object> getClass(int nr)
{
    if (nr == 0)
        return A{};
    else if (nr == 1)
        return B{};
    else if(nr == 2)
        return C{};
    return std::nullopt;
}

void f(const Object& ob)
{
    //how to call foo function ???
}

int main()
{
    const auto& obj = getClass(2);

    if (obj.has_value())
        f(obj.value());
}

A: You can use std::visit
void f(const Object& ob)
{
    std::visit([](const auto& o){ o.foo();},ob);
}


text:
Q: Pretty simple AngularJS Unit Test in Karma seems to fail My karma.conf.coffee:
module.exports = (config) ->
  config.set
    basePath: '../'

    files: [
      'public/bower_components/lodash/dist/lodash.min.js'
      'public/bower_components/angular/angular.min.js'
      'public/bower_components/angular-mocks/angular-mocks.js'
      'public/bower_components/angular-route/angular-route.min.js'
      'public/bower_components/angular-strap/dist/angular-strap.min.js'
      'public/scripts/**/*.js'
      'test/unit/**/*.js'
    ]

    singleRun: true

    frameworks: ['jasmine']

    browsers: ['PhantomJS']

    plugins: [
      'karma-junit-reporter'
      'karma-jasmine'
      'karma-phantomjs-launcher'
    ]

    logLevel: config.LOG_INFO

I'm testing my HeaderController which is:
'use strict';

angularMoonApp.controller('HeaderController', ['$scope', '$rootScope', function ($scope, $rootScope) {
  $scope.init = function () {
    $rootScope.currentItem = 'home';
  }

  $scope.init();

}]);

My test/unit/controllers/header.spec.js is:
'use strict';

(function() {
  describe('HeaderController', function() {
    var $scope, $rootScope, createController;

    beforeEach(module('angularMoon'));

    beforeEach(inject(function($injector) {
      $rootScope = $injector.get('$rootScope');
      $scope = $rootScope.$new();

      var $controller = $injector.get('$controller');

      createController = function() {
        return $controller('HeaderController');
      };
    }));

    it("should set the current menu item to 'home'", function() {
      createController();
      $scope.init();

      expect($rootScope.currentItem).toBe('home');

    });

  });
})();

But when I executed $ karma start test/karma.conf.coffee, I get:
INFO [karma]: Karma v0.12.14 server started at http://localhost:9876/
INFO [launcher]: Starting browser PhantomJS
INFO [PhantomJS 1.9.7 (Mac OS X)]: Connected on socket nVTesgfm72ZGKPHrK027 with id 17114851
PhantomJS 1.9.7 (Mac OS X) HeaderController should set the current menu item to 'home' FAILED
    Error: [$injector:unpr] http://errors.angularjs.org/1.2.16/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope
        at /Users/mycomp/Sites/angular-introduction-website/public/bower_components/angular/angular.min.js:35
        at c (/Users/mycomp/Sites/angular-introduction-website/public/bower_components/angular/angular.min.js:34)
        at /Users/mycomp/Sites/angular-introduction-website/public/bower_components/angular/angular.min.js:36
        at c (/Users/mycomp/Sites/angular-introduction-website/public/bower_components/angular/angular.min.js:34)
        at d (/Users/mycomp/Sites/angular-introduction-website/public/bower_components/angular/angular.min.js:34)
        at /Users/mycomp/Sites/angular-introduction-website/public/bower_components/angular/angular.min.js:34
        at /Users/mycomp/Sites/angular-introduction-website/public/bower_components/angular/angular.min.js:66
        at /Users/mycomp/Sites/angular-introduction-website/test/unit/controllers/header.spec.js:16
        at /Users/mycomp/Sites/angular-introduction-website/test/unit/controllers/header.spec.js:21

So what am I doing wrong for such a simple test?

A: You forgot to pass $scope to your controller in $controller. Here's a working plunk.
createController = function() {
          // pass the objects you need injected in the controller.
          // including other services (if required)
        return $controller('HeaderController', {
            '$scope': $scope
        });
      };


text:
Q: Selenium - Java - ChromeDriver: Opens blank "data;" on some cases before opening another chrome window that runs actual test? So I'm an intern who was tasked with developing various test cases with Selenium. For the most part what I've developed works, however:
For some of my test cases a blank "data;" window opens up and then it'll open another window with my actual test case running. It doesn't really impede on my test case from functioning, but gets annoying from all the extra windows it's opening.
I've searched stackoverflow as well as other forums thoroughly and some people found solutions from updating the chromedriver (which I did and didn't work) and the questions others have posted here are in regards to their actual test case window being a blank data; instead of the issue I'm having.
Relevant Information:

*

*I'm using JUnit and in my @Before annotation I instantiate the chrome
driver object as I close the driver after every case (to be able to
run each case independently even if they're in the same test class).

This extra blank data; window seemed to only come up after I did the above point.

*

*I do a driver.get(URL) within each test case at the beginning

If someone has a solution can they please post and perhaps explain why it's behaving this way as I don't just want the solution, but want to understand the underlying cause behind it.
Thanks a bunch in advance!

A: Try verbose logging to at least see if it's the same instance of chromedriver opening up two windows.
System.setProperty("webdriver.chrome.verboseLogging", "true");

If it's separate chromedriver instances, you'll see, on Windows, in Task Manager two instances of chromedriver.exe, on Mac in Activity Monitor, two instances in chromedriver. Then you can narrow it down to maybe one of your test cases doesn't actually run, or immediately fails.

A: New blank "data" window opens when new ChromeDriver() is created. So if you see two windows, that means new ChromeDriver() was executed twice.
You might have left some driver = new ChromeDriver(); in the code somewhere, before you created your @Before method.
So when you are running your test, you have this code (driver = new ChromeDriver();) executed twice. Once in @Before method, and then again somewhere else in code.
Try using search in your IDE to find all occurrences of new ChromeDriver().
Or if not, maybe somehow your @Before method executes twice. New blank "data" window opens when new ChromeDriver() is created. So if you see two windows, that means new ChromeDriver() was executed twice.


text:
Q: CFG for $a^ib^jc^k : j <= i + k$ I am trying to figure out the CFG of a given language.
For $a^ib^jc^k :j = i + k$
I found a solution something like below.
$$\begin{align}
S_0 &\to aS_1bS_2
\mid S_1bS_2c
\mid\epsilon \\
S_1 &\to aS_1b
\mid\epsilon\\
S_2 &\to bS_2c \mid \epsilon \\
\end{align}
$$
But when the condition is $j \le i + k$ I cannot figure out how should I modify my CFG.

A: Here's a slightly simplified grammar for the equality condition:
$$\begin{align}
S&\to S_1 S_2\\
S_1&\to a S_1 b \mid \epsilon\\
S_2&\to b S_2 c \mid \epsilon
\end{align}
$$
In effect, this ensures that an $b$ is added whenever either an $a$ or a $c$ is added. For the condition $\le$ instead of $=$, we instead add at most one $b$ instead of exactly one time:
$$\begin{align}
S&\to S_1 S_2\\
S_1&\to a S_1 b \mid a S_1\mid\epsilon\\
S_2&\to b S_2 c \mid S_2 c\mid\epsilon
\end{align}
$$
Similarly, for the $\ge$ condition, we want to make sure that at least one $b$ is added:
$$\begin{align}
S&\to S_1 S_2\\
S_1&\to a S_1 b \mid S_1 b\mid\epsilon\\
S_2&\to b S_2 c \mid b S_2\mid\epsilon
\end{align}
$$
These patterns are quite useful if you're playing the "write me a CFG game". More importantly, they might provide some insight into how pushdown automata work (and why they're called pushdown automata), and even into how to think recursively.


text:
Q: Почему интерфейсы упрощают жизнь? Ранее никогда не писал собственные интерфейсы для "упрощения жизни". Почему? Что в них такого интересного?
В комментариях попросили добавить в вопрос мои знания и область работы. Пишу android приложения и... Все. Об интерфейсах не знаю ничего, только то, что можно класс от интерфейса наследовать и переопределить методы. Но зачем? Смысл интерфейсов?
Спасибо за замечательные ответы!

A: Потому что интерфейс - это абстракция, которая говорит о том, что делать, а не как делать.  "упрощение жизни" заключается в том, что интерфейс задает единообразное ожидаемое поведение, и где бы вы его не встретили (если конечно программист не наплевал на контракт интерфейса). Вообще, чтобы понять, что я тут написал, вам бы почитать книги по ООП.

A: Интерфейсы и в правду упрощают жизнь .Допустим в android для навигации gps Google api  использую интерфейс, для слушателя используют интерфейс (Интерфейсы используются почти везде даже в потоках )А начиная с Java-8 интерфейсы реализуют и тело, так что можно уже писать не только условие но и тело интерфейса .Но дело каждого  использовать их или нет .Не всегда программист обязан реализовывать свои интерфейсы.Правила "написание хорошего кода"  гласит:сперва составь интерфейсы абстракцию  потом реализуй))

A: Интерфейс предоставляет контракт, который должны выполнять все классы, реализующие этот интерфейс, и является абстракцией, показывающей что объект может делать, но как он этот делает - не важно.
На практике это приводит к следующему:
При использовании интерфейсов появляется возможность заменять один класс, реализующий интерфейс, на другой класс, реализующий этот же интерфейс, без переписывания всего кода. Например, если методу передаётся Map:
public void handle(Map map) { ... }

то не придётся менять описание метода, если потребуется использовать TreeMap вместо HashMap.
Аналогично если метод возвращает Map: он может начать возвращать TreeMap вместо HashMap, и трагедии библейских масштабов при этом не случится, так как код, работающий с возвращенным этим методом значением, имеет дело с Map.
Это увеличивает гибкость кода: проще переключаться с одного источника данных на другой и с одной реализации на другую.
Также это полезно при тестировании, так как позволяет использовать Mock-объекты вместо настоящих.

Если нужно одинаково обрабатывать коллекции элементов (например, ArrayList и Set, возвращаемый методом keySet() у HashMap), то достаточно описать метод так:
public <T> void handle(Collection<T> elements) { ... }

Использование generics-типа здесь для большей реалистичности. Без использования интерфейса пришлось создавать два метода:
public <T> void handle(ArrayList<T> elements) { ... }

public <T> void handle(Set<T> elements) { ... }

И либо дублировать код, либо, например, во втором методе создавать ArrayList, добавлять в него все элементы из Set и вызывать первый метод.

Также использование интерфейсов позволяет объединить разные объекты, реализующий один и тот же интерфейс, в один список и одинаково их обрабатывать:
public interface Animal
{
    public void feed();
}

public class Dog implements Animal
{
    public void feed() { ... }
}

public class Cat implements Animal
{
    public void feed() { ... }
}

List<Animal> animals = new ArrayList<>();
animals.add(new Cat());
animals.add(new Dog());
for (Animal animal : animals)
{
    animal.feed();
}

Без использования интерфейса пришлось бы городить "if-else" (или "switch-case") с отдельной реализацией логики для каждого типа животных.

A: Лично для меня самым наглядным для понимания сущности интерфейсов являются коллекции и все, что с ними связанно. Скорее всего это так, потому что с ними приходилось чаще всего работать.
Одна из главных особенностей ООП - избавление от дублирования логики, за счет правильной архитектурной составляющей. Для данного случая (в общем понимании) и были придуманы интерфейсы и абстрактные классы.
Допустим у меня есть сферический в вакууме метод, делающий какую-то работу с коллекцией:
/*Здесь может быть любой тип коллекции, который реализует соотв. интерфейс.
Причем я использую интерфейс самого "низкого" уровня, т.к.
он полностью покрывает данный функционал (т.е. проход по элементам в цикле)
Также я могу написать любую свою реализацию для этого интерфейса
*/
public void showCollectionAtConsole(Iterable<?> col){
   col.forEach(object -> System.out.println(object));
}

Удобство здесь в том, что только в самой Java довольно много реализаций данного интерфейса, (подробнее) и я могу использовать данную логику для каждой из них.
Теперь у меня есть другой метод, реализующий какой-то функционал:
public boolean removeOrAddMyObject (Collection<MyObject> col, MyObject object){
    //Если удалил объект - true, иначе - false
    boolean isRemove = true;

    if (col!=null){
        if (col.isEmpty() || !col.remove(object)) {
            col.add(object);
            isRemove = false;
        }
    }else throw new IllegalStateException("Коллекция = null");

    return isRemove;
}

Здесь мне приходится использовать три метода коллекции: isEmpty(), add(), remove(). Однако все эти методы описаны в интерфейсе Collection и нет нужды в качестве аргумента передавать более "высокий" интерфейс или класс с реализацией.
Как я уже писал выше, данное решение позволит мне с чистой совестью переиспользовать неоднократно данный метод для других реализаций.
Также, как мне кажется, отличным примером использования интерфейсов являются Callback'и:
public final class MyClass {

    static class MyObject {
        int id;
        String name;

        public MyObject(int id, String name) {
            this.id = id;
            this.name = name;
        }

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

        @Override
        public String toString(){
            return "My Object: id = "+id+", name = "+name;
        }
    }

    //Интерфейс коллбэка
    interface MyCallback<T extends MyObject> {
        void doSome(T myObject);
    }

    static void doSomeAwesome(MyObject object, MyCallback<MyObject> callback) {
        System.out.println(object);
        callback.doSome(object);
        System.out.println(object);
    }

    public static void main(String[] args) {

        MyObject myObject = new MyObject(1,"someName");

        MyCallback<MyObject> callback = new MyCallback<MyObject>() {
            @Override
            public void doSome(MyObject myObject) {
                myObject.setId(2);
                myObject.setName("someOtherName");
            }
        };

        doSomeAwesome(myObject,callback);
    }
}

Суть сводится к тому, что в интерфейсе коллбэка вы явным образом определяете дженерик (если хотите передавать в метод параметры и/или получать из метода объекты) и описываете контракт. В моем случае это один метод, принимающий на вход аргумент. Теперь, я могу реализовать метод коллбэка на свое усмотрение, и таким образом расширить использование метода doSomeAwesome() дополнительной логикой.
Если выполнить код на выходе будет:

My Object: id = 1, name = someName
My Object: id = 2, name = someOtherName

UPD: Также следует понимать, что есть и другие контексты для использования интерфейсов:

*

*контекст множественного наследования (в Java нельзя наследоваться от более 1 класса, но можно имплементировать более 1 интерфейса)

*интерфейс как прослойка между взаимодействующими сущностями. Т.е. есть два модуля в программе которые выполняют разные функции и при этом взаимодействуют друг с другом. В идеальной ситуации оба модуля должны представлять друг для друга "черный ящик" с необходимым минимумом методов, описываемых интерфейсами. Таким образом куда проще избежать сложностей при последующей отладке кода.

*контекст проектирования архитектуры приложения. Как правило, на начальном этапе проектирования архитектуры будущего приложения, очень удобно "прикидывать" взаимодействие между сущностями с помощью интерфейсов. Это как будто черновой вариант, который не требует "заморачиваться" с реализацией, и позволяет относительно безболезненно модифицировать архитектуру на ранних этапах.

*контекст тестирования. Как уже упоминали в одном из ответов, использование интерфейсов позволяет: "использовать Mock-объекты вместо настоящих". Поверьте, в перспективе это очень облегчает жизнь.


text:
Q: How to resize table cell TD using Jquery UI? As i have done some research to resize the table cell using jquery ui resize event that has been achieved but this sample had done with TD id. But when i add more TD element in the table it doesn't work. I know that this code is static, so  how to make dynamically ? Thanks in Advance
[Fiddle] https://jsfiddle.net/fekkyDev/xmf7L8gu/5/

      View 1

      View 2

      View 3

 $(window).on("load resize", function() {

  var windowWidth = $(window).width();
  var windowHeight = $(window).height();
  var v1Width = $("#v1").width()

  $("#v1").resizable({
    minWidth: 50,
    maxWidth: windowWidth - 80,
    maxHeight: windowHeight * (.83),
    handles: "e, s"
  }).on("resize", function() {

    if (v1Width == $("#v1").width()) {
      $("#v2").height(0)
    }
    v1Width = $("#v1").width()
  });

  $("#v2").resizable({
    maxHeight: windowHeight * (.83),
    handles: "s"
  }).on("resize", function() {
    $("#v1").height(0)
  });

});


text:
Q: How to make the SoftKeyboard scrollable in android? I am new to android development and am working to modify the SoftKeyboard sample, so that it is a scrollable keyboard. For instance, on the phone screen I can scroll the keyboard to get to special characters instead of pressing a mode change button. How do I make the view scrollable by modifying this sample?

A: For customizing the view use sliding drawer in order to slide the keyboard from bottom.
Put all the layout that you design for keyboard under a scroll view. so that people can slide to get the functions just below the typing characters.


text:
Q: BeagleBone Green Wireless(BBGW) can not boot form eMMC BeagleBone Green Wireless(BBGW) was booted from SD card successfully.
After that, I removed the SD card by my hand.
Reboot the system, then I can not login through SSH.
I observe the 4 LEDs. It seems the system booted from eMMC normally. Heartbeat LED works well.
Questions:
1 Why can't the BeagleBone Green Wireless(BBGW) boot from eMMC again?
2 Is there a method to recover the board to factory state?

A: reason found:
edit the file in eMMC: /etc/fstab
delete the line I added some days ago:
/dev/mmcblk0p1  /mnt   vfat defaults  0  0
/dev/mmcblk0p1 is actually the eMMC device, I thought it was the SD card.
reboot.It works well.


text:
Q: How to stop form submit during ajax call I can only modify the code in the ajax call.
The ajax call occurs when I click the submit in form named $('#form1').
$('#form1').submit(function () {
    $.ajax({
       url: 'some.php',
       type: 'POST',
       data: somedata,
       success: function (msg) {
          if (!msg) {
             // I wanna to stop '#form1' submit here,how to do that? I can only modify the code in the ajax call.
          }
       }
    });
 });

A: You can also use preventDefault()
http://api.jquery.com/event.preventDefault/

A: return false or event.preventDefault should help you:
$('#form1').submit(function(){
    $.ajax({
        url:'some.php',
        type:'POST',
        data:somedata,
        success:function(msg){
        if(!msg){
            //i wanna to stop form1 submit here,how to do that?  you can only modify the code in the ajax call
        }
    }
    });
    return false;
});

or:
$('#form1').submit(function(e){
    e.preventDefault();
    $.ajax({
        url:'some.php',
        type:'POST',
        data:somedata,
        success:function(msg){
        if(!msg){
            //i wanna to stop form1 submit here,how to do that?  you can only modify the code in the ajax call
        }
    }
    });
});

A: Put a
return false;

This should stop the function to continue

A: You'll need to stop it BEFORE the success handler.  Because the function finishes executing after your AJAX call the form will submit while your ajax call is occurring (and by the time your ajax call finishes it is too late).
But yes, put return false at the end of your function.
function SubmitHandler(){
  // Your AJAX call here
  // blah blah blah

  return false;  // Stop form submit
}

If it's really important that it is in the success handler, then you could execute the call synchronously.

A: You need to prevent form submitting
onclick="ajaxcall(); return false;"

And do it in your code:
 $.ajax({
  url:'some.php',
  type:'POST',
  data:somedata,
  success:function(msg){if(msg) $('#form1').submit();}
 })

A: You can change button type from "submit" to "button" then submit form using jquery form.submit(); function according to your conditions. Consider the following example code below:
<script>
 $(document).ready(function() {
$("#button-id").click(function() //on click at button
{

var sel=$("#input").val();

        $.post("ajax-war.php",{jid:sel,rand:Math.random() } ,function(data)
        {

          if(data=='valid') //if correct login detail
          {

$('#war_form').submit(); //Submit form
          }

          else
          {
              alert('not valid'); //will not submit form

          }
});
});
});

</script>

A: Assuming the form's ID is #form1, you could bind a submit handler and return false from it:
$.ajax({
  url:'some.php',
  type:'POST',
  data:somedata,
  success:function(msg){
    if(!msg){
     $('#form1').submit(function(){
       return false; // prevents form submit
     });
    }
  }
 })


text:
Q: $_SERVER['REMOTE_ADDR'] is not returning ip address I am using $_SERVER['REMOTE_ADDR'] in php to find client's ip address.
$ipaddress=$_SERVER['REMOTE_ADDR'];

echo $ipaddress;

which return ::1
I also tried the following code,but that gives me same result as well.
if ($_SERVER['HTTP_CLIENT_IP'])
    $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
else if($_SERVER['HTTP_X_FORWARDED_FOR'])
    $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if($_SERVER['HTTP_X_FORWARDED'])
    $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if($_SERVER['HTTP_FORWARDED_FOR'])
    $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if($_SERVER['HTTP_FORWARDED'])
    $ipaddress = $_SERVER['HTTP_FORWARDED'];
else if($_SERVER['REMOTE_ADDR'])
    $ipaddress = $_SERVER['REMOTE_ADDR'];
else
    $ipaddress = 'UNKNOWN';

What am I doing wrong?How can I get clients ip?
I would use the ip to find client's location via ipinfo.io.
Thanks for your time.

A: ::1 is the actual IP. It is an ipv6 address (i.e. localhost). If you were using ipv4 it would be 127.0.0.1.
If you want to get a different IP address, then you'll need to connect to the server through a different network interface.