text:
Q: How should I resolve my appspot backup failure? I'm trying to make a backup but it won't:
2011-10-01 09:22:43.706 /remote_api 302 5ms 0cpu_ms 0kb

213.89.134.0 - - [01/Oct/2011:05:22:43 -0700] "GET /remote_api HTTP/1.1" 302 0 - - "montaoproject.appspot.com" ms=6 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000032

$ python ./appcfg.py download_data --application=montaoproject --url=http://montaoproject.appspot.com/remote_api --filename=montao.data
Downloading data records.
[INFO    ] Logging to bulkloader-log-20111001.122234
[INFO    ] Throttling transfers:
[INFO    ] Bandwidth: 250000 bytes/second
[INFO    ] HTTP connections: 8/second
[INFO    ] Entities inserted/fetched/modified: 20/second
[INFO    ] Batch Size: 10
[INFO    ] Opening database: bulkloader-progress-20111001.122234.sql3
[INFO    ] Opening database: bulkloader-results-20111001.122234.sql3
[INFO    ] Connecting to montaoproject.appspot.com/remote_api
Please enter login credentials for montaoproject.appspot.com
Email: niklasro
Password for niklasro:
[INFO    ] Authentication Failed

app.yaml:
- url: /remote_api
  script: remote_api.py

remote_api.py:

from google.appengine.ext.remote_api import handler
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import re

MY_SECRET_KEY = 'thetopsecret'

cookie_re = re.compile('^"([^:]+):.*"$')

class ApiCallHandler(handler.ApiCallHandler):
    def CheckIsAdmin(self):
        login_cookie = self.request.cookies.get('dev_appserver_login', '')
        match = cookie_re.search(login_cookie)
        if (match and match.group(1) == MY_SECRET_KEY
            and 'X-appcfg-api-version' in self.request.headers):
            return True
        else:
            self.redirect('/_ah/login')
            return False

application = webapp.WSGIApplication([('.*', ApiCallHandler)])

def main():
    run_wsgi_app(application)

if __name__ == '__main__':
    main()

Update
The server status is 302 and the method in remote_api.pyis not reached:
2011-11-08 09:02:40.214 /remote_api?rtok=935015419683 302 12ms 0kb

213.89.134.0 - - [08/Nov/2011:03:02:40 -0800] "GET /remote_api?rtok=935015419683 HTTP/1.1" 302 0 - - "montaoproject.appspot.com" ms=13 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000026

A: When using this approach to get remote API to work with open ID (from http://blog.notdot.net/2010/06/Using-remote-api-with-OpenID-authentication), I think you need to specify the secret key (ie 'thetopsecret') as the email when prompted (and then just hit enter when prompted for the password).

A: Use correct credentials. niklasro is not your email address.

A: If your app is using the High-replication datastore then your App-ID will be 's~montaoproject' (and probably needs to be in quotes on the command line? It certainly won't hurt to do so...).

A: [INFO    ] Authentication Failed
It is nothing to do with GAE core , Authentication failed => either your login request failed or you are not providing the right credentials .
You are working behind proxy ? https is trouble behind squid proxy .

A: MY_SECRET_KEY corresponds with your login, not your password.  You shouldn't need to actually enter a password (just hit return).  So when you authenticate use:
Email: thetopsecret
Password for thetopsecret: (nothing)


text:
Q: Camel JPA query parameters not being seen I am currently having an issue getting Camel to see my JPA query parameters for the current code.  I have tested that the registry can access the parameters in my map, but my jpa endpoint in the pollenrich is saying it cannot locate my parameters.
Versions:
 JBoss Fuse: 6.2.1.redhat-084
 Camel: 6.2.1.redhat-084
 Hibernate: 4.2.20.Final-redhat-1
 Hibernate jpa 2.0 API: 1.0.1.Final

Camel Route:
    from("direct:routeUpdates").routeId("RouteUpdates")
        .log(LoggingLevel.DEBUG, "${body}")
        .beanRef("ParameterManager", "setupQueryParameters").id("DetermineNamedQueryParameters")
        .process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                Registry registry = exchange.getContext().getRegistry();
                Map<String, Object> map = registry.lookupByNameAndType("params", Map.class);
                System.out.println("driverId: " + map.get("driverId"));
                System.out.println("statusDate: " + map.get("statusDate"));
            }
        })
        .pollEnrich("jpa:" + RouteEntity.class.getName() + "?consumeDelete=false&delay=3000&consumeLockEntity=false&consumer.namedQuery=findRouteByDriverIdAndDate&consumer.parameters=#params", new RouteStatusAggregationStrategy()).id("EnrichWithPreviousRouteEntityData")
        .to("jpa:" + RouteEntity.class.getName() + "?usePersist=false&flushOnSend=true&joinTransaction=true").id("PersistRouteEntity");

Spring Context:

<bean id="PackageCarStatusRoute" class="com.ups.ops.cipe.internal.route.PackageCarStatusRoute">
</bean>

<bean id="ParameterManager" class="com.ups.ops.cipe.internal.parameter.RouteEntityNamedQueryParameterManager">
    <property name="params" ref="params" />
</bean>

<util:map id="params" key-type="java.lang.String">
    <entry key="driverId" value="0049124"/>
    <entry key="statusDate" value="Wed Apr 13 21:02:17 EDT 2016"/>
</util:map>

JPA Entity:
@Entity
@IdClass(RouteEntityId.class)
@Table(name = "RouteStatus")
@NamedQuery(name = "findRouteByDriverIdAndDate", query = "SELECT r FROM RouteEntity r WHERE r.driverId = :driverId AND r.statusDate = :statusDate")
public class RouteEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Column(name = "DriverId", updatable = false, nullable = false, length = 20)
    private String driverId;

    @Id
    @Temporal(TemporalType.DATE)
    @Column(name = "StatusDate", updatable = false, nullable = false)
    private Date statusDate;

    @Column(name = "DriverName", length = 5-)
    private String driverName;

    //removed setters getters and other variables for brevity
}

Log:
driverId: 0049124
statusDate: Wed Apr 13 21:02:17 EDT 2016
2016-04-13 17:02:22,057 [ity.RouteEntity] WARN  JpaConsumer                    - Consumer Consumer[jpa://com.ups.ops.cipe.external.route.entity.RouteEntity?consumeDelete=false&consumeLockEntity=falseconsumer.namedQuery%3DfindRouteByDriverIdAndDate&consumer.parameters=%23params&delay=3000] failed polling endpoint: Endpoint[jpa://com.ups.ops.cipe.external.route.entity.RouteEntity?consumeDelete=false&consumeLockEntity=falseconsumer.namedQuery%3DfindRouteByDriverIdAndDate&consumer.parameters=%23params&delay=3000]. Will try again at next poll. Caused by: [java.lang.IllegalArgumentException - org.hibernate.QueryParameterException: could not locate named parameter [driverId]]
java.lang.IllegalArgumentException: org.hibernate.QueryParameterException: could not locate named parameter [driverId]
    at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:377)
    at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:74)
    at org.apache.camel.component.jpa.JpaConsumer.configureParameters(JpaConsumer.java:488)
    at org.apache.camel.component.jpa.JpaConsumer$1.doInTransaction(JpaConsumer.java:101)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:131)
    at org.apache.camel.component.jpa.JpaConsumer.poll(JpaConsumer.java:92)
    at org.apache.camel.impl.ScheduledPollConsumer.doRun(ScheduledPollConsumer.java:174)
    at org.apache.camel.impl.ScheduledPollConsumer.run(ScheduledPollConsumer.java:101)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.QueryParameterException: could not locate named parameter [driverId]
    at org.hibernate.engine.query.spi.ParameterMetadata.getNamedParameterDescriptor(ParameterMetadata.java:100)
    at org.hibernate.engine.query.spi.ParameterMetadata.getNamedParameterExpectedType(ParameterMetadata.java:106)
    at org.hibernate.internal.AbstractQueryImpl.determineType(AbstractQueryImpl.java:466)
    at org.hibernate.internal.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:436)
    at org.hibernate.ejb.QueryImpl.setParameter(QueryImpl.java:371)
    ... 14 more

A: Ok figured it out.  The long story short is to make sure I don't mess up my spring schema location tag.  I had:
xmlns:util="http://www.springframework.org/schema/util"

I had forgotten to add this to schema location:
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd

The end spring header was looking like this for anyone with the same issue:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Doing basic math in Rails within each "each do" loop and getting the sum New to Rails! I have products which are associated to a campaign. Each @product has a .price and .orders_count associated to it.
What I wanted to do is multiply the .price with .orders_count for each @product, and add them all up to get a total cost for the @campaign.
Being new to Rails, wasn't sure how to do the write syntax and had the following in the view. This does the first piece, but does not add them all up at the end. Thanks for the help!
<% @products.each do |p| %>
    <% if p.orders_count? %>
        <%= (number_to_currency((p.price) * p.orders_count)) %>
    <% end %>
<% end %>

A: Try setting a variable to keep track of the sum of all products, and add the product to it each time through the loop. Try this:
<% sum = 0 %>
<% @products.each do |p| %>
    <% if p.orders_count? %>
        <% product = (number_to_currency((p.price) * p.orders_count)) %>
        <% sum += product %>
        <%= product %>
    <% end %>
<% end %>

The sum is: <%= sum %>


text:
Q: check the authority of performing an action through openshift rest api In openshift doc, we can check the ability of performing an action with a single command:
oc policy can-i <verb> <resource>

but how could i achieve this (To determine if you can perform specific verbs on specific resources) through its rest api

A: Use the service account name for what the applications will run as:
$ oc policy can-i --list --user system:serviceaccount:myproject:default
Verbs     Non-Resource URLs   Resource Names   API Groups   Resources

$ oc create serviceaccount jupyterhub
$ oc policy add-role-to-user edit -z jupyterhub

$ oc policy can-i --list --user system:serviceaccount:myproject:jupyterhub
Verbs                                                                      Non-Resource URLs   Resource Names   API Groups                Resources
[create delete deletecollection get impersonate list patch update watch]   []                  []               []                        [serviceaccounts]
[create delete deletecollection get list patch update watch]               []                  []               []                        [buildconfigs]
[create delete deletecollection get list patch update watch]               []                  []               []                        [buildconfigs/webhooks]
....

Applications will run as default normally. Here I created a new service account called jupyterhub and gave it edit role. I then queried what it could do. Replace myproject with name of your project and replace jupyterhub with name of your service account or default if you are changing what role it has.
This presumes you are wanting to use the REST API from an application.
For an application it is actually pretty easy, you either give it view, edit or admin role.

*

*admin: A project manager. The user will have rights to view any resource in the project and modify any resource in the project except for quota. A user with this role for a project will be able to delete the project.

*edit: A user that can modify most objects in a project, but does not have the power to view or modify roles or bindings. A user with this role can create and delete applications in the project.

*view: A user who cannot make any modifications, but can see most objects in a project.
Even if a normal user account and doing it from outside of the cluster, still not going to be much different in way you interpret it, just going to use the users account name instead. Although if doing it for yourself, wouldn't need --user option.

A: find a way, use this command:
oc policy can-i get pods --loglevel=8

then i can see the api being called by this cmd, which is:
POST https://openshift-cluster.example.com:8443/oapi/v1/subjectaccessreviews

A: In OpenShift since version 4:
oc auth can-i --list --as=myuser

# as a service account
oc auth can-i --list --as=system:serviceaccount:mynamespace:myserviceaccountname


text:
Q: Restoring node-modules and bower_components based on script contents How do I restore node-modules and bower_components?
I want to source control files which are actually part of my application and not the dependencies.
I want to restore those dependencies after I clone a fresh copy of my project.
Something like the inverse of bower wiredep

A: You can just set up a package.json for npm to install your node_modules using npm install. I believe bower also has something similar with bower.json.
I think both npm init and bower init should get you started.
Edit: yeah, Bower has it too


text:
Q: Is NHibernate SessionFactory thread safe According to documentation the SessionFactory should be thread safe:

An ISessionFactory is threadsafe, many threads can access it concurrently and request ISessions.

I'm looking at the implementation and I can't understand how e.g. OpenSession() can be thread safe:
http://nhibernate.svn.sourceforge.net/viewvc/nhibernate/trunk/nhibernate/src/NHibernate/Impl/SessionFactoryImpl.cs?revision=5233&view=markup
There are few lock() calls but nothing in OpenSession(). All the lock free thread safe implementations I was able to find were basically singletons.

A: OpenSession just returns a new object and passes in fields from the SessionFactoryImpl. Those fields seems to not be modified any place (bar the constructor) so this seems thread safe. The prerequisite is the settings.CacheProvider.NextTimestamp() and  sessionLocalInterceptor.SetSession(session); are also thread safe as these are potentioally altered in some of the overloaded OpenSession calls.
There's room for some race conditions atleast on  .Dispose/.Close though.


text:
Q: How to use ORDER BY in subqueries update dbo.Sheet1$ set F01 = 0 where ID in(
select top 3 ID from dbo.Sheet1$ where ID in(
select ID, ISNULL(F01,0) + ISNULL(F02,0) + ISNULL(F03,0) as RowSum
   from dbo.Sheet1$ where F01 = 1 AND F02 = 1 order by RowSum desc))

Running this code I get the error message:

Msg 1033, Level 15, State 1, Line 1 The ORDER BY clause is invalid in
  views, inline functions, derived tables, subqueries, and common table
  expressions, unless TOP, OFFSET or FOR XML is also specified.

can I write another query that exactly does the same like above query?

A: Your query has more issues than just ordering without sampling. For example, when you use a subquery inside the  IN () predicate, it cannot return more than 1 column, while your returns two.
Check this one, maybe I have guessed it correctly:
update dbo.Sheet1$ set F01 = 0
where ID in (
    select top 3 ID
    from dbo.Sheet1$
    where F01 = 1 AND F02 = 1
    order by ISNULL(F01,0) + ISNULL(F02,0) + ISNULL(F03,0) desc
);

A: 2 possible reasons for the errors are:
1) You subquery has condition IN which tries to look for 2 column in the subquery while you can have only 1 column while you query IN
2) Your subquery can not use Order By because whether you're going to sort or not, it'll look for matching records from the subquery result set and update the records. So there won't be any meaning of using Order By in your subquery. Whether you'll keep Order By or remove Order By in your subquery, it'll give you the same output.
Hope this helps!


text:
Q: How do I connect IntelliJ to GitHub using SSH I have successfully configured my GitHub client to use SSH, and received the confirmatory email from GitHub that a new SSH key was added. I would like to setup IntelliJ to use SSH as well, so that I don't have to enter my Username and Password every time I interact with GitHub. I also don't want IntelliJ to save my password for me, since I am unsure how secure that would be.
The closest I have come so far is that I need to edit my ~/.ssh/config file to tell IntelliJ that there is an SSH key it can use. Unfortunately I have not managed to find an example that works.
Here is my latest attempt at a ~/.ssh/config entry:
Host IntelliJ
  HostName github.com
  User git
  IdentityFile "/Users/peter/.ssh/github_rsa"
  TCPKeepAlive yes
  IdentitiesOnly yes

I have tried restarting IntelliJ after adding that entry, but to no avail.
I'm running IntelliJ Ultimate 12.1.6 on Mac OSX 10.8.5

A: Steve Byrne is right about the changes to this procedure.
As I do not have enough reputation to comment, I would like to add to his answer that I could only make this work with Github when inputing the SSH URL in the prompt for cloning a repo. You can get your repo's SSH URL by clicking on "Clone or Download" and then "Use SSH" on Github, like so:

A: *

*Open Git Bash and create a new ssh key using your GitHub email address like this:
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

*Then it asks you a file path for saving the key. You can simply accept the default by pressing Enter.

*You then will be asked for a passphrase. Make sure you remember it as you may need it at the time you want to push your project's changes to GitHub.

*Ensure your ssh agent is running. For that you can enter the following command
eval $(ssh-agent -s)

*Now add your SSH private key to the ssh-agent like this:
ssh-add ~/.ssh/id_rsa

*Now go to your GitHub profile and select setting->SSH and GPG keys. Select New SSH Key and after entering a title, copy your key using this command :
clip < ~/.ssh/id_rsa.pub

*Finally go to the Git setting of IntelijIDEA and select Built-in  for SSH executable.

*You can try to see if everything works fine by pushing your project to GitHub. You will be asked for the passphrase you entered when creating ssh key.

A: The answer above by kukido seems to now be out of date; the IntelliJ UI no longer provides the same level of access to the github URL.  And, the default "built-in" (to IntelliJ) ssh executable seems to not respect the .ssh/config file settings.  What I have found now works is to switch from using the built-in ssh executable to the "native" ssh executable.  This is done by visiting Settings... | Version Control | Gitand then choosing Native in the SSH executable pulldown menu.
This applies to IntelliJ version 2016.2 and I'm pretty sure earlier versions such as 2016.1 and the 2015 series.

A: GitHub plugin for IntelliJ lets you to save the password, so you don't have to enter it every time.

With keys
(adapted from Multiple SSH Keys settings for different github account, thanks to CrazyCoder comment):

*

*Create ssh key pair
$ ssh-keygen -t rsa -C "activehacker@youremail.com"

*Add key
$ ~/.ssh/id_rsa_activehacker

*Confirm that the key is added
$ ssh-add -l

*Modify ~/.ssh/config
Host github.com-activehacker
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_activehacker

In IntelliJ
VCS > Checkout from Version Control > Git

Test

As you can see, you will still have to either enter passphrase for the key pair after every IntelliJ relaunch(I believe the passphrase is kept in memory) or let IntelliJ to store it permanently.

A: Using IntelliJ 2016.3.3 this seems very straight forward by following the steps below:

*

*Generate your keypair to use, if none exists already with

ssh-keygen

*Add the key to your github profile as per https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/

*Modify the settings in IntelliJ under | VersionControl > GitHub

Tick 'Clone git repositories using ssh'

Choose 'Native' as 'SSH executable'

A: For those who are having issue on Mac M1 Chip with IntelliJ IDEA 2022.2.3, I have fixed as following:

*

*Go to Preferences

*Tools

*SSH Configurations

*Add a new configuration as shown in the screenshot:

If you pull your changes now in Intellij, Intelij will pull changes with ssh git


text:
Q: how to filter listView, when i don't store my data in an array I want to filter my listView for multiple data, but i don't actually store my data in an array.
it's pulled directly from a .csv file, like this:
public View getView(final int pos, View convertView, final ViewGroup parent){

    TextView mView = (TextView)convertView;

    if(null == mView){
        mView = new TextView(parent.getContext());
        mView.setTextSize(28);
    }

    mView.setText(getItem(pos).getItemName());

    return mView;
}

private void loadArrayFromFile(){
    try {

        InputStream is = ctx.getAssets().open("menustat.csv");
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String line;

        //Read each line
        while ((line = reader.readLine()) != null) {

            //Split to separate the name from the capital
            String[] RowData = line.split(",");

            //Create a State object for this row's data.
            mealList cur = new mealList();
            cur.setResturant(RowData[0]);
            cur.setFoodCategory(RowData[1]);
            cur.setItemName(RowData[2]);
            cur.setItemDescription(RowData[3]);
            cur.setServingsPerItem(RowData[4]);
            cur.setServingSize(RowData[5]);
            cur.setServingSizeUnit(RowData[6]);
            cur.setCalories(RowData[7]);
            cur.setFat(RowData[8]);
            cur.setSodium(RowData[9]);
            cur.setCarbs(RowData[10]);
            cur.setFiber(RowData[11]);
            cur.setProtein(RowData[12]);

            //Add the State object to the ArrayList (in this case we are the ArrayList).
            this.add(cur);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

For reference, this was what i tried doing: Android - How to filter a listview on multiple values?


text:
Q: Full-screen AlertDialog has janky animation when keyboard is shown Watch the video here to see the problem: https://streamable.com/s0yhrm
Or see it here on a faster device: https://streamable.com/4sshdn
I have an AlertDialog that I've set up to take all the vertical space. The problem is that when the keyboard appears, I get a nasty animation as the AlertDialog resizes to fit above the keyboard. Is there some way to prevent this from happening? Ideally, it should measure the available space above the keyboard before the AlertDialog ever displays.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/enter_address_alert_dialog_root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="4dp">

    <TextView
        android:id="@+id/title_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="6dp"
        android:paddingLeft="12dp"
        android:paddingTop="6dp"
        android:paddingBottom="4dp"
        android:text="Delivery address"
        android:textSize="14dp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/network_error_imageView"
        android:layout_alignParentRight="true"
        android:src="@drawable/cloud_off_36dp"
        app:tint="@color/colorError"
        android:visibility="gone"
        tools:visibility="visible"
        android:layout_alignTop="@id/title_textView"
        android:layout_alignBottom="@id/title_textView"
        android:layout_marginRight="12dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:id="@+id/top_LinearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_below="@id/title_textView"
        android:background="@drawable/autocomplete_list_item_background"
        android:elevation="2dp"
        android:paddingLeft="8dp"
        android:paddingTop="2dp"
        android:paddingRight="8dp"
        android:paddingBottom="12dp">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:gravity="bottom">

            <EditText
                android:id="@+id/address_editText"
                style="@style/MyEditTextStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Street address"
                android:imeOptions="actionNext"
                android:maxLength="100"
                android:maxLines="4"
                android:importantForAutofill="no"
                android:paddingLeft="4dp"
                android:paddingTop="8dp"
                android:paddingRight="32dp"
                android:selectAllOnFocus="true"
                android:textSize="@dimen/address_alert_dialog_text_size" />

            <ImageButton
                android:id="@+id/clear_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:paddingTop="4dp"
                android:paddingLeft="4dp"
                android:paddingRight="4dp"
                android:paddingBottom="0dp"
                android:background="?selectableItemBackgroundBorderless"
                android:src="@drawable/ic_close_24dp" />

        </RelativeLayout>

        <EditText
            android:id="@+id/enter_address_unit_number_alert_dialog_edit_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginLeft="16dp"
            android:layout_weight="0.8"
            android:gravity="center"
            android:imeOptions="actionDone"
            android:hint="Unit #"
            android:importantForAutofill="no"
            android:inputType="textPostalAddress|textCapWords|text"
            android:maxLength="30"
            android:paddingTop="6dp"
            android:selectAllOnFocus="true"
            android:textSize="@dimen/address_alert_dialog_text_size" />

    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/map_button"
        android:layout_below="@id/top_LinearLayout">

        <!--Single parent to ScrollView-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/no_store_address_enter_address_alert_dialog_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="@dimen/address_autocomplete_margin_above_empty_view"
                android:layout_marginRight="18dp"
                android:textSize="@dimen/address_alert_dialog_no_store_address_text_size"
                android:text="You haven't entered a store address. Without this, the app can't locate delivery addresses or calculate driving distances. To fix this, go to Settings and use the 'Store addresses' option."
                android:textColor="#F00"
                android:visibility="gone" />

            <TextView
                android:id="@+id/enter_address_alert_dialog_empty_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="@dimen/address_autocomplete_margin_above_empty_view"
                android:layout_marginRight="18dp"
                android:drawablePadding="6dp"
                android:gravity="center_horizontal"
                android:padding="12dp"
                android:text="Start typing an address above and matching results will show up here"
                android:textSize="@dimen/address_alert_dialog_text_size"
                app:drawableTint="@color/colorAutocompleteEmptyViewIcon"
                app:drawableTopCompat="@drawable/ic_search_white_28dp" />

        </LinearLayout>

    </ScrollView>

    <ListView
        android:id="@+id/enter_address_alert_dialog_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/map_button"
        android:layout_below="@id/scrollView"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="4dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="4dp"
        android:divider="@android:color/transparent"
        android:dividerHeight="-3dp" />

    <TextView
        android:id="@+id/map_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="16dp"
        android:background="@drawable/toolbar_image_button_ripple"
        android:fontFamily="sans-serif-medium"
        android:padding="8dp"
        android:text="MAP"
        android:textColor="@color/colorAlertDialogButton"
        android:textSize="@dimen/alert_dialog_button_text_size" />

    <TextView
        android:id="@+id/cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="15dp"
        android:layout_toLeftOf="@id/submit_button"
        android:background="@drawable/toolbar_image_button_ripple"
        android:fontFamily="sans-serif-medium"
        android:padding="8dp"
        android:text="CANCEL"
        android:textColor="@color/colorAlertDialogButton"
        android:textSize="@dimen/alert_dialog_button_text_size" />

    <TextView
        android:id="@+id/submit_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="20dp"
        android:background="@drawable/toolbar_image_button_ripple"
        android:fontFamily="sans-serif-medium"
        android:padding="8dp"
        android:text="SUBMIT"
        android:textColor="@color/colorAlertDialogButton"
        android:textSize="@dimen/alert_dialog_button_text_size" />

</RelativeLayout>

A: there is no "default" workaround for your problem. your Dialog appears at first, then EditText is drawn, it requests focus and then keyboard shows - Dialog is already drawn (full screen), so it shrinks
maybe you can try to force show keyboard BEFORE Dialog appears
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).
    toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

then show your Dialog (maybe with some few milisec delay?) and call editText.requestFocus() for "connecting" keyboard to freshly shown EditText (there is a change is will be done automatically, as EditText may request focus when inflated)

A: I was able to solve this in a satisfactory manner by expanding the AlertDialog's height only once the user starts typing. See video here: https://streamable.com/oj3fbv
       addressEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String inputText = s.toString().toLowerCase().trim();

                if (inputText.length() > 0) {
                    if (inputText.length() == 1) {
                    autocompleteListView.setVisibility(View.VISIBLE);

                        RelativeLayout.LayoutParams listViewParams = new RelativeLayout.LayoutParams(
                                RelativeLayout.LayoutParams.MATCH_PARENT,
                                RelativeLayout.LayoutParams.MATCH_PARENT);
                        listViewParams.addRule(RelativeLayout.BELOW, topLinearLayout.getId());
                        listViewParams.addRule(RelativeLayout.ABOVE, mapButton.getId());
                        listViewParams.leftMargin = dpToPx(8);
                        listViewParams.rightMargin = dpToPx(8);
                        listViewParams.topMargin = dpToPx(4);
                        listViewParams.bottomMargin = dpToPx(4);
                        autocompleteListView.setLayoutParams(listViewParams);

                        RelativeLayout.LayoutParams mapButtonParams = new RelativeLayout.LayoutParams(
                                RelativeLayout.LayoutParams.MATCH_PARENT,
                                RelativeLayout.LayoutParams.WRAP_CONTENT);
                        mapButtonParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                        mapButton.setLayoutParams(mapButtonParams);
                    }

                    clearButton.setVisibility(View.VISIBLE);

                    if (inputText.length() > 1 && storeAddressEntered) {
                        alertDialogEmptyView.setVisibility(View.GONE);
                        scrollView.setVisibility(View.GONE);
                    }
                }
                alertDialogAdapter.getFilter().filter(inputText);
            }
        });

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/enter_address_alert_dialog_root_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dp">

    <TextView
        android:id="@+id/title_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="6dp"
        android:paddingLeft="12dp"
        android:paddingTop="6dp"
        android:paddingBottom="4dp"
        android:text="Delivery address"
        android:textSize="14dp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/network_error_imageView"
        android:layout_alignParentRight="true"
        android:src="@drawable/cloud_off_36dp"
        app:tint="@color/colorError"
        android:visibility="gone"
        tools:visibility="visible"
        android:layout_alignTop="@id/title_textView"
        android:layout_alignBottom="@id/title_textView"
        android:layout_marginRight="12dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:id="@+id/top_LinearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_below="@id/title_textView"
        android:background="@drawable/autocomplete_list_item_background"
        android:elevation="2dp"
        android:paddingLeft="8dp"
        android:paddingTop="2dp"
        android:paddingRight="8dp"
        android:paddingBottom="12dp">

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:gravity="bottom">

            <EditText
                android:id="@+id/address_editText"
                style="@style/MyEditTextStyle"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Street address"
                android:imeOptions="actionNext"
                android:maxLength="100"
                android:maxLines="4"
                android:importantForAutofill="no"
                android:paddingLeft="4dp"
                android:paddingTop="8dp"
                android:paddingRight="32dp"
                android:selectAllOnFocus="true"
                android:textSize="@dimen/address_alert_dialog_text_size" />

            <ImageButton
                android:id="@+id/clear_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:paddingTop="4dp"
                android:paddingLeft="4dp"
                android:paddingRight="4dp"
                android:paddingBottom="0dp"
                android:background="?selectableItemBackgroundBorderless"
                android:src="@drawable/ic_close_24dp" />

        </RelativeLayout>

        <EditText
            android:id="@+id/enter_address_unit_number_alert_dialog_edit_text"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:layout_marginLeft="16dp"
            android:layout_weight="0.8"
            android:gravity="center"
            android:imeOptions="actionDone"
            android:hint="Unit #"
            android:importantForAutofill="no"
            android:inputType="textPostalAddress|textCapWords|text"
            android:maxLength="30"
            android:paddingTop="6dp"
            android:selectAllOnFocus="true"
            android:textSize="@dimen/address_alert_dialog_text_size" />

    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/top_LinearLayout">

        <!--Single parent to ScrollView-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/no_store_address_enter_address_alert_dialog_text_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="18dp"
                android:layout_marginTop="@dimen/address_autocomplete_margin_above_empty_view"
                android:layout_marginRight="18dp"
                android:textSize="@dimen/address_alert_dialog_no_store_address_text_size"
                android:text="You haven't entered a store address. Without this, the app can't locate delivery addresses or calculate driving distances. To fix this, go to Settings and use the 'Store addresses' option."
                android:textColor="#F00"
                android:visibility="gone" />

            <TextView
                android:id="@+id/enter_address_alert_dialog_empty_view"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="18dp"
                android:layout_marginRight="18dp"
                android:drawablePadding="6dp"
                android:gravity="center_horizontal"
                android:padding="12dp"
                android:text="Start typing an address above and matching results will show up here"
                android:textSize="@dimen/address_alert_dialog_text_size"
                app:drawableTint="@color/colorAutocompleteEmptyViewIcon"
                app:drawableTopCompat="@drawable/ic_search_white_28dp" />

        </LinearLayout>

    </ScrollView>

    <ListView
        android:id="@+id/enter_address_alert_dialog_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/scrollView"
        android:visibility="gone"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="4dp"
        android:layout_marginRight="8dp"
        android:layout_marginBottom="4dp"
        android:divider="@android:color/transparent"
        android:dividerHeight="-3dp" />

    <TextView
        android:id="@+id/map_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/scrollView"
        android:layout_marginLeft="16dp"
        android:background="@drawable/toolbar_image_button_ripple"
        android:fontFamily="sans-serif-medium"
        android:padding="8dp"
        android:text="MAP"
        android:textColor="@color/colorAlertDialogButton"
        android:textSize="@dimen/alert_dialog_button_text_size" />

    <TextView
        android:id="@+id/cancel_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/map_button"
        android:layout_marginRight="15dp"
        android:layout_toLeftOf="@id/submit_button"
        android:background="@drawable/toolbar_image_button_ripple"
        android:fontFamily="sans-serif-medium"
        android:padding="8dp"
        android:text="CANCEL"
        android:textColor="@color/colorAlertDialogButton"
        android:textSize="@dimen/alert_dialog_button_text_size" />

    <TextView
        android:id="@+id/submit_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignBottom="@id/map_button"
        android:layout_marginRight="20dp"
        android:background="@drawable/toolbar_image_button_ripple"
        android:fontFamily="sans-serif-medium"
        android:padding="8dp"
        android:text="SUBMIT"
        android:textColor="@color/colorAlertDialogButton"
        android:textSize="@dimen/alert_dialog_button_text_size" />

</RelativeLayout>


text:
Q: maple: simplify a*f(x)=0 assuming a>0 I would like to simplify the expression a*f(x)=0, where a>0, using Maple.
I expect Maple to give me f(x)=0, but fail.
In maple, I type
(simplify(f(x)*a = 0) assuming (0 < a));
But it gives:
f(x) a = 0
Thanks!


text:
Q: Head revision not working as intended for Google Docs formats For "native" Google documents (maybe it applies to all Google formats, I haven't checked), using head in the revisions.get method returns the first revision instead of the latest one. It seems that it only relies on the order of the revisions returned by the revisions.list method, and that order is not really uniform (e.g. a Google document lists the latest first).

A: This looks like a bug, I managed to reproduce it. I reported it to the engineers and I'll update this answer as soon I hear back from them.
UPDATE 12/2: this is now fixed and the fix will be live in 1-2 weeks


text:
Q: Is it possible to let a user input any number of words one per line using the input function? I was wondering is it possible to let a user enter any number of words one per line using the input function. So for example, let's say I have the following prompt:
Enter any number of words, one per line, or a blank line to stop:
and the output is something like this:
hello
my
name
is
dave

What would the code for this look like?

A: simply :
while True:
    x = input()
    if x == '':
        break


text:
Q: Akka.NET actor system in ASP.NET I created a service with a RESTful API in ASP.NET, hosted in IIS. Inside this service, I would like to create an actor system with Akka.NET.
Upon creating the actor system:
var actorSystem = ActorSystem.Create("myActorSystem");

The following exception is thrown:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.dll
  Additional information: An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked <%@ Page Async="true" %>. This exception may also indicate an attempt to call an "async void" method, which is generally unsupported within ASP.NET request processing. Instead, the asynchronous method should return a Task, and the caller should await it.

The actor system is inherently a concurrent system with asynchronous messages being exchanged between actors. As explained here, this actor system would not survive IIS taking down the AppDomain, which is probably why the aforementioned exception is thrown.
This article explains how to run background tasks in ASP.NET. However, I don't see how I could use this for my actor system, as I have no control over the lifecycle of background tasks that might be created by Akka.NET.
Is there a way to make this work, or should I abandon the idea of having an actor system in an ASP.NET application?
EDIT: I also saw a question on Stackoverflow about implementing a REST service using Akka. Any advice about a solution similar to the Spray toolkit, but working for Akka.NET would be welcome.

A: I've used Akka.NET and Akka.Remote inside ASP.NET MVC applications that are doing up to 1000 requests per second on EC2 - so I'll share some of the tips and tricks I used to get it up and running successfully. Had a prototype version that even used Akka.Cluster but ended up not shipping that version.

*

*Best place to call ActorSystem.Create is inside Global.asax Application_Start().

*Hang onto a static reference to the ActorSystem object inside Global.asax itself, using a static field or property. Helps ensure that the ActorSystem itself doesn't get garbage-collected in long-running applications.

*Create a separate static helper class to initialize any top-level actors your applications needs - i.e. actors at the top of the /user/ hierarchy. This class should also provide actor paths that your ASP.MVC controllers and action methods can use for Tell and Ask operations.

Creating the ActorSystem is a bit of an expensive operation, because lots of system-level stuff gets fired up at once. It's definitely best to do this once at application startup and then just cache the result inside the Application class.
Creating individual actor instances is cheap - you should be able to do this no-problem inside ASP.NET MVC action methods. If you see this error come up again, please let us know what part in the request-handling process this error occurred and with which version of ASP.NET.
Edit: added some updated guidance for how to do this on ASP.NET Core
https://petabridge.com/blog/akkadotnet-aspnetcore/

A: Keep your ActorSystem as a shared property in some static class container - this way you may access it from the rest of your application. Actor system initialization/disposal can be done by:

*

*Global.asax - use ActorSystem.Create(...) inside Global.asax Application_Start and dispose it with system.Shutdown() on Application_End.

*OWIN - create actor system in OWIN's Startup.Configuration method and shut it down by binding to host.OnAppDisposing event (how-to link).

Remember that IIS will startup your web app only after first request and tear it down automatically after some time when it's idle. Therefore make sure, that your deployment script will ping application after publishing and set idle timeout (link) for long enough if you want your Akka actor system to run continuously.
Second option
Separate your Actor System logic and deploy it, for example, as a Windows Service (or Linux deamon). Turn on Akka.Remoting for it and create a proxy client, which will forward all application long-running sensitive tasks to external service. Similar solution is often used for things such as schedulers or event buses, when your application logic must be working continuously.


text:
Q: Can't Create Receive Connector So I'm trying to copy a single receive connector from one server to another. I store the receive connector in a variable like so:
$NKCRC = Get-ReceiveConnector "<Source Resource Connector>" | Select *

Then I try to create the new one with the command below:
New-ReceiveConnector -Server $targetServer -Bindings $NKCRC.Bindings -RemoteIPRanges $NKCRC.RemoteIPRanges -Name $NKCRC.Name -TransportRole FrontEndTransport

The source RC is an Exchange 2010 RC and I'm creating it on an Exchange 2016 server. When I run the command, I get the following error:
The values that you specified for the Bindings and RemoteIPRanges parameters
conflict with the settings on Receive connector "<Identity of receive connector on the
target server>" SMTP Relay". A Receive connector must have a unique combination of a local
IP address & port bindings and remote IP address ranges. Change at least one of these
values.

I checked the mentioned RC and found they don't have the exact same settings for ANYTHING AT ALL, Bindings or RemoteIPRanges. I'm kinda at a loss. The bindings and RemoteIPRanges for each RC is below:

Source RC Bindings: {0.0.0.0:25}
Count of Source RC RemoteIPRanges: 60 (Rather than post them all, lol)

RC that the Exchange thinks is a duplicate
Bindings: {0.0.0.0:25, 10.200.154.79:25}
Count of Source RC RemoteIPRanges: 50
So obviously they aren't duplicates, right? What am I missing?


text:
Q: OnCreate expected semicolon in Android studio     public class MainActivity extends AppCompatActivity {
        private TaskDBHelper helper;
        private ListAdapter listAdapter;
        @Override
        public void onCreate(Bundle savedInstanceState) {

            private void updateUI(){
                helper = new TaskDBHelper(MainActivity.this);
                SQLiteDatabase sqlDB = helper.getReadableDatabase();
                Cursor cursor = sqlDB.query(TaskContract.TABLE,
                        new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
                        null, null, null, null, null);

                listAdapter = new SimpleCursorAdapter(
                        this,
                        R.layout.task_view,
                        cursor,
                        new String[]{TaskContract.Columns.TASK},
                        new int[]{R.id.taskTextView},
                        0
                );
                ListView listView = (ListView) findViewById(R.id.list);
                listView.setAdapter(listAdapter);
            }
        }
}

I keep getting a red mark on private void updateUI() where an error message that displays express expected (semicolon).

A: Try this:
 public class MainActivity extends AppCompatActivity {
        private TaskDBHelper helper;
        private ListAdapter listAdapter;
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                updateUI();
                ListView listView = (ListView) findViewById(R.id.list);
                listView.setAdapter(listAdapter);
            }

            private void updateUI(){
                helper = new TaskDBHelper(MainActivity.this);
                SQLiteDatabase sqlDB = helper.getReadableDatabase();
                Cursor cursor = sqlDB.query(TaskContract.TABLE,
                        new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
                        null, null, null, null, null);

                listAdapter = new SimpleCursorAdapter(
                        this,
                        R.layout.task_view,
                        cursor,
                        new String[]{TaskContract.Columns.TASK},
                        new int[]{R.id.taskTextView},
                        0
                );
        }
}

A: In Java you can't declare a method inside scope of another method. You can only declare methods inside scope of a class. So your way of declaring the method updateUI() is invalid and should be moved to the class scope.


text:
Q: Control submenus width in css dropdown menu I'm posting here to get some help.
I'm trying to make a simple dropdown menu and I'm stacked with the submenus (limpieza and balance).
What i'm trying to achieve here is to make the limpieza and balance buttons have the same width and text align as the rest of the buttons. I just dont know how. It looks like once the relative attribute is added to the container and the absolute attribute is added to limpieza and balance, I can't control their width or text align anymore. I guess is bc they are out of its cointainer. I'm really confused here since this is the first time I try css.
I would appreciate if some1 could provide some help.
Here is the code.

@charset "utf-8";
/* CSS Document */
*{
    margin: 0px;
    padding: 0px;
}

body {
 font-family: Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", serif;
 }

/*ESTILOS GENERALES*/

.header {
    left: 0;
    position: fixed;
    top: 0;
    width: 100%;
    background:white;
    }

.barrasup {
 background:#203c6e;
 padding-top: 10px;
 padding-bottom: 10px;
 min-height: 29px;
    z-index: 2;
}

.contenedor {
 margin: 0 auto;
 max-width: 1200px;
  }

.social {
 background: #203c6e;
 display: block;
 float: none;
 margin-bottom: 5px;
 margin-left: auto;
 margin-right: auto;
 width: 75px;
}

.instasocsup {
 margin-right: 10px
}

/*MENU*/

.barrainf {
    margin-top: 10px;
}

.menu {
    width: 1180px;
    margin-left: auto;
    margin-right: auto;
}

.menu ul {
 list-style:none;
 padding: 0;
}

.menu li {
    line-height: 2.5rem;
    position: relative;

 }

.menu li .item2 ul {
     position: absolute;
 }

.menu > ul > li > div > a {
    text-decoration:none;
    color: black;
    display: block;
}

.menu > ul > li > div > a:hover {
    color: white;
    background: #203c6e;
}

.menu > ul > li > div > a {
    text-decoration:none;
    color: black;
    display: block;
}

.menu > ul > li > div > a:hover {
    color: white;
    background: #203c6e;
}

.menu > ul > li > div > ul > li >div > a {
    text-decoration:none;
    color: white;
    display: block;
}

.menu li ul {
    display: none;
}

.menu li:hover ul {
    display:block;
}

.item1 {
    margin-left: 10px;
    margin-right: 10px;
    background: white;
}

.item2, .item3, .item4, .item5  {
    margin-left: 0px;
    margin-right: 10px;
    background:white;
}

.subitem1, .subitem2 {
    margin-left: 0px;
    background: #203C6E;
    color: white;
}

/*1ER NIVEL*/

.menu > ul{
    background: #DF2529;
    display: table;
    width:100%;
    }

.menu > ul > li {
    float: left;
    width: 20%;
    text-align: center;
    }

<!doctype html>

<meta charset="utf-8">
<title>Documento sin título</title>
<link href="css/styleIndigo.css" type="text/css" rel="stylesheet">

Inicio

Comprar

Balance

Limpieza

Blog

Quienes somos

Contacto

A: Just use calculate css for width that works with inherited table display properties. View it here http://codepen.io/anon/pen/reMpRj
.menu > ul > li > div > ul {
  width: calc(100% - 10px);
}


text:
Q: Spring security custom login redirection conflict I have created a custom login form using spring security some point of time it working as perfect but some times after login URL is redirecting to css or images or js folders. After i  hit refresh it working fine, i dont know what is wrong with my spring security.
Custom login page
<form:form class="form-vertical login-form"   action="j_spring_security_check" method="post">

Login to your account

        <input  type="text" autocomplete="off" placeholder="Username" name="j_username"/>
        <input  type="password" autocomplete="off" placeholder="Password" name="j_password"/>

           ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

    </form:form>

Security context xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                    http://www.springframework.org/schema/security
                    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

     <http pattern="/" security="none"/>
    <http use-expressions="true">
        <intercept-url pattern="/**" access="isAuthenticated()"/>

        <form-login login-page="/" login-processing-url="/j_spring_security_check"  default-target-url="/home" authentication-failure-url="/"/>
        <logout logout-url="/logout" logout-success-url="/"/>
    </http>

    <authentication-manager>
        <authentication-provider>

            <user-service>
                <user name="admin" password="admin" authorities="Admin, User"/>
                <user name="user" password="user" authorities="User"/>
            </user-service>
        </authentication-provider>
    </authentication-manager>

</beans:beans>

Login Controller
@RequestMapping("/")
public String loginForm()
{
    return "login";
}

Web xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>YESKAY</display-name>

  <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-servlet.xml
            /WEB-INF/security-context.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

Successful login url
http://localhost:8080/PROJECT/home

Some times redirect to below url or something else
http://localhost:8080/PROJECT/resources/assets/plugins/font-awesome/font/fontawesome-webfont.ttf?v=3.2.0

My folder Structure

A: You need to omit requests for your static resources path from Spring Security's filters, otherwise it can get confused about what the actual request was that triggered a login (since the browser will also send requests for the page resources such as images).
Adding something like
<http pattern="/resources/**" security="none"/>

to the top of your configuration should do it.


text:
Q: Can pkg_resources find a resource located under the dist-info dir created when extrtacting a whl? My setup is dependant on packages downloaded as whl's and extracted and their resources thus reside in the ".dist-info" dir as specified in
I am failing in finding those files using pkg_resources.resource_filename
Here's a zsh + ipython output that demonstrates it:
➜  jupyter-adapter git:(develop) ✗ find eggs/jupyterhub-0.8.1-py3-none-any.ovo/ -name 'error.html'
eggs/jupyterhub-0.8.1-py3-none-any.ovo//jupyterhub-0.8.1.dist-info/data/share/jupyter/hub/templates/error.html
➜  jupyter-adapter git:(develop) ✗ bin/ipython
Python 3.5.1 (default, Jan 15 2017, 17:45:49)
Type "copyright", "credits" or "license" for more information.

IPython 5.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import sys

In [2]: [x for x in sys.path if 'jupyterhub' in x]
Out[2]: ['/Users/oded/work/jupyter-adapter/eggs/jupyterhub-0.8.1-py3-none-any.ovo']

In [3]: import pkg_resources

In [6]: pkg_resources.resource_filename('jupyterhub', 'jupyter/hub/templates/error.html')
Out[6]: '/Users/oded/work/jupyter-adapter/eggs/jupyterhub-0.8.1-py3-none-any.ovo/jupyterhub/jupyter/hub/templates/error.html'

In [7]: open(_)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-7-724e07d998de> in <module>()
----> 1 open(_)

FileNotFoundError: [Errno 2] No such file or directory: '/Users/oded/work/jupyter-adapter/eggs/jupyterhub-0.8.1-py3-none-any.ovo/jupyterhub/jupyter/hub/templates/error.html'

Setup 2 (virtual env):
(jupyter-adapter) root@public-notebook (Ubuntu 14.04) ➜  jupyter-adapter find /root/jupyter-adapter/share/ | grep 'error.html'                                                                                17-12-27 08:40
/root/jupyter-adapter/share/jupyter/hub/templates/error.html
(jupyter-adapter) root@public-notebook (Ubuntu 14.04) ➜  jupyter-adapter ipython                                                                                17-12-27 08:41
Python 3.5.2 (default, Jul 17 2016, 00:00:00)
Type "copyright", "credits" or "license" for more information.

IPython 5.4.1 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import pkg_resources

In [2]: pkg_resources.resource_filename('jupyterhub', 'jupyter/hub/templates/error.html')
Out[2]: '/root/jupyter-adapter/lib/python3.5/site-packages/jupyterhub/jupyter/hub/templates/error.html'

In [3]: open(_)
---------------------------------------------------------------------------
FileNotFoundError                         Traceback (most recent call last)
<ipython-input-3-724e07d998de> in <module>()
----> 1 open(_)

FileNotFoundError: [Errno 2] No such file or directory: '/root/jupyter-adapter/lib/python3.5/site-packages/jupyterhub/jupyter/hub/templates/error.html'

What am I missging?


text:
Q: How can I catch the text from a javascript alert and set a OK using chrome headless? guys!
How can I catch the text from a javascript alert and set a OK using chrome headless?
The follow code works very well, but if I set headless option it seems not find the pop up alert.
Edit I realize that my code stops on " self.action.move_to_element(firstLevelMenu).perform() ", instead on javascript alert like I thought. How can I fix it?

import os
from selenium import webdriver from webdriver_manager.chrome import
 ChromeDriverManager from webdriver_manager.firefox import
 GeckoDriverManager from selenium.webdriver.common.keys import Keys
 import time as pausa  from selenium.webdriver.common.by import By from
 selenium.webdriver.common.action_chains import ActionChains from
 selenium.webdriver.support.ui import WebDriverWait from
 selenium.webdriver.support import expected_conditions as EC #olhar
 from selenium.webdriver.remote.webelement import WebElement from
 datetime import datetime from tkinter import * from tkinter import
 scrolledtext,  messagebox, ttk import pyautogui as p import csv import
 datetime from datetime import date, datetime import pyodbc

class Driver:
  def __init__ (self):
    if nav_cbx.get()=='Chrome':
        options = webdriver.ChromeOptions()
        options.add_experimental_option('useAutomationExtension', False)
        # options.add_argument("--headless")
        options.add_argument("--dns-prefetch-disable")
        options.add_argument("--disable-infobars")

self.driver = webdriver.Chrome('c:/driver/chromedriver.exe', options=options)  #PASTA DO SCRIPT
    self.action = ActionChains(self.driver)
    self.wait = WebDriverWait(self.driver, 30)
    self.wait2 = WebDriverWait(self.driver, 10)
    agora = str(datetime.today()).replace(':', '.')

    cria_pasta_log()
    self.log = open(f'{caminho_log()}/log{agora}.csv', "w", newline='\n', encoding='ANSI')

    self.log.write(f'ID;Chpras;Bin;Final;Portador;Status')

    self.login = in_login.get()
    self.senha = in_senha.get()

def menu_reemitir(self, chpras):
    self.retorna_frame()

    firstLevelMenu = self.driver.find_element(By.XPATH, '//*[@id="imgMenu"]')
    self.action.move_to_element(firstLevelMenu).perform() #menu opções
    secondLevelMenu = self.driver.find_element(By.XPATH, '//*[@id="elem9"]')
    secondLevelMenu.click() #submenu reemitir cartão
    self.driver.switch_to.window(self.driver.window_handles[2]) #alternar para popup
    self.wait.until(EC.presence_of_element_located((By.XPATH, '//*[@id="FormSAT"]/div[2]/table[2]/tbody/tr/td[1]/input'))).click()
    # self.driver.execute_script("modificarReemision()")
    pausa.sleep(0.5)

    #### THE PROBLEM STARTS RIGHT HERE!!!!!!!!!!!!!!!!!!!!!!!!
    #there's 2 alerts. On the first one I need set an accept

    alert1 = self.wait.until(EC.alert_is_present())

    alert1.accept()

    pausa.sleep(0.5)
    try:
        # on the second one I need cacth the text and set another "ok"
        alert2 = self.wait.until(EC.alert_is_present())

        text = alert2.text

        alert2.accept()

        print(text)

        if 'BLOQU' in str(text).upper():
            text = self.captura_msg_bloqueio(chpras)

        self.log.write(f'{text};')

    except:
        self.log.write(f'Não foi possível capturar a mensagem de retorno;')
        self.driver.close()

    self.aceita_alerta()
    self.driver.switch_to.window(self.driver.window_handles[1])

    pausa.sleep(0.5)

I really need use the headless option, and I need load/accept the both pop up alerts. How I do this?

A: You can overwrite alert to catch the message:
driver.executeScript("""
  window.alert = message => window.alertMessage = message
""")

Then get it later
message = driver.executeScript("return window.alertMessage")


text:
Q: Best way to use the Firefox search box input to construct a url and navigate to it I'd like to use the Firefox search field at the top right to automatically navigate to a particular URL based on the value of the search string.
Example: If I type "Kangaroo" and hit enter I'd like to navigate to "http://example.org/?q=Kangaroo".
Is there a straightforward way to do this?

A: Did you know Firefox search bar supports keyword for each search engine ? For example : type g superuser in address bar you will get http://www.google.com/search?q=superuser&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
Hope it helps.

A: O'Reilly has detailed tutorial on creating a Firefox search plugin from scratch here
http://oreilly.com/pub/h/3033.

A: This should be easy : Define the URL as a bookmark, then go to its properties and add a keyword. You can then use this keyword as a shortcut to that URL.

For more information, see for example : Keyword Bookmarks Catalogs Handy Firefox Keyword Strings.


text:
Q: two markers in ionic native geolocation using cordova geolocation I have a scenario where I need to show the source and destination with two markers and a blue line that indicates directions. I am using cordava plugin geolocation and trying to get the current location like below
        $cordovaGeolocation.getCurrentPosition(options).then(function(position){

    var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

    var mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    $scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
    google.maps.event.addListenerOnce($scope.map, 'idle', function(){

  var marker = new google.maps.Marker({
      map: $scope.map,
      animation: google.maps.Animation.DROP,
      position: latLng
  });

I also have destination lat and long but I dnt understand how to place them in the code to show two markers and where to show blue connecting line
as
    var marker = new google.maps.Marker({
  map: $scope.map,
  animation: google.maps.Animation.DROP,
  position: latLng
});

takes only an object
Any help would be appreciated.

A: What i did-
  addMarker(position, icon, content) {
    let marker = new google.maps.Marker({
      map: this.map,
      animation: google.maps.Animation.DROP,
      icon: icon,
      position: new google.maps.LatLng(position[0], position[1])
    });
  }

And then
 array.projectsLocation.forEach(element => {
      this.addMarker([element.latitude, element.longitude], element.map_pin_url, element.description);
 });

I was using custom icons so you can ignore that.
Check documentation.


text:
Q: Firebase - How do I add a new field for each row in an existing database? I'm using real time Firebase database. Let's say I already have one million users and each user has fields like email, password, etc..
What if I suddenly want to add a new field to every user in my database? Like I want each user to have a field called age.
I know I can do it manually in Firebase but it's not practical when we deal with a large and complex database

A: Why not create a method using Firebase .update running all documents?
Something like: (this is using Firebase firestore)
updateUser() {
        this.db.collection('yourDbCollection').doc('ifYourIdCostumized').update({
            age: newAgeHere
        })
            .then(function () {
                console.log("Document successfully updated!");
            }).catch(function (error) {
                console.error("Error removing document: ", error);

            });
    }

Or you can use Firebase functions if you want to make it server-side. Post some code so we can see how to help you.


text:
Q: Minimal polynomial in splitting field completion Let $K(\theta)/K$ be a field extension with a minimal polynomial $f(X)$ that decompose to $f_1(X) \dots f_g(X)$ in the completion field $K_\mathfrak{p}$ for  some prime $\mathfrak{p}$ of $K$.
I Know that there are exactly $\mathfrak{P}_1, \dots ,\mathfrak{P}_g$ extentions of $\mathfrak{p}$ in $K(\theta)$ and their decomposition groups fulfills:
$
D(\mathfrak{P}_i / \mathfrak{p}) \cong
Gal(L_{\mathfrak{P}_i}/K_\mathfrak{p}) \cong
Gal(K_p[X]/(f_i(X)))
$
My question is:
For a splitting field $L/K$ of some polynomial $f(X) \in K[X]$
and $\mathfrak{P}_L/\mathfrak{p}_K$ primes, is there any relation between
the minimal polynomial of the extension $L_{\mathfrak{P}}/K_\mathfrak{p}$ and $f(X)$ ?
Also, is it true to say that
$
D(\mathfrak{P} / \mathfrak{p}) \cong
Gal(L_{\mathfrak{P}}/K_\mathfrak{p}) \cong
Gal(K_p[X]/(f(X)))
$ in this case?


text:
Q: success is not defined in Angular $http.jsonp I'm making a $http.jsonp request in my angular/phonegap app. The data is successfully being delivered to the remote server, but I can't get a response from the success function in the angular app. The console is telling me that 'success is not defined.'
Here is my angular code:
app.controller('mainControl' , function($scope , $http){
$scope.credentials = {username: '' , password: ''};

$scope.login = function(){
console.log($scope);

var url = "http://127.0.0.1:3000/endpoint?callback=JSON_CALLBACK";
var responsePromise = $http.jsonp(url, {params: {
  username:$scope.credentials.username,
  password:$scope.credentials.password
}});

responsePromise.success(function (data){
  console.log(data);
})
}

})

Am I missing a step in order to define success?

A: I believe for jsonp you have to use the .then method of handling promise resolution:
responsePromise.then(function (data){
    //success things go here
    console.log(data);
}, function(data({
    //error things go here
});


text:
Q: RDS Aurora (MySQL) performing EXTREMELY poorly I'm migrating our Amazon RDS MsSQL database to RDS Aurora but I am very impressed by Aurora's lack of performance.
UPDATE Cars
SET CurrentDriver_id = (
            SELECT Drivers.Id
            FROM Drivers
            WHERE Drivers.Car_id = Cars.Id
            ORDER BY Drivers.Id DESC
            LIMIT 1)
WHERE Cars.Id BETWEEN 1 AND 500;

I had to limit to the first 500 records so I can even see results in Aurora.
Even limiting to 500 rows, Aurora takes incredibly 55s while MsSQL for all 70.000 records took less than 1 second.
In this scenario, MsSQL performs almost 8.000x faster than Aurora.
The subject of this topic is not the query itself, nor how it could be improved. It is just a simple update running on 70k Cars and 220k Drivers. It should be nothing to a database.
Cars.Id and Drivers.Id are primary keys. No indexes and no foreign keys.
Is this expected?!
Edit:
1. Both RDSs are db.t2.medium
2. MsSQL is a production server with hundreds of users while Aurora is only me.

A: You could try using an approach that don't use subselect
  UPDATE Cars
  inner join Drivers on Drivers.Car_id = Cars.Id  and Cars.Id BETWEEN 1 AND 500
    SET Cars.CurrentDriver_id = Drivers.Id


text: Q: Record rtp stream with FFMPEG can not save files less than 256Kb I'm using ffmpeg to record only audio rtp stream it's work ok. But if recorded file less than 256Kb ffmpeg is not save the file. I received a new file 0Kb(error). If recorded file greater than 256Kb ffmpeg only save file when 256, 512, 768, 1024,.... Kb.


text:
Q: Keeping dropdown menu active (visible) even after hover out My sub menu disappears immediately after I move my mouse pointer to scroll towards the sub menu. Feel like I have screwed my CSS somewhere. I could not figure out after several attempts to make it stay active. I followed few tutorials(have a look at it) where they have called the hover on the ul instead of a(anchor), I tried similar ways but could not achieve what I want. Please point out where I have made the mistake. Here is my fiddle(my code). Sample CSS code for hover is below.
#topnav ul li ul
{
    display: none;
    position: absolute;
    text-align: left;
    background:#510000;
    top:30px;
}
#topnav ul li:hover ul
{
    display: block;
}

A: Put the padding on your list items instead of your ul or container. That way the dropdown overlaps your hover element and your browser never thinks that you hovered out of the element. See this:
#topnav li {
    display:inline-block;
    padding:10px 0;
    margin-right:30px;
    position: relative;
}

http://jsfiddle.net/jeffreyTang/q5cmqLrf/1/

A: You can also give
#topnav ul li ul {
   padding-top:30px
}

instead of:
#topnav ul li ul {
   top:30px
}

A: The problem is with your padding being at the nav level and you trying to make the drop down appear below it. Because you position your dropdown away from the parent li, you're no longer hovering over it when you move your mouse down. To fix, remove the padding from the nav and add it to the li.
remove padding from here:
#topnav{
   display:block;
   clear:both;
   width:500px;
   margin:0;
   padding:0;
   text-align:center;
}

add to here:
#topnav li{
   display:inline-block;
   padding: 15px 0 15px 5px;
   margin-right:30px;
   position: relative;
}

remove top from here:
#topnav ul li ul {
    display: none;
    position: absolute;
    text-align: left;
    background:#510000;
}

fiddle: http://jsfiddle.net/zj8krh95/7/

A: Here's a way to do it (it's more of a trick):
http://jsfiddle.net/zj8krh95/5/
#topnav ul li:hover {
    padding-bottom: 10px;
    margin-bottom: -10px; /* so that the menubar's height stays the same */
}
#topnav ul li:hover ul {
    margin-top: -10px; /* so that the menu opens at the right position */
}

Basically, on hover, i extend the menu item's height so that no mouseout is trigger when i move down to the menu.


text:
Q: How to test service class with @Autowired I have a service class MyService which is defined and being used in controller like so:
public interface MyService {
  public String someMethod()
}

@Service("myService")
public class MyServiceImpl implements MyService {
  public String someMethod() {
    return "something";
  }
}

@Controller
public class MyController {
  @Autowired
  public MyService myService;

  @RequestMapping(value="/someurl", method=RequestMethod.GET)
  public String blah () {
    return myService.getsomeMethod();
  }
}

I'd like to write a test case for the someMethod method, however, the following doesn't work. How can I wire in the implementation class?
public class MyServiceImplTest {
 @Autowired
 private MyService myService;

 @Test
 public void testSomeMethod() {
   assertEquals("something", myService.someMethod());
 }

}

A: public class MyServiceImplTest {
    private MyService myService = new MyServiceImpl();

    @Test
    public void testSomeMethod() {
        assertEquals("something", myService.someMethod());
    }
}

Why inject the bean in your test rather than creating an instance by yourself?

A: Try this:
@RunWith(SpringJUnit4ClassRunner.class)
 // specifies the Spring configuration to load for this test fixture
@ContextConfiguration("yourapplication-config.xml")

Also see the Spring.IO docs for more detail.


text:
Q: Exceeded memory or invalid memory reference - C++ error Can someone please illuminate why I am getting the following error with the following code?
Execution error: Your program had this runtime error:
        Exceeded memory or invalid memory reference. The program ran for
        0.000 CPU seconds before the error. It used 3048 KB of memory.
    ------ Data ------
    7 4
    11 6 11 6 3 10 6
    7 9 6 13 5 15 5
    1 10 12 7 13 7 5
    13 11 10 8 10 12 13
    ----------------------------

Code:
#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
int castle[50][50];
int components[50][50];
bool visited[50][50];
int N, M;

void flood(int y, int x, int component) {
    if(visited[y][x]) return;
    visited[y][x] = true;
    components[y][x] = component;
    if(x>0 && !((castle[y][x] & 1) == 1)) { //West
        cout<<"castle["<<y<<"]["<<x<<"] just";
        cout<<"flooded west\n";
        flood(y, x-1, component);
    }
    if(y>0 && !((castle[y][x] & 2) == 2)) { //North
        cout<<"castle["<<y<<"]["<<x<<"] just";
        cout<<"flooded north\n";
        flood(y-1, x, component);
    }
    if(x<M && !((castle[y][x] & 4) == 4)) { //East
        cout<<"castle["<<y<<"]["<<x<<"] just";
        cout<<"flooded east\n";
        flood(y, x+1, component);
    }
    if(y<N && !((castle[y][x] & 8) == 8)) { //South
        cout<<"castle["<<y<<"]["<<x<<"] just";
        cout<<"flooded south\n";
        flood(y+1, x, component);
    }
}

int main() {
    ifstream inp("castle.in");
    ofstream out("castle.out");
    memset(components, -2, sizeof(components));
    memset(visited, false, sizeof(visited));
    inp >> M >> N;
    for(int y=0; y<N; y++) {
        for(int x=0; x<M; x++) {
            inp >> castle[y][x];
        }
    }

    int curComponent = 0;
    for(int y=0; y<N; y++) {
        for(int x=0; x<M; x++) {
            if(visited[y][x]) continue;
            flood(y,x,++curComponent); //first component will be 1
//          cout << "curComponent = " << curComponent <<"\n";
        }
    }
    int roomAreas[curComponent+2]; //need an extra one since curComponent actually starts at 1
    memset(roomAreas, 0, sizeof(roomAreas));
    int greatestArea = 0;
    for(int y=0; y<N; y++) {
        for(int x=0; x<M; x++) {
            cout << "components[" << y <<"][" << x <<"] = " << components[y][x] << "\n";
            roomAreas[components[y][x]]++;
            if(roomAreas[components[y][x]] > greatestArea) greatestArea = roomAreas[components[y][x]];
        }
    }
    int greatestCombined = 0, bestx=0, besty=0;
    char bestDir='N'; //Means none -> error
    for(int y=0; y<N; y++) {
        for(int x=0; x<M; x++) {
        /*
            if(x>0 && components[y][x] != components[y][x-1] && roomAreas[components[y][x]] + roomAreas[components[y][x-1]] > greatestCombined) { //West
                greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y][x-1]];
                bestx = x;
                besty = y;
                bestDir = 'W';
            }
        */
            if(y>0 && components[y][x] != components[y-1][x] && roomAreas[components[y][x]] + roomAreas[components[y-1][x]] > greatestCombined) { //North
                greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y-1][x]];
                bestx = x;
                besty = y;
                bestDir = 'N';
            }
            if(x<M && components[y][x] != components[y][x+1] && roomAreas[components[y][x]] + roomAreas[components[y][x+1]] > greatestCombined) { //East
                greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y][x+1]];
                bestx = x;
                besty = y;
                bestDir = 'E';
            }
        /*
            if(y<N && components[y][x] != components[y+1][x] && roomAreas[components[y][x]] + roomAreas[components[y+1][x]] > greatestCombined) { //South
                greatestCombined = roomAreas[components[y][x]] + roomAreas[components[y+1][x]];
                bestx = x;
                besty = y;
                bestDir = 'S';
            }
        */
        }
    }
    out << curComponent << "\n" << greatestArea << "\n" << greatestCombined << "\n" << besty+1 << " " << bestx+1 << " " << bestDir << "\n";
    return 0;
}

Thanks so much!

A: Possibly
if(x<M && ...

should be
if(x<M-1 && ...

Since in that part, it can recursively flood(x+1). That could mean passing in x equal to M, which is overflowing the bounds to the east.
Similarly for the y flooding south check.


text:
Q: Exam question: changing from active to passive voice the below-mentioned question is asked in my exam, I think my answer is correct, please tell if I am right, I have to challenge the question in 2 days if its answer given is wrong.
correct answer is given by examiner.
candidate answer is the answer I ticked as correct.
In the following question, a sentence has been given in Active/Passive voice. Out of the four alternatives suggested, select the one which best expresses the same sentence in Passive/Active voice.

I will keep your secret.

Options:
1) Keeping of your secret will be done by me.
 2) I will be keeping the secret of you.
 3) Your secret would be kept by me.
 4) Your secret I will be keeping.
Correct Answer: Your secret would be kept by me.
Candidate Answer: Keeping of your secret will be done by me.

A: The given sentence is in the active, and the test requires that the answer use the passive voice. (2) and (4) are active voice.
Answer (1) is a possible, it creates a gerund phrase as the subject. It is possible but it isn't a likely form.
Answer (3) uses the passive voice, but changes the meaning. The word "would" has several meanings, one possibility is as the conclusion to a conditional phrase, in which the condition is not explicit. "Your secret would be kept, (if it wasn't such great gossip)"
So neither is really an acceptable answer. Instead, the most obvious passive form is just "Your secret will be kept (by me)."

A: I believe this is a question of which one is the best.
Both answers are correct grammar. In fact, I believe that all of the choices except C are correct grammar. But, the Candidate Answer a.k.a yours, is considered "wordy," which means that it requires more words and complex sentence structure than what is needed.
I have to say that the Correct Answer is better than the Candidate Answer.
Does this answer your question?


text:
Q: Special character combination "?/" not being interpreted correctly in XML? For our top menu, we use a custom control that essentially reads from an XML file. The name of the control is SCS.MultiMenu.
One of the menuitems is a report whose link is the following:
http://MyServer/ReportServer/Pages/ReportViewer.aspx?/Folder/MyReport

The report generates correctly with that URL.
So, in the XML file, the menuitem looks like this:
<MenuItem Text="My report"
Url="http://MyServer/ReportServer/Pages/ReportViewer.aspx?/Folder/Report"
PostBack="False"/>

When I click on this menuitem, I'm redirected to the following link, which is incorrect: http://myserver/ReportServer/Pages/ReportViewer.aspx? As you can see, it removed everything after the question mark.
I tried using escape sequences to see if it accepts the correct URL (ie. ? for question mark (?) and / for slash) but it continues cutting everything after the "?". I tried something like this:
http://MyServer/ReportServer/Pages/ReportViewer.aspx?/Folder/MyReport

What could the issue be? I even tried switching every single character to escpae sequences, but did not work.
I'm thinking that it's possibly an error in this menu control, but it wouldn't make sense.
I'm including everything I've tried and what the URL looks like when I click on it:
http://MyServer/ReportServer/Pages/ReportViewer.aspx?/Folder/MyReport
>> http://myserver/ReportServer/Pages/ReportViewer.aspx?

http://MyServer/ReportServer/Pages/ReportViewer.aspx?path=%2FFolder%2FReport
>> http://myserver/ReportServer/Pages/ReportViewer.aspx?path=/Folder/Report&

http://MyServer/ReportServer/Pages/ReportViewer.aspx?/Folder/MyReport
>> http://myserver/ReportServer/Pages/ReportViewer.aspx?

http://MyServer/ReportServer/Pages/ReportViewer.aspx?/Folder/MyReport=
>> http://myserver/ReportServer/Pages/ReportViewer.aspx?/Folder/MyReport=&

http://MyServer/ReportServer/Pages/ReportViewer.aspx?=/Folder/MyReport
>> http://myserver/ReportServer/Pages/ReportViewer.aspx?=/Folder/MyReport&

Thanks

A: The library handles the url of a menu item in a special way:
It cuts of the querystring from the url and parses it:

*

*split by & into single parameters

*split by = into name value pairs.

(see QueryString.cs)
If no = is present in step 2 the parameter is silently discarded, and that is why
your querystring /Folder/Report vanishes.
You could try if /Folder/Report= or =/Folder/Report survive this treatment and are accepted by your server.


text:
Q: Getting the size of my list is crashing my program It's only a one line file.
When I call .size() with something else (like appending it to a string of spaces), it spits out something, so why would it would crash when I call the function alone?
int pos =0;
List<List<String>> mine = new ArrayList<List<String>>();
while((nextLine = csvReader.readLine()) != null) {
    mine.add(pos,new ArrayList <String>());
    for (String token : nextLine.split(",")) {

        //get next token and store it in the list
        mine.get(pos).add(token);
        //Toast.makeText(MainActivity.this,mine.size() + " " + mine.get(pos).size(), Toast.LENGTH_SHORT).show();
    }

    //Toast.makeText(MainActivity.this, " " + mine.get(pos).size(), Toast.LENGTH_SHORT).show(); //doesn't crash here

    //  mine_end= mine.get(pos).size(); //crash here

    pos ++;
}

Here is the latest stack trace of errors:
07-17 15:52:44.987: E/wpa_supplicant(29035): Ongoing Scan action...
07-17 15:52:46.989: E/wpa_supplicant(29035): Ongoing Scan action...
07-17 15:52:48.991: E/wpa_supplicant(29035): Ongoing Scan action...
07-17 15:52:49.061: E/AndroidRuntime(1249): FATAL EXCEPTION: main
07-17 15:52:49.061: E/AndroidRuntime(1249): android.content.res.Resources$NotFoundException: String resource ID #0x1
07-17 15:52:49.061: E/AndroidRuntime(1249):     at android.content.res.Resources.getText(Resources.java:221)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at android.widget.Toast.makeText(Toast.java:284)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at com.jimmyc.summer.wificollection.MainActivity.match(MainActivity.java:137)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at com.jimmyc.summer.wificollection.MainActivity.access$2(MainActivity.java:91)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at com.jimmyc.summer.wificollection.MainActivity$2$1$1.run(MainActivity.java:383)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at android.os.Handler.handleCallback(Handler.java:587)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at android.os.Handler.dispatchMessage(Handler.java:92)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at android.os.Looper.loop(Looper.java:130)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at android.app.ActivityThread.main(ActivityThread.java:3691)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at java.lang.reflect.Method.invokeNative(Native Method)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at java.lang.reflect.Method.invoke(Method.java:507)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
07-17 15:52:49.061: E/AndroidRuntime(1249):     at dalvik.system.NativeStart.main(Native Method)
07-17 15:52:49.071: E/(306): Dumpstate > /data/log/dumpstate_app_error

A: It's quite likely that mine.get(pos) is returning null, hence a NullPointerException occurs. Make sure that you've initialized each pos position in the list.

A: The error was something completely unrelated. I guess I shouldn't use Toast messages to debug.  In this case, it affected the timing and led me to believe that the .size() was causing the error.


text:
Q: all nested descendants Deep nesting I have Taxons table with all parent child records:
<ActiveRecord::Relation [

#<Spree::Taxon id: 1, parent_id: nil, position: 0, name: "Brands",
permalink: "brands", taxonomy_id: 1, lft: 1, rgt: 20,
icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil,
description: nil, created_at: "2017-06-14 08:52:19", updated_at: "2017-06-23 06:34:11",
meta_title: nil, meta_description: nil, meta_keywords: nil, depth: 0>,

#<Spree::Taxon id: 2, parent_id: nil, position: 0, name: "Brand", permalink: "brand", taxonomy_id: 2, lft: 21, rgt: 22,
icon_file_name: nil, icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil, description: nil,
created_at: "2017-06-14 08:52:19", updated_at: "2017- 06-14 08:52:22", meta_title: nil,
meta_description: nil, meta_keywords: nil, depth: 0>,

#<Spree::Taxon id: 3, parent_id: 1, position: 0, name:
"Bags", permalink: "brands/bags", taxonomy_id: 1, lft: 2, rgt: 3,
icon_file_name: nil, icon_content_type: nil, icon_file_size: nil,
icon_updated_at: nil, description: nil, created_at: "2017-06-14
08:52:19", updated_at: "2017-06-21 05:03:52", meta_title: nil,
meta_description: nil, meta_keywords: nil, depth: 0>,

#<Spree::Taxon id: 4, parent_id: 1, position: 0, name: "Mugs", permalink:
"brands/mugs", taxonomy_id: 1, lft: 4, rgt: 5, icon_file_name: nil,
icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil,
description: nil, created_at: "2017-06-14 08:52:20", updated_at: "2017-
06-14 08:58:29", meta_title: nil, meta_description: nil, meta_keywords:
nil, depth: 0>,

#<Spree::Taxon id: 5, parent_id: 1, position: 0, name:
"Clothing", permalink: "brands/clothing", taxonomy_id: 1, lft: 6, rgt:
11, icon_file_name: nil, icon_content_type: nil, icon_file_size: nil,
icon_updated_at: nil, description: nil, created_at: "2017-06-14
08:52:20", updated_at: "2017-06-23 06:34:11", meta_title: nil,
meta_description: nil, meta_keywords: nil, depth: 0>,

#<Spree::Taxon id: 6, parent_id: 5, position: 0, name: "Shirts", permalink:
"brands/clothing/shirts", taxonomy_id: 1, lft: 7, rgt: 8,
icon_file_name: nil, icon_content_type: nil, icon_file_size: nil,
icon_updated_at: nil, description: nil, created_at: "2017-06-14
08:52:20", updated_at: "2017-06-20 06:10:16", meta_title: nil,
meta_description: nil, meta_keywords: nil, depth: 0>,

#<Spree::Taxon id: 7, parent_id: 5, position: 0, name: "T-Shirts", permalink:
"brands/clothing/t-shirts", taxonomy_id: 1, lft: 9, rgt: 10,
icon_file_name: nil, icon_content_type: nil, icon_file_size: nil,
icon_updated_at: nil, description: nil, created_at: "2017-06-14
08:52:20", updated_at: "2017-06-23 06:34:11", meta_title: nil,
meta_description: nil, meta_keywords: nil, depth: 0>,

#<Spree::Taxon id: 8, parent_id: 1, position: 0, name: "Ruby", permalink:
"brands/ruby", taxonomy_id: 2, lft: 12, rgt: 13, icon_file_name: nil,
icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil,
description: nil, created_at: "2017-06-14 08:52:21", updated_at: "2017-
06-20 06:09:31", meta_title: nil, meta_description: nil, meta_keywords:
nil, depth: 0>,

#<Spree::Taxon id: 9, parent_id: 1, position: 0, name:
"Apache", permalink: "brands/apache", taxonomy_id: 2, lft: 14, rgt: 15,
icon_file_name: nil, icon_content_type: nil, icon_file_size: nil,
icon_updated_at: nil, description: nil, created_at: "2017-06-14
08:52:21", updated_at: "2017-06-23 06:34:11", meta_title: nil,
meta_description: nil, meta_keywords: nil, depth: 0>,

#<Spree::Taxon id: 10, parent_id: 1, position: 0, name: "Spree", permalink:
"brands/spree", taxonomy_id: 2, lft: 16, rgt: 17, icon_file_name: nil,
icon_content_type: nil, icon_file_size: nil, icon_updated_at: nil,
description: nil, created_at: "2017-06-14 08:52:21", updated_at: "2017-
06-14 08:58:29", meta_title: nil, meta_description: nil, meta_keywords:
nil, depth: 0>, ...]>

I need a tree structure like this:
parent1(first taxon(first record) with all child if it has)
  - child1
  - child2
  - child3
    - child7
    - child9
  - child4
  - child5
parent2(it has no child)
parent3(Not it has child)
  - child7
  - child9

I short I need each individual taxon with its nested child.
I have tried something like:
Taxon.all.each do |i|
     i.self_and_descendants.each do |j|
       taxon_with_childs << j
     end

But this gives plain array, but I want array with parent child nesting.
I have also tried:
Taxon.each_with_level(Taxon.root.self_and_descendants) do |taxon, level|
    taxon_with_childs << taxon
  end

But this is giving only first record's children and not a deep nesting.

A: I think it can be done by DFS function
def add_self_and_descendents(x, taxon_with_childs)
  taxon_with_childs << x
  x.descendants.each do |y|
    add_self_and_descendents(y, taxon_with_childs)
  end
end

Taxon.all.each do |i|
  add_self_and_descendents(i, taxon_with_childs)
end

And it will have long time if the database is bigger and bigger.
But there's no other way to do it with short time because database operation functions only use constant values such as Taxon.where(:parent_id => 1 )
Hope this works for you.


text:
Q: Error with ostream definition Doing some refactoring, I get an error after moving some code in a class' member function:
std::ostream  logStream;         //  <-- error
std::filebuf  fileBuffer;

// Send the output either to cout or to a file
if(sendToCout) {
    logStream.rdbuf(std::cout.rdbuf());
}
else {
    fileBuffer.open("out.txt", std::ios_base::out | std::ofstream::app);
    logStream.rdbuf(&fileBuffer);
}

logStream << "abcd..." << std::endl;

This is the compiler error message:
file.cpp:417: error: calling a protected constructor of class 'std::__1::basic_ostream<char>'
        std::ostream  logStream;
                      ^

Could this be a solution?
std::filebuf  fileBuffer;
std::ostream  logStream(&fileBuffer);

...

if(sendToCout) {
    logStream.rdbuf(std::cout.rdbuf());
}

A: If you see e.g. this std::ostream constructor reference you will see that the only public constructor is one taking a pointer to a std::streambuf object, like for example your variable fileBuffer.
So one way to solve your problem is to do
std::filebuf  fileBuffer;
std::ostream  logStream(&fileBuffer);

A better solution is to use std::ofstream if you want output to a file.
If you want a more generic solution, where it should be possible to use any kind of output stream, then a redesign to use references instead is a possible solution.
Or, you know, try and find an existing logging library which handles everything for you already.


text:
Q: SharePoint 2010 web application migrate Server 2008 to server 2012 R2 Ajax Control toolkit error Previous Farm : SharePoint 2010,server 2008,SQL 2008
New Farm :SharePoint 2010,server 2012 R2,SQL 2014
Goal : migration web application to new server
Steps :

*

*create backup whole farm full backup from the central admin

*copy backup in new server

*install SharePoint 2010 SP2 in new server

*new web aplication crete in new server

*Restore web application from old server backup

Error:

A: You have to install that tool kit into the new farm. That is 3rd party toolkit which is not backed up using the sharepoint backup method.
Please install that and then test your web application.
I think Ajax control toolkit is a codeplex solution