text:
Q: Pass HTML table data from view as list to Controller action method in ASP.NET Core Getting null values in controller action method. Could not loop table data rows.
Model:
class:
 public class Generation
    {
        public int Generation1Count { get; set; }
        public int Generation1TotalSum { get; set; }
        public int Generation2Count { get; set; }
        public int Generation2TotalSum { get; set; }
        public int Generation3Count { get; set; }
        public int Generation3TotalSum { get; set; }
        public List<Memberdetails> Memberdetails { get; set; }
    }

public class Memberdetails
{
    public string MemberType { get; set; }
    public string MemberCategory { get; set; }
    public int TotalSum { get; set; }
    public int MemberCount { get; set; }
}

Controller:
public ActionResult Index()
        {
            Generation model = new Generation();
            model.Memberdetails = populateMemberDetails();
            return View(model);
        }

   private static List<Memberdetails> populateMemberDetails()
    {
        List<Memberdetails> list = new List<Memberdetails>();
        list.Add(new Memberdetails { MemberCategory = "A", MemberType = "Generation1", MemberCount = 12, TotalSum = 2636 });
        list.Add(new Memberdetails { MemberCategory = "B", MemberType = "Generation2", MemberCount = 12, TotalSum = 4747 });
        list.Add(new Memberdetails { MemberCategory = "A", MemberType = "Generation2", MemberCount = 12, TotalSum = 47474 });
        return list;
    }

    [HttpPost]
    public JsonResult Save(Generation generation)
    {
        return null;
    }

View: Table row looping is not working .is that correct way?
@model CLPConfigurations.Models.Generation

@{
    Layout = null;
}

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

    <form id="frmDetails">

                    MemberType
                    MemberCategory
                    TotalSum
                    MemberCount

                @foreach (var item in Model.Memberdetails)
                {

                        @item.MemberType
                        @item.MemberCategory
                        @item.TotalSum
                        @item.MemberCount

                }

        <input id="btnSave" type="button" value="Save" />
    </form>

Expecting view values to controller action method \ but getting null values. Don't know how to pass values from view to controller action method.

A: That's because your form isn't submitted. Firstly, replace this line in your view:
<input id="btnSave" type="button" value="Save" />

with this:
<input id="btnSave" type="submit" value="Save" />

Secondly, specify the action your form should call on submit:
<form id="frmDetails" action="/YourController/Save" method="post">

And add some code into action Save (beyond returning null). At least this, to see whether your form was submitted:
return Json(new { Result = "Form successfully submitted." }, JsonRequestBehavior.AllowGet); // Because returned type is JsonResult


text:
Q: Java 8, Using Nashorn with Java 8 Compact Profiles Is it possible to use Nashorn (the new JavaScript engine for Java8) together with each of the three Java 8 compact profiles?

A: Yes, you can use Nashorn in all compact profiles.  This is explicitly documented in the compact profiles for embedded documentation:

Compact1 Profile APIs
Similar to the legacy Connected Device Configuration (CDC) with the Foundation Profile, secure sockets layer (SSL), logging, and scripting language support, including Javascript. When configured with the minimal JVM, the compact1 profile APIs have a static footprint of about 12MB.

Each compact profile is a superset of the previous one, so by virtue of being usable in compact1, Nashorn is also usable in compact2 and compact3.
As further evidence, bug JDK-8027532 was filed and resolved to ensure Nashorn doesn't use any classes outside of compact1.
Note that there is no requirement for JVMs to provide any particular script engine.  Thus while Nashorn is compatible with all compact profiles, a particular JVM may not make it available.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to check if a column exists, if it does, return a value from it In psycopg2, if I have a table:
+------+-----+-------+
| name | age | color |
+------+-----+-------+
| Bob  |  25 | red   |
| Bill |  50 | blue  |
| Jane |  45 | black |
+------+-----+-------+

If I do cursor.execute("SELECT * FROM mySchema.this_table LIMIT 1")
then I check if color exists with:
colnames = [desc[0] for desc in cursor.description]
then search colnames for 'color'
then I think I get the row with:
myrow = importCursor.fetchone()
but how do I get the 'color' value of that row?
I tried color = importCursor.fetchone()['color']
but that doesn't work.
How do I get the color value of the row returned by that SELECT statement? I don't know how many columns there are in the table, or if the 'color' column will always be column #3 I have to do this for a bunch of columns in this table (check if exists, if does, return column value of row) so an efficient way is best!

A: Select only some columns
If you select only certain columns, then you do know the column order.
cursor.execute("SELECT name, age, color FROM mySchema.this_table LIMIT 1")

Now you know that column 0 is name, 1 is age, 2 is color. So you can choose which one with something like myrow[1].
Get a map of columns first
You can get a map of the returned columns, and then use that to figure out where to fetch.
column_names = [desc[0] for desc in cursor.description]
if 'color' in column_names:
    color = cursor.fetchOne()[column_names.index('color')]

This should be relatively efficient, because you only need to calculate the column name list one time after the query, and then you can map the column name to a column number with simple list operations like index and in, which are much faster than hitting the database again.


text:
Q: Full Tree View in SharePoint Online I want to achieve a full tree view of my site hierarchy and the documents in there. So I would be able to see the full tree view of the site hierarchy from any site.
It isn't possible to do with the "tree view" or "quick start" areas from what I understand.
Any tip on how to do this in SharePoint Online? Maybe with the help of SharePoint Designer?
Actually a webpart containing such a full tree view would be great, since I could use it in a template.

A: How comfortable are you with JavaScript, REST, Asynchronous processing?
The information you want is not available with one call, you have to recursively process Webs and Lists
Starting points:

*

*Retrieve folders and sub folders from document library by REST call

*Get all Files and Folders in one call


text:
Q: How to plot other field in a single map with levelplot (LatticeExtra)? I'm make meteorogical maps with levelplot function of LatticeExtra package. But, usully i need more than a field in a single map. For example: A single map with wind speed (shaded) and pressure (contour) (Fig1). But, i really dont know how make this maps compost in R. There any method for make this style maps in R?
Is possible at least make a single map with one field shaded and other contour?

A: For example you can plot continuous data and contours like this (taken from the levelplot examples):
require(lattice)
require(stats)
attach(environmental)
ozo.m <- loess((ozone^(1/3)) ~ wind * temperature * radiation,
               parametric = c("radiation", "wind"), span = 1, degree = 2)
w.marginal <- seq(min(wind), max(wind), length = 50)
t.marginal <- seq(min(temperature), max(temperature), length = 50)
r.marginal <- seq(min(radiation), max(radiation), length = 4)
wtr.marginal <- list(wind = w.marginal, temperature = t.marginal,
                     radiation = r.marginal)
grid <- expand.grid(wtr.marginal)
grid[, "fit"] <- c(predict(ozo.m, grid))
contourplot(fit ~ wind * temperature | radiation, data = grid,
            cuts = 10, region = TRUE,
            xlab = "Wind Speed (mph)",
            ylab = "Temperature (F)",
            main = "Cube Root Ozone (cube root ppb)")

Also check out the examples on https://oscarperpinan.github.io/rastervis/#levelplot.


text:
Q: Replication timeout exception is occuring often in infinispan replicated cache added in wildfly 10 cluster(2 nodes) We are setting up a clustered environment using wildfly 10 of 2 nodes. We have added a new cache-container and replicated cache named 'userSessionData' for sharing data across two servers. Standalone-full-ha.xml is used. Everything is working fine in our development environment.
But in client pre-prod environment, quite often, we are getting replication timeout exception. In our dev environment, we are using default remote-timeout setting i.e. 17500 ms, which I think corresponds to replication timeout. In client pre-prod environment, we have increased it to 60000 ms i.e. 1 min, but still getting same exception quite often. One of the timeout issue scenario:- When user login into application,then we put user session details into cache. During writing into cache, exception occurs.
I have attached infinispan configuration, Java codes used during cache writing and exception.  Also pasted it below.
Below is the infinispan configuration for added cache.
<cache-container name="userSessionData_cache" default-cache="default" jndi-name="infinispan/userSessionData_cache">
                <transport lock-timeout="60000"/>
                <replicated-cache name="userSessionData" jndi-name="infinispan/userSessionData_cache/userSessionData" mode="SYNC" remote-timeout="60000">
                    <transaction mode="BATCH"/>
                </replicated-cache>
</cache-container>

Below is the Java class code which will call another Java class used for cache:
public class UserSessionTracker {

    private UserSessionTracker() {
    }
    private static UserSessionTracker instance = new UserSessionTracker();

    public static void putUserSession(String userName, String sessionId) {
        synchronized (instance) {
                UserSessionDataCacheManager.getInstance().putUserSession(userName, sessionId);
        }
    }
 }

Below is the java class used for cache (Singleton pattern for class is used ) :
@ManagedBean(name = "userSessionDataCacheManager", eager = true)
@ApplicationScoped
public class UserSessionDataCacheManager {

@Resource(name = "java:jboss/infinispan/userSessionData_cache/userSessionData")
    private Cache<String, java.util.Hashtable<String, Object>> entityCache = null;

    private static UserSessionDataCacheManager configInstance = null;

    public UserSessionDataCacheManager() {
        configInstance = this;
    }

    @PostConstruct
    public void start() {
System.out.println("Cache name: " + entityCache.getName());
    }

    public static UserSessionDataCacheManager getInstance() {
        if (configInstance == null) {
            createInstance();
        }
        return configInstance;
    }

    private static void createInstance() {
        configInstance = new UserSessionDataCacheManager();
    }

    public void putUserSession(String userName, String sessionId) {
System.out.println("inside  putUserSession");
    java.util.Hashtable<String, Object> sessionData = new java.util.Hashtable<String, Object>();
        sessionData.put("Session", sessionId);
        entityCache.put(userName, sessionData);

    }
}

Below is the exception log.
2017-07-27 11:53:54,539 INFO  [stdout] (default task-15) inside putUserSession

2017-07-27 11:54:54,571 ERROR [org.infinispan.interceptors.InvocationContextInterceptor] (default task-15) ISPN000136: Error executing command PrepareCommand, writing keys [F2959267]: org.infinispan.util.concurrent.TimeoutException: Replication timeout for fit-r3stems01
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.checkRsp(JGroupsTransport.java:801)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.lambda$invokeRemotelyAsync$1(JGroupsTransport.java:642)
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:602)
    at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:1962)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:47)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:16)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    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:748)

2017-07-27 11:54:54,571 ERROR [org.infinispan.transaction.impl.TransactionCoordinator] (default task-15) ISPN000097: Error while processing a prepare in a single-phase transaction: org.infinispan.util.concurrent.TimeoutException: Replication timeout for fit-r3stems01
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.checkRsp(JGroupsTransport.java:801)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.lambda$invokeRemotelyAsync$1(JGroupsTransport.java:642)
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:602)
    at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:1962)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:47)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:16)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    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:748)

2017-07-27 11:55:54,587 ERROR [org.infinispan.interceptors.InvocationContextInterceptor] (default task-15) ISPN000136: Error executing command RollbackCommand, writing keys [F2959267]: org.infinispan.util.concurrent.TimeoutException: Replication timeout for fit-r3stems01
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.checkRsp(JGroupsTransport.java:801)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.lambda$invokeRemotelyAsync$1(JGroupsTransport.java:642)
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:602)
    at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:1962)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:47)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:16)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    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:748)

2017-07-27 11:55:54,587 WARN  [org.infinispan.transaction.impl.TransactionCoordinator] (default task-15) ISPN000141: Could not rollback prepared 1PC transaction. This transaction will be rolled back by the recovery process, if enabled. Transaction: LocalXaTransaction{xid=DummyXid{id=77}} LocalTransaction{remoteLockedNodes=null, isMarkedForRollback=false, lockedKeys=[], backupKeyLocks=[], topologyId=3, stateTransferFlag=null} org.infinispan.transaction.xa.LocalXaTransaction@8b: org.infinispan.util.concurrent.TimeoutException: Replication timeout for fit-r3stems01
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.checkRsp(JGroupsTransport.java:801)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.lambda$invokeRemotelyAsync$1(JGroupsTransport.java:642)
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:602)
    at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:1962)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:47)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:16)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    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:748)

2017-07-27 11:55:54,587 WARN  [org.infinispan.transaction.tm.DummyTransaction] (default task-15) ISPN000112: exception while committing: javax.transaction.xa.XAException
    at org.infinispan.transaction.impl.TransactionCoordinator.handleCommitFailure(TransactionCoordinator.java:207)
    at org.infinispan.transaction.impl.TransactionCoordinator.commit(TransactionCoordinator.java:159)
    at org.infinispan.transaction.xa.TransactionXaAdapter.commit(TransactionXaAdapter.java:114)
    at org.infinispan.transaction.tm.DummyTransaction.finishResource(DummyTransaction.java:401)
    at org.infinispan.transaction.tm.DummyTransaction.commitResources(DummyTransaction.java:448)
    at org.infinispan.transaction.tm.DummyTransaction.runCommit(DummyTransaction.java:321)
    at org.infinispan.transaction.tm.DummyTransaction.commit(DummyTransaction.java:108)
    at org.wildfly.clustering.ee.infinispan.InfinispanBatch.close(InfinispanBatch.java:71)
    at org.wildfly.clustering.web.undertow.session.DistributableSession.requestDone(DistributableSession.java:81)
    at io.undertow.servlet.spec.ServletContextImpl.updateSessionAccessTime(ServletContextImpl.java:814)
    at io.undertow.servlet.spec.HttpServletResponseImpl.responseDone(HttpServletResponseImpl.java:565)
    at io.undertow.servlet.spec.HttpServletResponseImpl.sendRedirect(HttpServletResponseImpl.java:202)
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
    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:748)
Caused by: org.infinispan.util.concurrent.TimeoutException: Replication timeout for fit-r3stems01
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.checkRsp(JGroupsTransport.java:801)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.lambda$invokeRemotelyAsync$1(JGroupsTransport.java:642)
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:602)
    at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:1962)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:47)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:16)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    ... 3 more

2017-07-27 11:55:54,712 WARN  [org.wildfly.clustering.web.undertow] (default task-15) javax.transaction.HeuristicMixedException: org.infinispan.commons.CacheException: javax.transaction.HeuristicMixedException
    at org.wildfly.clustering.ee.infinispan.InfinispanBatch.close(InfinispanBatch.java:74)
    at org.wildfly.clustering.web.undertow.session.DistributableSession.requestDone(DistributableSession.java:81)
    at io.undertow.servlet.spec.ServletContextImpl.updateSessionAccessTime(ServletContextImpl.java:814)
    at io.undertow.servlet.spec.HttpServletResponseImpl.responseDone(HttpServletResponseImpl.java:565)
    at io.undertow.servlet.spec.HttpServletResponseImpl.sendRedirect(HttpServletResponseImpl.java:202)
    at io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
    at io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
    at io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
    at io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
    at io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
    at org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:131)
    at io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
    at io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
    at io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
    at io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
    at io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
    at io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
    at io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:292)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:138)
    at io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:135)
    at io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
    at io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.api.LegacyThreadSetupActionWrapper$1.call(LegacyThreadSetupActionWrapper.java:44)
    at io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:272)
    at io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:81)
    at io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:104)
    at io.undertow.server.Connectors.executeRootHandler(Connectors.java:202)
    at io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:805)
    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:748)
Caused by: javax.transaction.HeuristicMixedException
    at org.infinispan.transaction.tm.DummyTransaction.finishResource(DummyTransaction.java:439)
    at org.infinispan.transaction.tm.DummyTransaction.commitResources(DummyTransaction.java:448)
    at org.infinispan.transaction.tm.DummyTransaction.runCommit(DummyTransaction.java:321)
    at org.infinispan.transaction.tm.DummyTransaction.commit(DummyTransaction.java:108)
    at org.wildfly.clustering.ee.infinispan.InfinispanBatch.close(InfinispanBatch.java:71)
    ... 161 more
Caused by: javax.transaction.xa.XAException
    at org.infinispan.transaction.impl.TransactionCoordinator.handleCommitFailure(TransactionCoordinator.java:207)
    at org.infinispan.transaction.impl.TransactionCoordinator.commit(TransactionCoordinator.java:159)
    at org.infinispan.transaction.xa.TransactionXaAdapter.commit(TransactionXaAdapter.java:114)
    at org.infinispan.transaction.tm.DummyTransaction.finishResource(DummyTransaction.java:401)
    ... 165 more
Caused by: org.infinispan.util.concurrent.TimeoutException: Replication timeout for fit-r3stems01
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.checkRsp(JGroupsTransport.java:801)
    at org.infinispan.remoting.transport.jgroups.JGroupsTransport.lambda$invokeRemotelyAsync$1(JGroupsTransport.java:642)
    at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:602)
    at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
    at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
    at java.util.concurrent.CompletableFuture.complete(CompletableFuture.java:1962)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:47)
    at org.infinispan.remoting.transport.jgroups.RspListFuture.call(RspListFuture.java:16)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    ... 3 more

A: We had an issue where these timeouts occurred during garbage collection events using the default throughput garbage collection.  Which can be tuned multiple ways to reduce pausing including parallel gc or cms collection.
Remote possibility for some sort of network issue as well depending upon how you are using jgroups, but in my observation this more likely occurs during the "stop the world" garbage collection condition as services grow under memory pressure.
-XX:+UseConcMarkSweepGC -XX:+UseParNewGC
Since infinispan is a cache the timeouts are so small that they exceed the jvm pause millis that are normally considered acceptable for some applications.
http://infinispan.org/docs/stable/performance_guide/performance_guide.html#garbage_collection
https://developer.jboss.org/thread/269569?_sscc=t
Difference between -XX:UseParallelGC and -XX:+UseParNewGC


text:
Q: Django Sending Email : SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed I am trying to send email to an AOL account via Django and I am getting the following error:
Traceback (most recent call last):
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Dom\Documents\Python_Projects\Django\TDD_with_Python_and_Django\superlists\accounts\views.py", line 21, in send_login_email
    [email],
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\__init__.py", line 62, in send_mail
    return mail.send()
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\message.py", line 348, in send
    return self.get_connection(fail_silently).send_messages([self])
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 104, in send_messages
    new_conn_created = self.open()
  File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 71, in open
    self.connection.login(force_str(self.username), force_str(self.password))
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 721, in login
    initial_response_ok=initial_response_ok)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 631, in auth
    (code, resp) = self.docmd("AUTH", mechanism + " " + response)
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 421, in docmd
    return self.getreply()
  File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 391, in getreply
    + str(e))
smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed by the remote host
"POST /accounts/send_email HTTP/1.1" 500 130728

Here are my settings:
EMAIL_HOST = 'smtp.aol.com'
EMAIL_HOST_USER = 'myemail@aol.com'
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
EMAIL_PORT = 465
EMAIL_USE_SSL = True

I am following along with the book TDD with Python on Chapter 18, which has a custom authentication backend:
class PasswordlessAuthenticationBackend(object):

    def authenticate(self, uid):
        print('uid', uid, file=sys.stderr)
        if not Token.objects.filter(uid=uid).exists():
            print('no token found', file=sys.stderr)
            return None
        token = Token.objects.get(uid=uid)
        print('got token', file=sys.stderr)
        try:
            user = ListUser.objects.get(email=token.email)
            print('got user', file=sys.stderr)
            return user
        except ListUser.DoesNotExist:
            print('new user', file=sys.stderr)
            return ListUser.object.create(email=token.email)

    def get_user(self, email):
        return ListUser.objects.get(email=email)

This is suppose to authenticate the user via email using the following view
def send_login_email(request):
    email = request.POST['email']
    uid = str(uuid.uuid4())
    Token.objects.create(email=email, uid=uid)
    print('saving uid', uid, 'for email', email, file=sys.stderr)
    url = request.build_absolute_uri(f'/accounts/login?uid={uid}')
    send_mail(
        'Your login link for Superlists',
        f'Use this link to log in:\n\n{url}',
        'noreply@superlists',
        [email],
    )
    return render(request, 'login_email_sent.html')

The traceback suggests it is failing at send_login_email but I am not sure why; the book example uses a gmail account but I am using an AOL account instead because I have a throwaway email I never use. I adjusted my settings.py to accommodate AOL's email service settings, but I may have missed something...I'm just not sure what.
Any help/info is greatly appreciated. Thank you.
EDIT
I disabled my firewall at the suggestion of @hwjp and I no longer receive the [WinError 10054]; the code gets a little further but now I get the following error:
File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 394, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")

Looking at the smtplib.py function where it is failing:
def getreply(self):
        """Get a reply from the server.

        Returns a tuple consisting of:

          - server response code (e.g. '250', or such, if all goes well)
            Note: returns -1 if it can't read response code.

          - server response string corresponding to response code (multiline
            responses are converted to a single, multiline string).

        Raises SMTPServerDisconnected if end-of-file is reached.
        """
        resp = []
        if self.file is None:
            self.file = self.sock.makefile('rb')
        while 1:
            try:
                line = self.file.readline(_MAXLINE + 1)
            except OSError as e:
                self.close()
                raise SMTPServerDisconnected("Connection unexpectedly closed: "
                                             + str(e))
            if not line:
                self.close()
                raise SMTPServerDisconnected("Connection unexpectedly closed")

To me this seems like self.sock.makefile('rb') is failing; but I am not sure why and I am having some difficulties tracing the source of the problem.
I will continue to look into it but any other hints/suggestions are appreciated.


text:
Q: MySQL UPDATE is Creating New Record with Pear DB I am working on a basic add/edit/delete form using PEAR DB. My add and delete functions are working correctly, but my edit function is creating a duplicate record instead of editing the active record.
I have searched the forums, the MySQL manual, and php.net, but there isn't much documentation out there. The site I am working on is old, and I understand that very few people are working with Pear DB, as frameworks like CodeIgniter are now the way to go. I would switch this site over if I could, believe me. That said, any help sorting this out would be greatly appreciated!
Here's my code:
<?php

require 'controller.php';
global $dbc;
$member_id = $_GET['memberid'];
$aid = $_GET['aid'];

/* Handle Accounting Actions -- Add, Edit, Delete */

$action = isset( $_GET['action'] ) ? $_GET['action'] : "";

switch ($action) {

  case 'add':
    add_aid();
    break;

  case 'edit':
    edit_aid();
    break;

  case 'delete':
    delete_aid();
    break;

  default:
    add_aid();
    break;
}

function add_aid()
{
    global $dbc;
    $member_id = $_GET['memberid'];
    $aid = $_GET['aid'];

?>

    <form name="add accounting record" action="?module=members&mode=edit" method="post">

    <input type="hidden" id="member_id" name="member_id" value="<?=$member_id?>" />

                Accounting

                Actions	Year	Dues Pd. (Date)	Amount Pd.	Attended
Conference
(Date)

                    <a href="?module=memberss&mode=edit&aid='<?php print $data['aid'];?>" title="Edit"> <a onclick="return window.confirm(\'Are you sure you want to delete this record?\');" href="?module=members&action=delete&aid=<?php print $data[0];?>" title="Delete">

                    <input type="text" id="year" name="year" value="<?=$_POST['year']?>" size="10" maxlength="4" />

                    <input type="text" id="dues_paid_date" value="<?=$_POST['dues_paid_date']?>" name="dues_paid_date" size="20" maxlength="10"  />

                    <input type="text" id="amount_paid" value="<?=$_POST['amount_paid']?>" name="amount_paid" size="20" maxlength="16" />

                    <input type="text" id="attended_conf" value="<?=$_POST['attended_conf']?>" name="attended_conf" size="20" maxlength="10" />

            <input class="form_button" style="float:right;" type="submit" value="CLOSE WINDOW" onclick="window.opener.location.href = window.opener.location.href; window.close();">

            <input class="form_button" type="submit" value="SAVE DATA" onclick="this.form.submit();" />
        </div
    </form>

<?php

    if (isset($_POST['year']) &&
        isset($_POST['dues_paid_date']) &&
        isset($_POST['amount_paid']) &&
        isset($_POST['attended_conf']))

        {
            $member_id = (int)$_POST['member_id'];
            $year = ($_POST['year']);
            $dues = ($_POST['dues_paid_date']);
            $amount = ($_POST['amount_paid']);
            $conference = ($_POST['attended_conf']);

        $res =& $dbc->query("INSERT INTO accounting (member_id,year, dues_paid_date, amount_paid, attended_conf) VALUES ('".$member_id."','".$year."','".$dues."','".$amount."','".$conference."')",null,null);
        }
}

function edit_aid()
{
    global $dbc;
    $member_id = $_GET['memberid'];
    $aid = $_GET['aid'];

    $dbQuery = "SELECT *
                FROM accounting
                WHERE member_id='".$member_id."'
                AND aid='".$aid."'
                LIMIT 0,1";
    $dbResult = $dbc->query( $dbQuery,__FILE__,__LINE__ );
    $adata = $dbResult->fetchRow( DB_FETCHMODE_ASSOC );

    $year = ($adata['year']);
    $dues = ($adata['dues_paid_date']);
    $amount = ($adata['amount_paid']);
    $conference = ($data['attended_conf']);

    ?>

    <form name="edit contact" action="?module=members&mode=edit" method="post">

        <input type="hidden" id="member_id" name="member_id" value="<?=$member_id?>" />

        <input type="hidden" id="aid" name="aid" value="<?=$aid?>" />
        <?php //echo $member_id; ?>

            <label value="<?=$adata['Year']?>">Year
                <input type="text" id="year" name="year" value="<?=$adata['year'];?>" size="20" maxlength="20" />

            <label value="<?=$adata['dues_paid_date']?>">Dues Paid Date
                <input type="text" id="dues_paid_date" name="dues_paid_date" value="<?=$adata['dues_paid_date']?>" size="20" maxlength="20"  />
            <label value="<?=$adata['amount_paid']?>">Amount Paid
                <input type="text" id="amount_paid" name="amount_paid" value="<?=$adata['amount_paid']?>" size="45" maxlength="60" />
            <label value="<?=$adata['attended_conf']?>">Attended Conference
                <input type="text" id="attended_conf" name="attended_conf" value="<?=$adata['attended_conf']?>" size="30" maxlength="30" />

                <input class="form_button" type="submit" value="SAVE DATA" onclick="this.form.submit();" />
            </div
        </form>

    <?php
    $dbQuery = "UPDATE accounting
        SET member_id='".$member_id."', year='".$year."', dues_paid_date='".$dues."', amount_paid='".$amount."', attended_conf='".$conference."'
            WHERE member_id='".$member_id."'
            AND aid='".$aid."'";
    $dbc->query( $dbQuery,__FILE__,__LINE__ );

    $_SESSION['msg'] = 'The contact was successfully updated.';
    }

function delete_aid()
{
    global $dbc;
    $member_id = $_GET['memberid'];
    $aid = $_GET['aid'];

    $dbQuery = "SELECT *
                FROM accounting
                WHERE member_id='".$member_id."'
                AND aid='".$aid."'
                LIMIT 0,1";
    $dbResult = $dbc->query( $dbQuery,__FILE__,__LINE__ );
    $adata = $dbResult->fetchRow( DB_FETCHMODE_ASSOC );

    ?>

    /* Echo the data, confirm we want to delete */

<input class="form_button" style="float:right;" type="submit" value="REMOVE RECORD" onclick="window.opener.location.href = window.opener.location.href; window.close();">

    <?php
    $dbQuery = "DELETE FROM accounting
                WHERE member_id='".$member_id."'
                AND aid='".$aid."'";
    $dbc->query( $dbQuery,__FILE__,__LINE__ );

    $_SESSION['msg'] = 'The contact was successfully deleted.';
    }

?>

A: You're are using 'mode' in your form action as the key but you are looking for $_GET['action'] instead of $_GET['mode']. This is causing the default from your switch to run since there is no $_GET['action']


text:
Q: recv() blocks from second call I have a simple client-server app for sending files from client to server.
The client sends the file in chunks of predefined size (say 512).
The server receives the file also in chunks with the same size.
The socket on the client side isn't closed until the server sends an ack after receiving the entire file.
What happens is that:

*

*the client manages to send (send() call) the entire file, means all its chunks.

*the server manages to get (recv() call) only the first chunk, means recv() call returned 512 on the first call and on the second call it blocks.

What might be the cause for such behavior?
Here are the relevant parts.
Send\Receive functions:
int sendBuf(int sockFd, char* buf, int size){
    int bytesSent = 0;
    while (bytesSent < size){
        bytesSent += send(sockFd, buf, size, 0);
    }
    return bytesSent;
}

int sendInt(int sockFd, int num){
    uint32_t nbo_num = htonl(num);
    return sendBuf(sockFd, (char*)&nbo_num, sizeof(nbo_num));
}

int getBuf(int sockFd, char* buf, int size){
    int bytesRecv = 0;
    while (bytesRecv < size){
        bytesRecv += recv(sockFd, buf, size, 0);
    }
    return bytesRecv;
}

int getInt(int sockFd, int *num){
    int temp, bytesRecv;
    bytesRecv = getBuf(sockFd, (char*)&temp, sizeof(int));
    *num = ntohl(temp);
    return bytesRecv;
}

Server:
printf("%s     New file was created.\n",tStr);

/* get file data */
char buf[FILE_READ_CHUNK_SIZE] = {0}; // FILE_READ_CHUNK_SIZE is the maximal read amount
int bytesWritten = 0, bytesLeft = fileSize, _size=0, chunkNo=0;
bytesRecv = 0;

while (bytesLeft > 0){
    _size = (bytesLeft > FILE_READ_CHUNK_SIZE) ? FILE_READ_CHUNK_SIZE : bytesLeft;
    bytesRecv = getBuf(newsockfd, buf, _size);
    int _bytesLeft = bytesRecv;
    bytesWritten = 0;
    while (_bytesLeft > 0){
        bytesWritten = fileInfoWrite(fileInfo, buf, _bytesLeft);
        _bytesLeft -= bytesWritten;
    }
    chunkNo++;
    printf("%s     chunk #%d: received %d bytes\n",tStr , chunkNo, bytesRecv);
    bytesLeft -= bytesRecv;
}
printf("%s   Finished getting file #%d.\n",tStr ,i+1);

/* send ack to the client */
bytesSent = sendInt(newsockfd, 1);
printf("%s   Sent the client an  ack for file #%d.\n",tStr ,i+1);

Client:
/* send the entire data of the file */
printf("  Sending file data\t\t... ");
char buf[FILE_READ_CHUNK_SIZE] = {0}; // FILE_READ_CHUNK_SIZE is the maximal read amount
int numOfChunks=0, bytesRead = 0, bytesLeft = filesArr[i]->fileSize ;
bool eof = false;
bytesSent = 1;

while (bytesLeft > 0){
    bytesRead = fileInfoRead(filesArr[i], buf, &eof);
    int _bytesLeft = bytesRead;
    while (bytesSent < _bytesLeft){
        bytesSent = sendBuf(sockFd, buf, _bytesLeft);
        _bytesLeft -= bytesSent;
    }
    //printf("    chunk #%d: sent %d bytes\n", numOfChunks+1, bytesRead);
    bytesLeft -= bytesRead;
    numOfChunks++;
}
printf("Success.\n");

/* get ack from server */
int ack=0;
bytesRecv = getInt(sockFd, &ack);
if (bytesRecv!=4 || ack!=1){
    printf("Server ack is invalid.\n");
}
printf("Finished sending file #%d.\n",i+1);

A: Your sending code is wrong, it won't send more than one chunk under normal circumstances (i.e. the write writes a full chunk in one go).
This is because you don't reset bytesSent after the inner loop. Chances are it is going to be == FILE_READ_CHUNK_SIZE after the first sendBuf, and the while condition will always be false after that.
So you're only sending one buffer.
(There are probably a few more errors in your code. You'll be sending the wrong parts of the buffer if a short write happens (you'll resend the head of your buffer) for instance.)


text:
Q: Check if value exists in a column in a csv file (Python) I have a csv file and would like to be able to check if a value exists in a column.  For example:
Frame,LED,R,G,B,W
2,8,0,0,0,126
3,1,0,0,0,126
17,1,0,0,0,126
19,1,0,0,0,126
20,1,0,0,0,126

I need a line that will give some indication that '17' already exists in the 'Frame' column
This should be really easy and there are already posts and articles about how to achieve this, but I have now tried so many things which makes me think I made a mistake earlier on which is preventing the 'search' functions from working.
import os
import pandas as pd
import csv

# bin/cache/temp.csv
'''
Frame,LED,R,G,B,W
1,1,0,0,0,126
1,1,0,0,0,126
2,1,0,0,0,126
etc
'''

def this_is_the_code_used_to_add_column_names():
    if not os.path.exists('bin/cache/temp.csv'):
        with open('bin/cache/temp.csv', 'a', encoding='UTF8', newline='') as file:
            writer = csv.writer(file)
            writer.writerow(['Frame', 'LED', 'R', 'G', 'B', 'W'])

def this_is_the_code_used_to_write_and_sort_the_data():
    with open('bin/cache/temp.csv', 'a', encoding='UTF8', newline='') as file:
            writer = csv.writer(file)
            writer.writerow('var_1', 'var_2', 'ver_3', 'ver_4', 'var_5', 'var_6')

    dataFrame = pd.read_csv('bin/cache/temp.csv')
    dataFrame.sort_values(["Frame","LED"],axis=0, ascending=True,inplace=True,na_position='first') # Sorting file
    dataFrame.to_csv('bin/cache/temp.csv', sep=',', encoding='utf-8', index=False) # Write to file new data

def the_part_that_is_not_working():
    df = pd.read_csv('bin/cache/temp.csv')
    # Need a line to return True or a list with all entries with the searched-for value
    # Just any metric that will indicate if it exists
    # Ideally with a way to reference back to it like an index, but I'll cross that bridge
    print(df[df['Frame']=='1'].index.tolist())

the_part_that_is_not_working()

The code above shows every interaction with the csv file in my program, on run if the file doesn't exist it is created and the headers added.  Then lines can be written with data, followed by a sort of the entire file.  I am aiming to add a way to check if 'Frame' '17' already exists, so there are no duplicates.
I have had a plethora of outputs and errors so I didn't include all the solutions I have tried but essentially, the function named the_part_that_is_not_working is what I have been trying to get to work.
Any help will be greatly appreciated.

A: To check if value 17 in column Frame exists you can use .any():
df = pd.read_csv('your_data.csv')

out = df['Frame'].eq(17).any()
print(out)

Prints:
True

A: Turns out, the issue was that the data was being read as int not str.
The fix is to change this:
x = df[df['Frame']=='1'].index.tolist()

Into this...
x = df[df['Frame']==1].index.tolist()

This returns a list containing the index of every occurrence
Good to know that csv files don't exclusively return strings.


text:
Q: States surrounding/adjacent to a given state I want a function that gives a list of all states adjacent to a given state. How can I do this in Mathematica?

A: f[x_] := AdministrativeDivisionData[x, "BorderingStates"]

Use:
f[{"California", "UnitedStates"}]
{Entity["AdministrativeDivision", {"Oregon", "UnitedStates"}],
 Entity["AdministrativeDivision", {"Nevada", "UnitedStates"}],
 Entity["AdministrativeDivision", {"Arizona", "UnitedStates"}]}


text:
Q: Styling an Input Field How can I give the input field below the characteristics listed below?
Characteristics:
-Text typed into the field starts in the upper left corner and starts on another line (wraps?) when the right border of the field is reached.
-A scroll bar appears if the text is more than what can fit into the field.
-The text is in Courier font.
Thanks in advance,
John
echo '<form  action="http://www...com/sandbox/comments/comments2.php" method="post">
    <input type="hidden" value="'.$_SESSION['loginid'].'" name="uid">
    <input type="hidden" value="'.$submissionid.'" name="submissionid">
    <input type="hidden" value="'.$submission.'" name="submission">

    Add a comment:

    <input class="commentsubfield" name="comment" type="comment" id="comment" maxlength="1000">

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

</form>
';

Some relevant CSS:
.commentsubfield {margin-left: 30px; margin-top: 30px; width: 390px; height: 90px; border: 1px solid #999999; padding: 5px; }

A: This might sound pretty elementary, but why not just use a textarea? It does exactly what you are describing
<textarea></textarea>

textarea
edit: to better show what the textarea should look like
<textarea class="commentsubfield" name="comment" id="comment" rows="10" cols="40"></textarea>

of note, textarea does not have a maxlength attribute, to limit length in the textarea you would need to use some javascript.

A: As mentioned you should use a textarea instead of a <input type="text".
The CSS would be

.commentsubfield {
      font-family: Courier, sans-serif;
      overflow: auto; }


text:
Q: Elasticsearch constant_score wrapped inside must does not return expected result I have the following ES query :
{
    "query": {
        "bool": {
            "should": [
                {
                    "constant_score": {
                        "boost": 5,
                        "filter": {
                            "bool": {
                                "must": [
                                    {
                                        "ids": {
                                            "values": [
                                                "winnerAthlete-A"
                                            ]
                                        }
                                    },
                                    {
                                        "dis_max": {
                                            "queries": [
                                                {
                                                    "bool": {
                                                        "filter": {
                                                            "term": {
                                                                "isAthlete": true
                                                            }
                                                        }
                                                    }
                                                },
                                                {
                                                    "bool": {
                                                        "filter": {
                                                            "term": {
                                                                "isWinner": true
                                                            }
                                                        }
                                                    }
                                                }
                                            ]
                                        }
                                    }
                                ]
                            }
                        }
                    }
                },
                {
                    "constant_score": {
                        "boost": 4,
                        "filter": {
                            "bool": {
                                "must": [
                                    {
                                        "ids": {
                                            "values": [
                                                "winnerAthlete-B"
                                            ]
                                        }
                                    },
                                    {
                                        "dis_max": {
                                            "queries": [
                                                {
                                                    "bool": {
                                                        "filter": {
                                                            "term": {
                                                                "isAthlete": true
                                                            }
                                                        }
                                                    }
                                                },
                                                {
                                                    "bool": {
                                                        "filter": {
                                                            "term": {
                                                                "isWinner": true
                                                            }
                                                        }
                                                    }
                                                }
                                            ]
                                        }
                                    }
                                ]
                            }
                        }
                    }
                }
            ]
        }
    }
}

It does return the result I expect : the 2 documents winnerAthlete-A and winnerAthlete-B, assigning a score of 5.0 to winnerAthlete-A and a score of 4.0 to winnerAthlete-B.
Now, when I turn the should on the third line of the query into a must, the query does not match any document whereas I would expect the exact same result. I can't wrap my head around why. I have tried using the ES _explain keyword to understand why this query doesn't match when using must but it didn't help me.
Any idea why this query rewritten with a must does not return anything whereas the should version does return the expected result ?

A: Should works like "OR" . It will return a document which matches any of clauses.
Must works like "AND" . Document must satisfy both clauses.
Your query is not returning any result because there is no single document which has ids as winnerAthlete-A as well as winnerAthlete-B


text:
Q: How to get current prdocut category ID in Virtuemart Does anyone know what is conditional statement to detect a category id?
I need something like this:
If product is in category ID = 64 show some HTML
print_r($this->category);
TableCategories Object ( [virtuemart_category_id] => 16 [virtuemart_vendor_id] => 1 [category_name] => Chiloți, boxeri, indispensabili [slug] => chiloti-boxeri-indispensabili [category_description] => [category_template] => default [category_layout] => 0 [category_product_layout] => 0 [products_per_row] => 0 [ordering] => 3 [shared] => 0 [limit_list_step] => 0 [limit_list_initial] => 0 [metadesc] => [customtitle] => [metakey] => [metarobot] => [metaauthor] => [published] => 1 [_pkey:protected] => virtuemart_category_id [_pkeyForm:protected] => [_obkeys:protected] => Array ( [category_name] => Category in record is missing ! Can't save the record with no Category. [slug] => The given Sef Alias already exists. ) [_unique:protected] => 1 [_unique_name:protected] => Array ( [slug] => The given Sef Alias already exists. ) [_orderingKey:protected] => ordering [_slugAutoName:protected] => category_name [_slugName:protected] => slug [_loggable:protected] => 1 [_xParams:protected] => 0 [_varsToPushParam:protected] => Array ( ) [_translatable] => 1 [_translatableFields:protected] => Array ( [0] => category_name [1] => category_description [2] => metadesc [3] => metakey [4] => customtitle [slug] => slug ) [_langTag:protected] => en_gb [_tbl_lang:protected] => #__virtuemart_categories_en_gb [_updateNulls:protected] => [_tablePreFix] => c. [_tbl:protected] => #__virtuemart_categories [_tbl_key:protected] => virtuemart_category_id [_db:protected] => JFDatabase Object ( [mlTableList] => Array ( [0] => content [1] => modules [2] => menu ) [skipSetRefTables] => [orig_limit] => 0 [orig_offset] => 0 [skipjf] => 0 [translate] => 1 [tableFields:JFDatabase:private] => [profileData] => Array ( [JFDatabase::JFDatabase] => Array ( [total] => 0.0002288818359375 [count] => 1 [start] => Array ( ) ) [interceptDB::loadObjectList] => Array ( [total] => 0.0227241516113281 [count] => 62 [start] => Array ( [0] => 1397209811.22307 [1] => 1397209811.22406 [2] => 1397209811.22585 [3] => 1397209811.22628 [4] => 1397209811.23031 [5] => 1397209811.23254 [6] => 1397209811.24075 [7] => 1397209811.24117 [8] => 1397209811.24466 [9] => 1397209811.24608 [10] => 1397209811.27806 [11] => 1397209811.28038 [12] => 1397209811.28142 [13] => 1397209811.28238 [14] => 1397209811.28439 [15] => 1397209811.28616 [16] => 1397209811.28671 [17] => 1397209811.28773 [18] => 1397209811.28882 [19] => 1397209811.28975 [20] => 1397209811.29121 [21] => 1397209811.29171 [22] => 1397209811.29234 [23] => 1397209811.29328 [24] => 1397209811.29369 [25] => 1397209811.29412 [26] => 1397209811.2953 [27] => 1397209811.29915 [28] => 1397209811.29965 [29] => 1397209811.30009 [30] => 1397209811.30052 [31] => 1397209811.30295 [32] => 1397209811.304 [33] => 1397209811.30527 [34] => 1397209811.3057 [35] => 1397209811.30631 [36] => 1397209811.3067 [37] => 1397209811.30721 [38] => 1397209811.3123 [39] => 1397209811.32571 [40] => 1397209811.32638 [41] => 1397209811.32792 [42] => 1397209811.32891 [43] => 1397209811.32985 [44] => 1397209811.3308 [45] => 1397209811.33191 [46] => 1397209811.33233 [47] => 1397209811.333 [48] => 1397209811.33367 [49] => 1397209811.33744 [50] => 1397209811.33793 [51] => 1397209811.3384 [52] => 1397209811.33884 [53] => 1397209811.33928 [54] => 1397209811.34905 [55] => 1397209811.3519 [56] => 1397209811.35311 [57] => 1397209811.35398 [58] => 1397209811.35685 [59] => 1397209811.35732 ) ) [JFDatabase::getTableName] => Array ( [total] => 0.00406312942504883 [count] => 59 [start] => Array ( ) ) [JFDatabase::setLanguage] => Array ( [total] => 0.000144720077514648 [count] => 2 [start] => Array ( ) ) [JFDatabase::loadResult] => Array ( [total] => 0.000228643417358398 [count] => 13 [start] => Array ( ) ) [JFDatabase::loadAssoc] => Array ( [total] => 0.000162124633789062 [count] => 7 [start] => Array ( ) ) [JFDatabase::loadAssocList] => Array ( [total] => 0.000132083892822266 [count] => 4 [start] => Array ( ) ) [JFDatabase::loadResultArray] => Array ( [total] => 0.000250816345214844 [count] => 14 [start] => Array ( ) ) [JFDatabase::loadRow] => Array ( [total] => 0 [count] => 2 [start] => Array ( [0] => 1397209811.30335 [1] => 1397209811.30605 ) ) ) [name] => mysqli [nameQuote:protected] => ` [nullDate:protected] => 0000-00-00 00:00:00 [dbMinimum:protected] => 5.0.4 [_database:JDatabase:private] => 7624-magazin [connection:protected] => mysqli Object ( [affected_rows] => 0 [client_info] => mysqlnd 5.0.11-dev - 20120503 - $Id: bf9ad53b11c9a57efdb1057292d73b928b8c5c77 $ [client_version] => 50011 [connect_errno] => 0 [connect_error] => [errno] => 0 [error] => [error_list] => Array ( ) [field_count] => 1 [host_info] => ns13.host-md.net via TCP/IP [info] => [insert_id] => 0 [server_info] => 5.5.32-MariaDB-log [server_version] => 50532 [stat] => Uptime: 346321 Threads: 6 Questions: 164660555 Slow queries: 35 Opens: 1823800 Flush tables: 293 Open tables: 1024 Queries per second avg: 475.456 [sqlstate] => 00000 [protocol_version] => 10 [thread_id] => 2168966 [warning_count] => 0 ) [count:protected] => 0 [cursor:protected] => mysqli_result Object ( [current_field] => [field_count] => [lengths] => [num_rows] => [type] => ) [debug:protected] => [limit:protected] => 0 [log:protected] => Array ( ) [offset:protected] => 0 [sql:protected] => SELECT `virtuemart_vendor_id` FROM `#__virtuemart_vmusers` `au` WHERE `au`.`virtuemart_user_id`="687" AND `au`.`user_is_vendor` = "1" [tablePrefix:protected] => l50ti_ [utf:protected] => 1 [errorNum:protected] => 0 [errorMsg:protected] => [hasQuoted:protected] => [quoted:protected] => Array ( ) ) [_trackAssets:protected] => [_rules:protected] => [_locked:protected] => [_errors:protected] => Array ( ) [created_on] => 2014-03-16 21:10:24 [created_by] => 685 [modified_on] => 2014-04-08 13:29:22 [modified_by] => 685 [virtuemart_media_id] => Array ( ) [haschildren] => [children] => Array ( ) [productcount] => 6 [parents] => [images] => Array ( [0] => VmMediaHandler Object ( [media_attributes] => 0 [setRole] => [file_name] => [file_extension] => [virtuemart_media_id] => 0 [_foldersToTest:VmMediaHandler:private] => Array ( [0] => /var/www/vhosts/7624/domains/maicom.md/public_html/images/stories/virtuemart/category/ [1] => /var/www/vhosts/7624/domains/maicom.md/public_html/images/stories/virtuemart/category/resized/ ) [_actions:VmMediaHandler:private] => Array ( ) [_mLocation:VmMediaHandler:private] => Array ( ) [_hidden:VmMediaHandler:private] => Array ( ) [theme_url] => http://maicom.md/components/com_virtuemart/ [virtuemart_vendor_id] => 0 [file_title] => [file_description] => [file_meta] => [file_mimetype] => [file_type] => categories [file_url] => images/stories/virtuemart/category/ [file_url_thumb] => [published] => 0 [file_is_downloadable] => 0 [file_is_forSale] => 0 [file_is_product_image] => 0 [shared] => 0 [file_params] => 0 [file_lang] => [_translatable] => [_tablePreFix] => [created_on] => [created_by] => 0 [modified_on] => [modified_by] => 0 [file_url_folder] => images/stories/virtuemart/category/ [file_path_folder] => images/stories/virtuemart/category/ [file_url_folder_thumb] => images/stories/virtuemart/category/resized/ [media_role] => file_is_displayable ) ) [file_url_thumb] => [file_url] => images/stories/virtuemart/category/ ) </div>

A: What are you trying so far ?
did you need it in details page ?
if yes then try following method. I assume you are in any of the product details page layout.
if($this->product->virtuemart_category_id == 64){

   echo 'your Custom HTML';
}
else{
 //nothing
}

Also you need to get more details about current product just use.
echo "<pre/>";
print_r($this->product);

Hope its works..


text:
Q: iPad: Better way than invisible button on background to let users exit entries? On iPad/iPhone, Do you still need to make an invisible button on background to let users exit entries?  Is there a better way to dismiss the keyboard when users click outside of an entry?

A: I use
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

in the ViewController to call resignFirstResponder on the active control from there.
// edit:
My Views contain several UITextFields; I want the keyboard to disappear when the user touches anywhere besides a TextField or the keyboard, so my ViewController has this:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [currentTextfield resignFirstResponder];
}

This causes the keyboard to disappear. (I keep track of the current textfield elsewhere.)


text:
Q: Stopping the Android adb from Android Studio Background
I'm using Android Studio connected to my phone through usb using the adb (Android Debug Bridge).
The Android Studio seems to recognize that I have connected my phone to the computer, starts the adb, and the device automatically becomes usable through Android Studio.
Issue
When I want to remove my phone, I try to eject the device using "Safely Remove Hardware" feature on Windows.
This, of course, does not work because the adb is still in use. I know how to close the adb in the terminal using adb kill-server (as stated here). However, I'm wondering if there is a way to disconnect it from Android Studio (again, without having to use the terminal view to type adb kill-server).
It seems that if it can automatically connect to the adb there should be an option to disconnect it?
EDIT: This answer suggests closing the adb is not even necessary before removing your phone. If this is true, that is an acceptable response if you can explain why. To me it seems like it would be a problem if you were writing data to the phone at the time of disconnect.

A: Ejecting is really only needed for devices that have write caching enabled, since in this case the data may still be writing even though the operation has seemingly completed (i.e. the progress dialog says the operation is complete).
As long as you are sure that ADB is not actively writing to the device, removal without ejection will have no adverse effect whatsoever. Actively reading from the device never has any adverse effect on the file system, since it is not being changed. Usually it is the reading that causes windows to fail at ejecting the device - when running Android Studio, that is generally because it is reading logcat from the device.
This how-to-geek article provides some decent information on the subject :)


text:
Q: Simple question on foreach loop question with array with 2 variables. (with code) How can I edit this foreach loop so that I will be able to use strpos to look if q is found in the label ?
The result array will contain those values.
$q may be anna or ann or reas john
<?php

$q = $_GET["q"];
if (!$q) return;

$data = Array(
    Array(
        'label' => 'anna c13',
        'category' => 'Products'
    ),
    Array(
        'label' => 'anders andersson',
        'category' => 'People'
    ),
    Array(
        'label' => 'andreas johnson',
        'category' => 'People'
    )
);

$result = array();
foreach ($data as $value) {
    array_push($result, array(
        "label" => $value["label"],
        "category" => $value["category"]
    ));
}

$json = json_encode($result);

echo $json;
?>

A: This will output every array in $data where $q is somewhere in 'label'.
   <?php

    if( !isset( $_GET["q"] )) return;
    $q = $_GET["q"];

    $data = Array(
        Array(
            'label' => 'anna c13',
            'category' => 'Products'
        ),
        Array(
            'label' => 'anders andersson',
            'category' => 'People'
        ),
        Array(
            'label' => 'andreas johnson',
            'category' => 'People'
        )
    );

    $result = array();
    foreach ($data as $value) {
        if( strpos( $value['label'], $q ) !== false ) {
            $result[] = $value;
        }
    }

    $json = json_encode($result);

    echo $json;
    ?>

A: You haven't defined keys for your $data array - so it automatically take the form of:
 array(
    0=>array(...),
    1=>array(...),
    2=>array(...)
  )

This means that you're using strtolower on an int - so that's probably why it's failing.

A: foreach ($data as $value) {
    if(strpos($value['label'], $q) !== false){
        $result[] = $value;
    }
}


text:
Q: Sets with cardinality strictly greater an c Are there any examples of uncountably infinite sets with cardinality strictly greater than c other than the power set of the set of real numbers and the sequence of strictly larger sets obtained by constructing a sequence of uncountably infinite sets by creating the power set of the predecessor set, beginning with the real numbers?  I.e., with cardinality other than c,2c,22c,...?
This question is not a duplicate of the question "What infinity is greater than the continuum?" This question asks if there are any infinite cardinal numbers that are not elements of the countably infinite set {c,2c,22c,...}. Equivalently, does N is an infinite cardinal number imply N is an element of {c,2c,22c,...}?


text:
Q: React Navigation Stack Navigator returning to the wrong route I have a react native app and I'm using react navigation. Currently I have a Stack navigator (MainNav) Nested in a Tab navigator (TabNav) which is then nested in another stack navigator (StackNav).
When I press the back button in StackNav it brings me back to a route defined in MainNav and I'm not exactly sure why... Specifically, I'm on route EDIT and if I click back (on the StackNav back button not the MainNav) it will bring me to LOGIN.
Here's my code.
MainNav (contains a tab navigator):
const MainNav = StackNavigator({
  [INIT]: { screen: InitScreen },
  [MAIN]: { screen: TabNav },
  [LOGIN]: { screen: LoginScreen }
 },
 {
   headerMode: 'float'
 });

TabNav (Contains stack nav)
const TabNav = TabNavigator({
  [READ]: { screen: StackNav },
  [UNREAD]: { screen: UnreadScreen }
}, {
//options
});

StackNav:
const StackNav = StackNavigator({
  [MESSAGE]: { screen: MessageScreen },
  [EDIT]: { screen: PostScreen }
});

Not sure if this applies but each of these navigator have their own reducer and are each connected. Should there only be one reducer for all the navigators? Thanks for the help.


text:
Q: How to create an interval of times in PHP based on a start time? I'm wondering how given a start time, I can calculate a series of time spans in intervals and execute code during that time.
For example: I start at 3:30pm and have 4, 45 minute intervals that need to be calculated based on the start time. Then between 3:00pm and 3:45pm I want to be able to check if the current time is between that span and then execute a block of code if it is.
The gist: A company wants to give out 20 gift cards during a 3 hour span. They want to give out only 5 every 45 minutes.
Any thoughts would be appreciated.

A: As Walkerneo said, the best way to do this is to use a cron job on the server and maybe store the data for the gift cards in a MySQL that will be checked when the cron runs the php with the funcions...
The other (very bad way) to do this is keep a loop inside your php file to check if it's time to give out the gift cards, but this is a VERY VERY BAD idea because of the high CPU usage in the server...
If you want to give the the gift cards when the user opens a page or buys something, it's easy, just setup a table in MySQL with the time spans where the user can get the gift cards and then when we submits the form to buy or check it's PHP should go the table and check if you're in any of the time spans.
Hope it helps...


text:
Q: AttributeError: 'module' object has no attribute 'classFactory' I'm trying to compile a cython plugin for QGIS.
The plugin is working on windows (32/64) machines but was never used on Mac before.
I compiled the cython for python as described here but there are still issues and code now returns above error.
File "/Applications/QGIS.app/Contents/MacOS/../Resources/python/qgis/utils.py", line 306, in startPlugin
                plugins[packageName] = package.classFactory(iface)
            AttributeError: 'module' object has no attribute 'classFactory'

A: I rearranged the folder structure, bringing all modules from sub folders to main folder and adjusted code accordingly. - Current problem solved.


text:
Q: Adding Regex matches to an array I'm struggling to solve a small bit of code. What the code does is to first load a CSV file, line by line (starting by line 3), and add it to an array. Then run a regex match and I want to insert the value in an array.
This is my working code, it shows a msgbox with the actual matches:
Dim file = "C:\Users\David\Desktop\mycsv.csv"
    Dim basestatisticspath = Path.GetDirectoryName(file)
    Dim statistics() As String = IO.File.ReadAllLines(file)
    'Dim x As Integer = statistics.Length
    'ReDim Preserve statistics(x)

    Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
    Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
    Dim linefilename As Match = Nothing
    Dim langmatch As Match = Nothing
    Dim filename() As String
    Dim lang() As String

    For i = 2 To UBound(statistics)
        langmatch = regexlang.Match(statistics(i))
        linefilename = regexlinefilename.Match(statistics(i))
        MsgBox(langmatch.Value & linefilename.Value)
    Next

That works well and the actual matches is what I want. So my next step was to add each match to an array to then use it to generate other files.
Therefore I ended up with this:
    Dim file = "C:\Users\David\Desktop\myscv.csv"
    Dim basestatisticspath = Path.GetDirectoryName(file)
    Dim statistics() As String = IO.File.ReadAllLines(file)
    'Dim x As Integer = statistics.Length
    'ReDim Preserve statistics(x)

    Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
    Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
    Dim linefilename As Match = Nothing
    Dim langmatch As Match = Nothing
    Dim filename() As String
    Dim lang() As String

    ' Set all value line by line
    For i = 2 To UBound(statistics)
        langmatch = regexlang.Match(statistics(i))
        linefilename = regexlinefilename.Match(statistics(i))
        lang(i) = langmatch.Value.ToString
        filename(i) = linefilename.Value.ToString
        MsgBox(langmatch.Value & linefilename.Value)

    Next

After adding the below the program crashes on that line
    lang(i) = langmatch.Value.ToString
    filename(i) = linefilename.Value.ToString

I am assuming you can add the value of a regex match to a certain position of a string, but it seems I am wrong.
I´ve been searching for an answer with no results (at least to my poor understanding).
How could I convert each of the matches to a string and add it to the i position of the array?
Thanks in advance!
UPDATE:
As @Tval explained, I solved it by including the size of the array when declaring it. Thanks!
    Dim filename(UBound(statistics)) As String
    Dim lang(UBound(statistics)) As String

A: you need to initialize the array before you can reference it or you'll get a null reference error, also you can't reference an index that doesn't exist yet or you'll get an index out of range exception.
right now your using an array with a fixed length, so if you want to add a value to it you'll have to re-declare it one index larger every time.
If you want an array of a variable length id suggest using a list, so you can just append values to it without any issues
Dim myList = New List(Of String)
For Each foo As String In bar
    myList.Add(bar)
Next


text:
Q: Possible bug in JToggleButton API? I got an example for JToggleButton from java2s. In the code, I see that a toggle button does not display text properly if the text is "West". West is shown as We.. . Everything else is okay. But there is no problem when text = "west", ie w small. Is this a bug?

Code:
import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JToggleButton;

public class MainClass {
 public static void main(String args[]) {
 JFrame f = new JFrame("JToggleButton Sample");
 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 f.add(new JToggleButton("North"), BorderLayout.NORTH);
 f.add(new JToggleButton("East"), BorderLayout.EAST);
 f.add(new JToggleButton("West"), BorderLayout.WEST);
 f.add(new JToggleButton("Center"), BorderLayout.CENTER);
 f.add(new JToggleButton("South"), BorderLayout.SOUTH);
 f.setSize(300, 200);
 f.setVisible(true);
 }
}

A: Seems to work just fine for me...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestLayout23 {

    public static void main(String[] args) {
        new TestLayout23();
    }

    public TestLayout23() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame f = new JFrame("JToggleButton Sample");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new JToggleButton("North"), BorderLayout.NORTH);
                f.add(new JToggleButton("East"), BorderLayout.EAST);
                f.add(new JToggleButton("West"), BorderLayout.WEST);
                f.add(new JToggleButton("Center"), BorderLayout.CENTER);
                f.add(new JToggleButton("South"), BorderLayout.SOUTH);
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }

        });
    }

}

A: MetalLookAndFeel - getPreferredSize isn't calculated correctly

SystemLookAndFeel

Nimbus

Substance

from code (same issue with JFrame, JPanel as container by using BorderLayout)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class MainClass {

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

            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                            "org.pushingpixels.substance.api.skin.SubstanceOfficeBlue2007LookAndFeel");
                    //UIManager.getDefaults();
                } catch (Exception e) {
                }
            }
        });

       /*try {
            //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(laf.getName())) {
                    UIManager.setLookAndFeel(laf.getClassName());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame f = new JFrame("JToggleButton Sample");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel panel = new JPanel();
                panel.setLayout(new BorderLayout());
                panel.add(new JToggleButton("North"), BorderLayout.NORTH);
                panel.add(new JToggleButton("East"), BorderLayout.EAST);
                panel.add(new JToggleButton("West"), BorderLayout.WEST);
                panel.add(new JToggleButton("Center"), BorderLayout.CENTER);
                panel.add(new JToggleButton("South"), BorderLayout.SOUTH);
                f.add(panel);
                f.pack();
                //f.setSize(300, 200);
                f.setVisible(true);
            }
        });
    }
}


text:
Q: My question is about Appending excel data from active workbook to the bottom of a master file VBA Code Help Request I am trying to append the data in MaxWB to the bottom of the data in MasterWB.
I can copy the date, open the next file, but my code has an error when I try to find the last row and add a row or offset by 1 by one row.
I believe my paste special also has an error, but I can get past the offset to test.
I am very new to VBA, but like it!
Here is my Code:
Sub Append()

Dim MaxWB As Workbook
Dim MasterWB As Workbook
Dim path As String
Dim Filename As String
Dim Lastrow As Long
Dim Rng As Range

    Set MaxWB = ActiveWorkbook

    Sheets("Final Export FTP").Select
    Range("A1:E1").Select
    Range(Selection, Selection.End(xlDown)).Select
        Selection.Copy

    Set MasterWB = Workbooks.Open("C:\Users\ka20839\Desktop\Database\336116001.csv")

    Set MasterWB = ActiveWorkbook
    Sheets("ONParamfile").Select

    Range("A1").Select

With Worksheets("ONParamfile")

    Lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
    Set Rng = .Range("A" & Lastrow)

End With

'destCell appends I tried and failed to figure out
'Range(Selection, Selection.End(xlDown)).Select.Offset (1) '.Select

    ' paste throwing an error too
   ' .Range("A" & Lastrow + 1).PasteSpecial Paste:=xlPasteValues

'save master file
    MasterWB.Close SaveChanges:=True

End Sub

A: Try to avoid selecting objects:
Sub Append()

    Dim wkbSource As Workbook, wkbTarget As Workbook
    Dim lngLastRowSource As Long, lngLastRowTarget As Long

    Set wkbSource = ActiveWorkbook

    With Worksheets("Final Export FTP")
        lngLastRowSource = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    Set wkbTarget = Workbooks.Open("C:\Users\ka20839\Desktop\Database\336116001.csv")

    With Worksheets("ONParamfile")
        lngLastRowTarget = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    wkbSource.Worksheets("Final Export FTP").Range("A1:E" & lngLastRowSource).Copy _
        wkbTarget.Worksheets("ONParamfile").Range("A" & lngLastRowTarget)

End Sub


text:
Q: how to show users list in product edit page? List all users in product edit page admin panel.
Any tutorial or guide please share.
I just created a tab in product edit page but need to show all users details in that tab.
Here's my code:
<?
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

namespace Learning\ClothingMaterial\Model\Attribute\Source;

class Material extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
    /**
     * Get all options
     * @return array
     */
    public function getAllOptions()
    {

        $roleName = "merchant";
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$roleModel = $objectManager->create('Magento\Authorization\Model\Role');
$userModel = $objectManager->create('Magento\User\Model\User');
$roleModel = $roleModel->load($roleName, 'role_name');
$option_val = [];
        if($roleModel->getId()) {
            $userIds = $roleModel->getRoleUsers();
            foreach($userIds as $userId) {
                $user = $userModel->load($userId);
                $usernames = $user->getUsername();
                $userid = $user->getId();
                $option_val['label'] =  __($userid - $usernames);
                $option_val['value'] =  __($userid.$usernames);
            }
        }
        if (!$this->_options) {
            $this->_options = [$option_val];
        }
        return $this->_options;
    }
}

A: You need to add this to your class and constructor:
protected $userFactory;
public function __construct(
    ...
    \Magento\User\Model\UserFactory $userFactory,
    ...
)
{
    ...
    $this->userFactory = $userFactory;
    ...
}

Then create a method in the same class to retrieve the role data:
public function getUserData()
{
    $user = $this->userFactory->create();
    echo '<pre>';print_r($user->getData());die;
}

You have to get user collection here and use it for dropdown.


text:
Q: Alternative to XSD.EXE in LINQ-to-XML? Can LINQ-to-XML be used in a generic way to accomlish the intent of XSD.EXE, thus avoiding the usage of XSD.EXE

A: XSD2Code @ codeplex.
I am using it in my project and works like a charm.
Link: http://xsd2code.codeplex.com/


text:
Q: Callback called after promise completion with q nodejs I am using the Q promise library for making database calls. But before promise inside first then() completes, the second then() promise is started. The code is as follows:
var promise = Q.nfcall(function(){});
promise.then(removeFromOldList(data))
    .then(addToNewList(data))
    .done();

function removeFromOldList(data) {
    console.log('removeFromOldList');

    // remove the card from old list
    DB.ListTable.findOne({ _id : data.oldId},
        function(err, snippet) {
            if(err) console.error("An error occurred");
            if (err) console.error(err);

            console.log('removed the card from old list');
        })

}

function addToNewList(data) {
    console.log('addToNewList');

    // add the card to the new list
    DB.ListTable.findOne({ _id: data.newId},
        function(err, snippet) {
            if(err) console.error("An error occurred");
            if (err) console.error(err);

            console.log('add the card to the new list');
        })

}

The console log gives me:

removeFromOldList
addToNewList
removed the card from old list add the
card to the new list

How can i make the callbacks be executed before the promise is returned.

A: The problem is the DB.ListTable.findOne calls are asynchronous, so node will go through both functions before even hitting the DB callbacks.
Can you try something like this:
var query1 = DB.ListTable.findOne({ _id : data.oldId}, function(err, snippet) {
        ...
    }).exec();
var query2 = DB.ListTable.findOne({ _id: data.newId}, function(err, snippet) {
        ...
    }).exec();
var promise = Q.nfcall(function(){});
promise
    .then(query1)
    .then(query2)
    .done();


text:
Q: comparing xmls in two folders(input and output folders) and displaying difference of each comparison using python from xmldiff import main
diff = main.diff_files ("input1.xml","output1.xml")
print (diff)

Now this is comparing input1 xml with output1 xml and displaying differences in these two xmls else null in case of no differences !!
What I looking for is ... list of xmls (input1, input2, input3....) are stored in one folder (input folder) and similarly list of xmls (output1, output2, output3...) are in another folder (output folder). I want to iterate through input folder and output folder and compare one by one each xml ....input1 with output1 xml and display difference , then input2 with output2 xml and display difference and so on.......
Hence, all xmls in input folder must be compared with their respective output xmls and display whether same or if difference exist then display those differences.

A: The methods for xmldiff seem pretty straightforward for comparing to xml files:
https://github.com/Shoobx/xmldiff
Your questions seems to have two parts, iterating through files and printing differences between corresponding xml files. The first part of the quetion is simple the second is much harder for hierarchical data.Differences are really in the eye of the beholder and I think you need to be more specific about what difference you're looking for. See: http://ilpubs.stanford.edu:8090/115/1/1995-46.pdf
If your question provided accurate naming conventions i.e. (input[i], output[i]) you should be able to iterate pretty easily.
     from xmldiff import main

     n = 5 # number of files in each folder. We'll use 5 for example. File names should correspond for i in range(n)

    for i in range(n):
        diff = main.diff_files("filepath/input{0}.xml","filepath/output{0}.xml".format(n+1)
        print(diff)

I don't know enough about xml dff specifically to help you detect specific differences consider using xmldiff.formatting.XMLFormatter(normalize=WS_NONE, pretty_print=True, text_tags=(), formatting_tags=())

A: With few modifition got the results-
for i in range(n):
        diff = main.diff_files("filepath\input{i}.xml".format(i+1),"filepath\output{i}.xml".format(i+1)
        print(diff)


text:
Q: maven deploy goal failing I am using eclipse with maven2 plugin.
When doing a Run-As -> build with a goal of 'deploy' I am getting this error:
Error message:org.codehaus.plexus.component.configurator.ComponentConfigurationException: Class 'org.apache.maven.artifact.repository.ArtifactRepository' cannot be instantiated

I'm not sure I even need to do a 'deploy', I have another build that does a 'compile' goal, and from what I have learned doing a Run-As -> Run on Server (tomcat) is enough to deploy my application locally to tomcat.
Do I need run this build 'deploy' goal to run locally, should I just delete it and use 'run on server'?

A: Running mvn deploy won't "deploy your application on Tomcat", deploy is something different here, deploy is a phase done in an integration or release environment and copies the final package to the remote repository for sharing with other developers and projects.
In other words, unless you are dealing with a remote repository to distribute your application (and this requires to configure a valid <distributionManagement/> section in your POM), just forget about deploy for now, this is not what you think it is :)
So, to run your application and "deploy it on Tomcat" from Eclipse, use Run As > Run on Server. If you want to run it from outside Eclipse, you can use mvn tomcat:run but this isn't really appropriate here (this goal is an handy way to run a webapp without importing it in a IDE). And if really you want to deploy your application on Tomcat from the command line, the Maven Tomcat plugin supports many methods for Deployment. But again, I don't think that this is what you're looking for for now.


text:
Q: I am getting the error of "ValueError: The array returned by a function changed size between calls" similar problems were not solution for my problem what I am trying to do is generating lorentzian shaped function with following code:
import numpy as np
import matplotlib.pyplot as plt
import math
from scipy.optimize import fsolve # To find the zeros
from scipy.stats import cauchy
x = np.linspace(0,70,1000)
def Lo(x, m, s):
""" Return Lorentzian line shape at x with HWHM gamma """
return (1/3.1415)*(s/((x-m)**2 + s**2))
arrl = []
for i in x:
    arrl.append(10*np.log10(Lo(i,35,0.001)))
yl = np.array(arrl)
plt.plot(x,yl);

After that I want to solve the function for 4 different value, however I get an error.
colors = ['b', 'b', 'b', 'b']
max_y = max(yl)
db = [max_y-3, max_y-10, max_y-20, max_y-30]
div = [2, 2*math.sqrt(9), 2*math.sqrt(99), 2*math.sqrt(999)]
lw = []
m = 0
for i, y in enumerate(db):
    print(i)
    print(y)
    x0 = fsolve(lambda x: yl - y, 30)
    x1 = fsolve(lambda x: yl - y, 40)
    lw.append((abs(x0 -x1)/div[m])*1000)
    m = m+1

print(lw)

I am getting the error of :
"ValueError: The array returned by a function changed size between calls"
for the line of :
x0 = fsolve(lambda x: yl - y, 30)

Can you help me solve this?


text:
Q: How to make SeekBar to change colors on different positions? I need to make SeekBar with 3 positions that will change color on each of them, green, yellow and red. For now i am still on beginning of code
<SeekBar
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:layout_marginRight="10dp"
    android:max="3"/>

seekbar[colors]

A: Ok, I think it should helps you. I created in colors.xml:
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
<color name="colorGreen">#32CD32</color>
<color name="colorYellow">#D9D919</color>
<color name="colorRed">#cc0000</color>

and in MainActivity.java I did:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    seekBar = findViewById(R.id.seekBar);
    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if(progress == 2) seekBar.setProgressDrawable(getDrawable(R.color.colorYellow));
            if(progress == 3) seekBar.setProgressDrawable(getDrawable(R.color.colorRed));

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });
}


text:
Q: How to automatically deliver /var/mail/USER to my Gmail? My cron jobs sometimes sends mail to /var/mail/USERNAME.  I normally read it by log on the Mac computer and run mail command to read and delete these mails.  But how to deliver/forward such mails to my Gmail automatically? I would like to  read such mails from different Mac computers in one Gmail account.

A: On my High Sierra (10.13.4) machine, mail honors the .forward file. Create a file in your home directory called ".forward" containing an email address. All your mail on the Mac system will be forwarded to this address.
It makes good sense to limit access to this file, with chmod.
For example (open Terminal in your home directory):
cube:~ borg$ cat > .forward
locutus@borg.org <return>
<ctrl-d>
cube:~ borg$ chmod 600 .forward

Then you can test by sending a mail to yourself, from the command line:
cube:~ borg$ mail borg
Subject: test
This is a test.
<ctrl-d>EOT
cube:~ borg$ mail
No mail for borg
cube:~ borg$

Note: this only works for forwarding MacOS system mail, not for forwarding from any of your cloud mail services. You can enter any valid e-mail address in the file.

A: To manage mail routing on *nix system you should configure your MTA.
Here is extensive manual about MTA capabilities in OSX systems


text:
Q: NSTimer not working accurately. I am trying to make a countdown timer, however I am struggling with my code. I have a UIDatePicker to select the date to countdown to, but ever every time I try to do a countdown the seconds start at 54 seconds instead of adjusting to the actual time of the device. The code is very simple and straightforward, but I am struggling to figure it out.
- (IBAction)startCountdown:(id)sender {
if (ti == 0||ti <= 0) {
    [self stopCountdown:self];
}

//Set up a timer that calls the updateTime method every second to update the label
timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                         target:self
                                       selector:@selector(updateTime)
                                       userInfo:nil
                                        repeats:YES];
}
-(void)updateTime{

//Get the time left until the specified date and convert time into seconds.
NSInteger ti = ((NSInteger)[self.datePicker.date timeIntervalSinceNow]); //this is the key part of the code.
NSInteger seconds = ti % 60;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600) % 24;
//NSInteger days = (ti / 86400);

//Update the lable with the remaining time
//self.countdownLabel.text = [NSString stringWithFormat:@"%02i days %02i hrs %02i min %02i sec", days, hours, minutes, seconds];
self.countdownLabel.text = [NSString stringWithFormat:@"%02i hrs %02i min %02i sec", hours, minutes, seconds];

}

Please help me out it would be much appreciated!
Thank you in advance friends!!

A: There is more easy way to extract time units that can prevent errors in calculations. Take a look at [NSCalendar components:fromDate:toDate:options:]
It may become:
NSDate *now = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSCalendarUnit components = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *diff = [calendar components:components fromDate:self.datePicker.date toDate:now options:0];
NSInteger seconds = [diff second];
NSInteger minutes = [diff minute];
NSInteger hours = [diff hour];