text:
Q: Bind a String value to an enum in a @RequestBody entity in Spring Boot I am using Spring Boot to write a web service. I have an entity Animal and an enum Kind that can be either Kind.DOG or Kind.CAT. The Animal class contains private Kind kind as one of its instance variables. When I make an HTTP request, I pass in a string value for kind and when the request maps to the header:
@RequestMapping(method=RequestMethod.POST, value="/create")
 public ResponseEntity<Animal> createAnimal(@RequestBody Animal animal)
I want kind to be internally converted to Kind.DOG/Kind.CAT if I am passed in either "dog" or "cat". Right now, if I pass in DOG or CAT, it works fine but if's lowercase it doesn't. Can someone tell me what to do? I tried the following:
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
    dataBinder.registerCustomEditor(Kind.class, new KindEnumConverter());
}

@RequestMapping(method=RequestMethod.POST, value="/create")
public ResponseEntity<Animal> createAnimal(@RequestBody Animal animal)

and
public class KindEnumConverter extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        setValue(Kind.valueOf(text.toUpperCase()));
    }

}

but it didn't work.

A: InitBinder won't work with @RequestBody as per my experience.
We use Spring Boot and the way I solved this problem is, I excluded all the jackson related dependencies from spring-boot-starter-web, so that I can use latest jackson.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
        </exclusion>
        <exclusion>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </exclusion>
    </exclusions>
</dependency>

And then I added the latest jackson dependencies as:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.9.1</version>
</dependency>

Now that we have the new jackson library we can just set this in the application.properties file:
spring.jackson.mapper.accept_case_insensitive_enums=true
In case you use YAML, then:
spring:
  jackson:
    mapper:
      accept_case_insensitive_enums: true

Inspiration: https://stackoverflow.com/a/44217670/1781024


text:
Q: Validate visual flow screen fields using 3rd part javascript library I am creating a Visual Flow and I have few address fields which needs to be verified via 3rd part Address Verification javascript library(Smarty Street API). I am not able to find how to invoke this javascript inside my visual flow screen.
However the same address verification API is integrated with one of my VF page but I want to implement the same inside Visual Flow.
Can someone please guide on this?

A: There is no ability to call JavaScript functions placed on your Visualforce pages from Visual Flow.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Server sometimes uses a lot more cpu for query I have a stored procedure with a quite heavy SELECT statement that includes five joins and uses FieldName LIKE '%searchterm%' on multiple columns. This query usually finishes in about 2-5 seconds. But sometimes (at seemingly random points in time) the server goes into a state where the query takes ~120 seconds to finish. This state can last from a couple of minutes to several hours. I have indications that you can end the slow state by calling DBCC FREEPROCCACHE, but I'm not completely sure. I'm using SQL Server 11.0.3153.
I've used the profiler tool to trace the server. Most of the time the query requires 900 CPU and 500 000 reads, but in the slow state it's 100 000 CPU and 7.5*10^6 reads. Even when the server is in the slow state it only seems to affect connections made by my .NET application, I can still execute the stored procedure quickly via SQL Server Management Studio.
The query looks something like this:
SET @search = REPLACE(@search, ' ', '%');
SET @search = '%' + @search + '%';

SELECT
    ...
FROM
    Table1 t1,
    Table1 t2
    /* The real query uses 3 more joined tables left out here */
WHERE
    t1.id = t2.t1_id
    AND (
        (t1.col1 LIKE @search)
        OR (t2.col1 LIKE @search)
        OR (t1.id IN (SELECT t1_id FROM Table3 t3 WHERE t3.col1 LIKE @search)
        )
ORDER BY
    SomeCol DESC,
    SomeOtherCol DESC
OFFSET @row_offset ROWS FETCH NEXT @row_count ROWS ONLY

Can anyone tell me what's going on here? What can be the cause of the inconsistent behavior?

A: That sounds like it is using an inappropriate query plan. There are two obvious paths this query could take and it is presumably deciding between them depending on the values of @row_offset and @row_count: for a small offset it is probably better to scan SomeCol,SomeOtherCol in order and apply the complex filtering clauses (in the WHERE and JOIN ON clauses) to each row until enough have been found to satisfy @row_count. For many other circumstances this would be a terribly bad approach.
To be more specific we'd need details on those other tables, the indexes/keys, and the sort of size/distribution of each table's contents.
What I suspect is happening is a cached query plan is being used when that plan is inappropriate for the current input values. When you run DBCC FREEPROCCACHE the cache is purged so it is forced to create a new plan and use that.
You can try the RECOMPILE hint by appending OPTION(RECOMPILE) to direct SQL and WITH RECOMPILE on the stored procedure definition if it is a procedure rather than an ad-hoc query - this tells SQL Server not to bother checking the procedure cache and always generate a fresh plan. This of course means that you lose the benefit on occasions where using a cached plan instead of having to reassess stats and replan would have been faster - this may be an acceptable tradeoff but obviously you need to benchmark and make sure you are not degrading overall performance more than is acceptable (if so you'll need a different strategy)).


text:
Q: Regex lookahead part of group accepted I'm using regex in powershell 5.1.
I need it to detect groups of numbers, but ignore groups followed or preceeded by /, so from this it should detect only 9876.
[regex]::matches('9876 1234/56','(?<!/)([0-9]{1,}(?!(\/[0-9])))').value

As it is now, the result is:
9876
123
6
More examples: "13 17 10/20" should only match 13 and 17.
Tried using something like (?!(\/([0-9]{1,}))), but it did not help.

A: You may use
\b(?<!/)[0-9]+\b(?!/[0-9])

See the regex demo
Alternatively, if the numbers can be glued to text:
(?<![/0-9])[0-9]+(?!/?[0-9])

See this regex demo.
The first pattern is based on word boundaries \b that make sure there are no letters, digits and _ right before and after an expected match. The second one just makes sure there are no digits and / on both ends of the match.
Details

*

*(?<![/0-9]) - a negative lookbehind making sure there is no digit or / immediately to the left of the current location

*[0-9]+ - one or more digis

*(?!/?[0-9]) - a negative lookahead making sure there is no optional / followed with a digit immediately to the right of the current location.


text:
Q: Find the minimum value of an expression. Given that $x,y,z>0$ and $x\geq max${$y,z$}. Find the minimum value of:
$$A=\frac{x}{y}+2\sqrt{1+\frac{y}{z}}+3\sqrt[3]{1+\frac{z}{x}}.$$
This expression doesn't seem very "beautiful", I guess. And I have no idea what to do with this. What's your take on this?

A: First, we notice that $A(x,y,z)$ does not change if you multiply all arguments by the same positive number: $$A(\alpha\,x,\alpha\,y,\alpha\,z)=A(x,y,z)\quad\mbox{for any $\alpha>0$.}$$
Therefore we can impose a constraint $z=1$ without changing the answer and reduce the problem to that of finding the minimum of
$$A(x,y,1) = \frac{x}{y}+2\sqrt{1+y}+3\sqrt[3]{1+\frac{1}{x}}.$$
Now, taking partial derivative with respect to $x$, we get
$$\frac{\partial A(x,y,1)}{\partial x}=\frac{1}{y}-\frac{1}{x^2}\left(1+\frac{1}{x}\right)^{-\frac{2}{3}}$$
which is positive in the domain $x,y>0$, $x\ge \max(y,1)$.  Similar computation for $\frac{\partial A(x,y,1)}{\partial y}$ shows that it is negative in the same domain and therefore the minimum is achieved when $x$ is minimized to $x=1$ and $y$ is maximized to $y=x=1$:
$$\min A = A(1,1,1) = 1+2\sqrt{2}+3\sqrt[3]{2}.$$
Thanks Rob Pratt for pointing out the role of the domain.


text:
Q: Total capacitance for a ladder network with two capacitances Is there a standard formula to determine the total capacitance of:

simulate this circuit – Schematic created using CircuitLab
Where C1 and C are different capacitances and for n number of C1 and C.
Maybe one can create an equivalent circuit design, but I can't quite see it.
Thanks!

A: For each segment, we have two capacitors in series which are then in parallel with a third, so we have a total capacitance of:
$$C_{leg} = C_1 + \frac{1}{\frac{1}{C_2} + \frac{1}{C_1}}$$
We can generalise this into an iterative formula for each leg if we assume that the leg consists of only the two capacitors, and the final leg consists of just \$C_1\$:
$$C_{leg}(m+1) = C_1 +  \frac{1}{\frac{1}{C_2} + \frac{1}{C_{leg}(m)}} \quad\quad\quad\mathrm{where}\quad C_{leg}(0)=C_1$$
You can then simply iterate the formula \$n\$ times until you have the total capacitance - i.e. \$C_{total} = C_{leg}(n)\$.

Just for the fun of it, you will essentially you end up calculating iteratively something like this (example for n=4):
$$C_{total} = C_1 + \cfrac{1}{\frac{1}{C_2} + \cfrac{1}{C_1
          + \cfrac{1}{\frac{1}{C_2} + \cfrac{1}{C_1
          + \cfrac{1}{\frac{1}{C_2} + \cfrac{1}{C_1 + \cfrac{1}{\frac{1}{C_2} + \frac{1}{C_1}}}}}}}}$$

A: As a supplement to the answer by Tom Carpenter, if you have an infinite chain and the series converges, then
$$ C_{leg}(m + 1) \rightarrow C_{leg}(m) $$
$$C_{leg} = C_1 + \frac{1}{\frac{1}{C_2} + \frac{1}{C_{leg}}}$$
$$ \Rightarrow C_{leg} = \frac{1}{2}(\sqrt{4 C_1 C_2 + C_1^2} - C_1) $$

A: There is probably a compact form based on z-transform generating functions. See the SE question and answer on a related resistor ladder network: Closed form expression for a resistor ladder network.
Also see the catalogue of generating functions at : http://www.lacim.uqam.ca/~plouffe/articles/MasterThesis.pdf

A: If we write
$$\begin{pmatrix}U_1\\I_1\end{pmatrix}=\begin{pmatrix}1&Z\\Y&1\end{pmatrix}^n\begin{pmatrix}U_2\\I_2\end{pmatrix}$$
with $$Z = \frac{1}{2 \pi jf C_2}$$ and $$Y = 2 \pi jf C_1$$
then
$$\begin{pmatrix}1&Z\\Y&1\end{pmatrix}^n=\frac{1}{2\sqrt{YZ}}\begin{pmatrix}\sqrt{Z}&-\sqrt{Z}\\\sqrt{Y}&\sqrt{Y}\end{pmatrix}\begin{pmatrix}(1+\sqrt{YZ})^n&0\\0&(1-\sqrt{YZ})^n\end{pmatrix}\begin{pmatrix}\sqrt{Y}&\sqrt{Z}\\-\sqrt{Y}&\sqrt{Z}\end{pmatrix}$$
and now I have a headache from the diagonalization and somebody else should take it from there.


text:
Q: java.lang.OutOfMemoryError: Java heap space Hibernate entityIsPersistent I am reading 5gb of XML file using the below code and processing that data into Database using spring dataJpa, this below is just sample logic we are closing the inpustream and aswell xsr object.
 XMLInputFactory xf=XMLInputFactory.newInstance();
 XMLStreamReader xsr=xf.createXMLStreamReader(new InputStreamReader(new FileInputStream("test.xml"))

i have configured the max 8GB(ie -xms7000m and -xmx8000m) of heap memory But its getting the below hibernate heap issue when saving the data. it inserted around 700000 data total of 2100000
[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.OutOfMemoryError: Java heap space] with root cause

java.lang.OutOfMemoryError: Java heap space
    at java.base/java.util.IdentityHashMap.resize(IdentityHashMap.java:472) ~[na:na]
    at java.base/java.util.IdentityHashMap.put(IdentityHashMap.java:441) ~[na:na]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsPersistent(DefaultPersistEventListener.java:159) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:124) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.internal.SessionImpl$$Lambda$1620/0x00000008010a3040.applyEventToListener(Unknown Source) ~[na:na]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:113) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.internal.SessionImpl.persistOnFlush(SessionImpl.java:765) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.spi.CascadingActions$8.cascade(CascadingActions.java:341) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:492) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:416) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:525) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:456) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:419) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:218) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:151) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEventListener.java:158) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:148) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:81) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.internal.SessionImpl$$Lambda$1597/0x0000000801076040.accept(Unknown Source) ~[na:na]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1362) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:453) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3212) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2380) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.22.Final.jar:5.4.22.Final]
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534) ~[spring-orm-5.2.10.RELEASE.jar:5.2.10.RELEASE]

As per the above trace logs it seems some issue with hibernate save casacade , but not able to figured out , below are the entity classes which uses to save the data in databse.
@Data
@EqualsAndHashCode
@Builder(toBuilder = true)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class UMEnityPK implements Serializable {
    private static final long serialVersionUID=1L;

    private String batchId;
    private Long batchVersion;
    private BigInteger umId;
}

@Data
@Builder(toBuilder = true)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode(of = {"batchId", "batchVersion", "umId"})
@Entity
@Table(name ="um_base")
@IdClass(UMEnityPK.class)
public class UMBase {

    @Id private String batchId;
    @Id private Long batchVersion;
    @Id private BigInteger umId;

    private String firstName;
    private String lastName;
    private String umType;
    private String umLevel;

    @OneToMany(mappedBy = "umBase", cascade = CascadeType.ALL)
    private List<UMAddress> umAddresses;

    @OneToMany(mappedBy = "umBase", cascade = CascadeType.ALL)
    private List<UMIdentifier> umIdentifiers;

    @OneToOne(mappedBy = "umBase", cascade = CascadeType.ALL)
    private UMHierarchy umHierarchy;
}

@Data
@Builder(toBuilder = true)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode(of = {"id"})
@Entity
@Table(name = "um_identifier")
public class UMIdentifier {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "um_address")
    @SequenceGenerator(name = "um_address", sequenceName = "SEQ_UM_ADDRESS", allocationSize = 1)
    private Long id;

    private String idValue;
    private String idType;
    private String groupType;

    @ManyToOne
    @JoinColumns({
            @JoinColumn(name = "BATCH_ID", referencedColumnName = "batchId"),
            @JoinColumn(name = "BATCH_VERSION", referencedColumnName = "batchVersion"),
            @JoinColumn(name = "UM_ID", referencedColumnName = "umId")
    })
    private UMBase umBase;
}

@Data
@Builder(toBuilder = true)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode(of = {"batchId", "batchVersion", "umId"})
@Entity
@Table(name ="um_hierarchy")
public class UMHierarchy {

    @Id
    private String batchId;
    @Id private Long batchVersion;
    @Id private BigInteger umId;

    private String hierarchyTpe;
    private String umStatusCode;
    private String immediateParentId;
    private Date hierarchyDate;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumns({
            @JoinColumn(name = "BATCH_ID", referencedColumnName = "batchId"),
            @JoinColumn(name = "BATCH_VERSION", referencedColumnName = "batchVersion"),
            @JoinColumn(name = "UM_ID", referencedColumnName = "umId")
    })
    private UMBase umBase;
}

@Data
@Builder(toBuilder = true)
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PRIVATE)
@EqualsAndHashCode(of = {"id"})
@Entity
@Table(name = "um_address")
public class UMAddress {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "um_address")
    @SequenceGenerator(name = "um_address", sequenceName = "SEQ_UM_ADDRESS", allocationSize = 1)
    private Long id;
    private String addressType;
    private String addressLine1;
    private String getAddressLine2;
    private String city;
    private String state;
    private String postalCode;
    private String country;

    @ManyToOne
    @JoinColumns({
            @JoinColumn(name = "BATCH_ID", referencedColumnName = "batchId"),
            @JoinColumn(name = "BATCH_VERSION", referencedColumnName = "batchVersion"),
            @JoinColumn(name = "UM_ID", referencedColumnName = "umId")
    })
    private UMBase umBase;
}

Is there any issues with hibernate entity mapping which eating of the memory

A: After checking the heap dump, the issue is with the org.hibernate.engine.StatefulPersistenceContext -> org.hibernate.util.IdentityMap  memory leak , so used the below way and worked fine , create a custom JPARepository and have below sample method logic.
public <S extends T> void saveInBatch(Iterable<S> entities) {

        if (entities == null) {
            return;
        }

        EntityManager entityManager = entityManagerFactory.createEntityManager();
        EntityTransaction entityTransaction = entityManager.getTransaction();

        try {
            entityTransaction.begin();

            int i = 0;
            for (S entity : entities) {
                if (i % batchSize == 0 && i > 0) {
                    entityTransaction.commit();
                    entityTransaction.begin();

                    entityManager.clear();
                }

                entityManager.persist(entity);
                i++;
            }
            entityTransaction.commit();
        } catch (RuntimeException e) {
            if (entityTransaction.isActive()) {
                entityTransaction.rollback();
            }

            throw e;
        } finally {
            entityManager.close();
        }
    }
}

A: When dealing with converting datasets that big you need to do that in batches. Read 100 records from the xml, convert them to entities, save each of them with em.persist(record), then call em.flush() and  em.clear() to remove them from Hibernate, then clear them from your local collection, then manually invoke the garbage collector using System.gc(). You may even want to use Hibernate's batch processing as described in this tutorial.
In pseudocode this would be:
boolean finished = false;
List<Entity> locals = new ArrayList<>(100);
while (!finished) {
  for (int records = 0; records < 100; records++) {
    Entity ent = readEntityFrom(xml);
    // readEntity function must return null when no more remain to read
    if (ent == null) {
      finished = true;
      break;
    }
    locals.add(ent);
  }
  for (Entity ent : locals) em.persist(ent);
  em.flush(); // send any that are still waiting to the database
  em.clear(); // remove references Hibernate holds to these entities
  locals.clear(); // remove references we hold to these entities
  // now all these entity references are weak and can be garbage-collected
  System.gc(); // purge them from memory
}

Also you may want to manually begin and commit a transaction around each insert loop to ensure the database isn't holding everything for your entire import, or it might run out of memory instead of your java application.


text:
Q: How the cron timing is working? Suppose, current time is 11:42 and i have setup one cron file to run at every 5 minutes.
Then this file will run at which time 11:47 or 11:45?
So basically i am trying to understand that how the cron timing is work?
Edit : it was ran at 11:45, but i don't know the reason behind it
Cron Configuration :
*/5 * * * * wget -O /dev/null http://XXX/index.php?r=controller/action

A: As you know, cron will run jobs at a specific time.
A cron job will not use the time it was started, only the configuration matters. This means a cron job set to every 5 minutes (like your */5 * * * *) will only ever run at times ending with 0 or 5 (eg: 12:00, 12:05, 12:10), regardless of the time you run it. This makes sense because we want to schedule a job for a specific time.
If you really need a job to run every 5 minutes, with an offset (eg: 11:42, 11:47, 11:52) you will have to give a list in the configuration.
instead of (*/5 * * * *) you would need to use:
(2,7,12,...,57 * * * *), filling ... with all the other numbers.


text:
Q: automatic scrolling when using keytable plugin I'm using Allan Jardine's KeyTable plugin in a plain html table. It's a big table so it scrolls horizontally and vertically. The problem I'm facing right now is that it doesn't scroll automatically when the focused cell is out of sight (one knows the current cell because it has the .focus class).
How do I make it scroll automatically when using the keyboard?
Thanks.

A: I personally use the nice scrollintoview plugin for jQuery: https://github.com/litera/jquery-scrollintoview for this.
My own code, which is nice but still not perfect, works like this:
var anim_element = $();
var keys = new KeyTable( {
  "table": t,
  focus: false,
});
keys.event.focus( null, null, function(cell, posx, posy) {
  /* handler for focus events on all cells ... */
  anim_element.stop();
  var row = $(cell).parents("tr").first();
  anim_element = row.stop().scrollintoview({ duration: 50, direction: 'y'});
});

Note that you have to stop the animation when the next focus event starts but to do so you have to have the previous animation element stored somewhere. This is the part of my code that's still a little rough.
Hope it helps.

A: Try Using scrollX and scrollY in the DataTable Options
scrollX: true, // For Horizontal Scrolling
scrollY: "600px" // For Verticle Scrolling (define the pixels when scrolling should Start)

Reference :
https://datatables.net/reference/option/scrollX
https://datatables.net/reference/option/scrollY
It worked for me. I also checked it using KeyTable and it worked fine.


text:
Q: MPMoviePlayerViewController, remove quicktime symbol/add background image? I have an MPMoviePlayerViewController that plays audio. I would like to remove the Quicktime logo and/or add a custom background image to the player but keep the playback controls. I swear I have done this before prior to iOS 5 but I can't re-figure it out! Things I have tried:
-Adding a subview to MPMoviePlayerViewController. Puts the subview OVER the playback controls, not good.
-setBackgroundColor of the moviePlayer with a patternimage. Doesn't do anything.
-setView on the entire MPMoviePlayerViewController. As expected, the playback controls and navigation bar are gone. I suppose this could work but I'd need to recreate all the playback controls manually, but I'd really rather not.
Can anyone shed some light?

A: Check out the MPMoviePlayerController property backgroundView.
From the MPMoviePlayerController Class Reference;

backgroundView
A customizable view that is displayed behind the movie
  content. (read-only)
@property (nonatomic, readonly) UIView *backgroundView
Discussion This
  view provides the backing content, on top of which the movie content
  is displayed. You can add subviews to the background view if you want
  to display custom background content.
This view is part of the view hierarchy returned by the view property.
Availability Available in iOS 3.2 and later. Declared In
  MPMoviePlayerController.h

Try something like this (assuming that your instance of the MPMoviePlayerController is called moviePlayerController):
patternView = [[UIView alloc] initWithFrame:self.view.bounds];
patternView.backgroundColor = [UIColor redColor];
[moviePlayerController.backgroundView addSubview:patternView];
[patternView release];

A: Till's answer is correct for iPhoneOS 3.  This has changed in iOS 4 and 5.
Apple has now added a readonly property to MPMoviePlayerViewController exposing a MPMovieController.  The MPMovieController has a backgroundView that should be used.
Now you will want to do something like this:
patternView = [[UIView alloc] initWithFrame:self.view.bounds];
patternView.backgroundColor = [UIColor redColor];
[moviePlayerController.moviePlayer.backgroundView addSubview:patternView];
[patternView release];


text:
Q: Prove that the function is Riemann Integrable Question: Let $S$ be the sawtooth function defined by
$$
S(u) = \left\{
        \begin{array}{ll}
            u & \quad 0 \leq u \leq 1 \\
            u - 1 & \quad 1 < u \leq 2
        \end{array}
    \right.
$$
Prove that $S$ is Riemann integrable.
My Attempt
If $S : [0, 2]\rightarrow\mathbb{R}$, we want to show that $S$ is Riemann integrable.
We first need to show that $S_1 : [0, 1] \rightarrow\mathbb{R}$ where $S(u) = u$ is Riemann integrable. Suppose we let $P_n$ be a partition of the interval $[0, 1]$. Then we will have
$$P_n = \left\{[0, \frac{1}{n}],[\frac{1}{n}, \frac{2}{n}],...,[\frac{n-1}{n}, 1]\right\}$$
Then it follows that
\begin{align*}
u_i - u_{i - 1} &= \frac{1}{n} \\
m_i &= \frac{i - 1}{n} \\
M_i &= \frac{i}{n}
\end{align*}
Then from here, we can say that for a given $\epsilon > 0$
\begin{align*}
U(S_1, P) - L(S_1, P) &= \sum_{i = 1}^n M_i(u_i - u_{i - 1}) - \sum_{i = 1}^n m_i(u_i - u_{i - 1}) < \epsilon \\
\end{align*}
I am not exactly sure if I am on the right track, and I am not exactly sure how I should proceed from here.

A: Here is an easy way to do this.
Just observe that for any $x,y\in [0,2]$ for any $\epsilon >0$ there is a $\delta >0$ such that
$$
|S(x) - S(y)| < \epsilon/2
$$ whenever $|x - y| < \delta $
Consider the partition $P_n$ as you considered in question such that $1/n <\delta$. Since $S$ is continous in each interval it attains maximum and minimum there, so $M_i = S(a_i)$ and $m_i = S(b_i)$. Now just observe that $|a_i - b_i| < \frac{1}{n} < \delta$ which implies that $M_i - m_i < \epsilon /2$.
So $U(S,P_n) - L(S,P_n) = \sum_{i=1}^{n} (M_i - m_i)(u_i - u_{i-1}) < \frac{\epsilon}{2} (u_n - u_0) = \epsilon$


text:
Q: Django datetime field compered to now Please help.
I have this in my models.py
class Notificator(models.Model):
    headline = models.CharField(max_length=255, default='')
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()
    bought_from = models.ManyToManyField(VigneteSeller, blank=True)
    start_alert = models.DateTimeField()
    start_notifying_me = models.IntegerField(default=20)
    def save(self):
        d = timedelta(days=self.start_notifying_me)
        if not self.id:
            self.start_alert = self.end_date - d
            super(Notificator, self).save()

    @classmethod
    def starter(cls):
        ready = []
        if timezone.now() >= cls.start_alert:
            ready.append(cls.headline)
        return ready

    def __str__(self):
        return self.headline

All I want is to collect all instanceses from "start_alert" field compare it with timezone.now and return it with the starter function, and I am stuck.

A: This will return all instances with a start time greater than now
from datetime import datetime

Notificator.objects.filter(start_alert__gte=datetime.now())


text:
Q: Localhost has just stopped working (using xampp) I installed Xampp to use for local development of a Drupal site. Its been working fine out of the box until now.
The main Xampp localhost welcome menu loads, however my subdirectory (localhost/drupal) doesn't. It just spins in the browser for ages and nothing happens. Just a blank screen.
I've tried the edit people suggest in the hosts file but that hasn't work and I'm getting no errors so not sure what to do.
Anyone have any ideas what might be wrong?
PS I'm running Windows 7
edit:
Log files:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 123731968 bytes) in C:\xampp\apps\drupal\htdocs\sites\all\themes\directory\node--job.tpl.php on line 41

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 123731968 bytes) in C:\xampp\apps\drupal\htdocs\sites\all\themes\directory\node--job.tpl.php on line 41

[Tue Nov 05 20:52:07.242454 2013] [ssl:warn] [pid 8432:tid 260] AH01909: RSA certificate configured for www.example.com:443 does NOT include an ID which matches the server name

[Tue Nov 05 20:52:07.331459 2013] [core:warn] [pid 8432:tid 260] AH00098: pid file C:/xampp/apache/logs/httpd.pid overwritten -- Unclean shutdown of previous Apache run?

[Tue Nov 05 20:52:07.820487 2013] [ssl:warn] [pid 8432:tid 260] AH01909: RSA certificate configured for www.example.com:443 does NOT include an ID which matches the server name

[Tue Nov 05 20:52:07.898492 2013] [mpm_winnt:notice] [pid 8432:tid 260] AH00455: Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.16 configured -- resuming normal operations

[Tue Nov 05 20:52:07.898492 2013] [mpm_winnt:notice] [pid 8432:tid 260] AH00456: Server built: Feb 23 2013 13:07:34

[Tue Nov 05 20:52:07.898492 2013] [core:notice] [pid 8432:tid 260] AH00094: Command line: 'c:\\xampp\\apache\\bin\\httpd.exe -d C:/xampp/apache'

[Tue Nov 05 20:52:07.905492 2013] [mpm_winnt:notice] [pid 8432:tid 260] AH00418: Parent: Created child process 7588

[Tue Nov 05 20:52:08.882548 2013] [ssl:warn] [pid 7588:tid 272] AH01909: RSA certificate configured for www.example.com:443 does NOT include an ID which matches the server name

[Tue Nov 05 20:52:09.467582 2013] [ssl:warn] [pid 7588:tid 272] AH01909: RSA certificate configured for www.example.com:443 does NOT include an ID which matches the server name

[Tue Nov 05 20:52:09.534585 2013] [mpm_winnt:notice] [pid 7588:tid 272] AH00354: Child: Starting 150 worker threads.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 123731968 bytes) in C:\xampp\apps\drupal\htdocs\sites\all\themes\directory\node--job.tpl.php on line 41

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 123731968 bytes) in C:\xampp\apps\drupal\htdocs\sites\all\themes\directory\node--job.tpl.php on line 41


text:
Q: how to disable rolling effect and shadow effect in UIPICKER VIEW in ios? i am developing the one example of UIPICKERVIEW and i want to disable or off the shadow effect and rolling effect but not able to do it.do you have any idea for that ?
Source code:
pickerViewController.h file
#import <UIKit/UIKit.h>

@interface pickerViewController : UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
{
    UIPickerView *languageSelect;
    NSMutableArray *pickerData;
}
@property (nonatomic, retain) UIPickerView *languageSelect;
@property (nonatomic, retain)  NSArray *pickerData;
@end

pickerViewController.m file
#import "pickerViewController.h"

@interface pickerViewController ()

@end

@implementation pickerViewController
@synthesize languageSelect, pickerData;
- (void)viewDidLoad
{
    [super viewDidLoad];
    pickerData= [[NSMutableArray alloc]     initWithObjects:@"English",@"Spanish",@"French",@"Greek",
             @"Japaneese",@"Korean",@"Hindi",@"English",@"Spanish",@"French",@"Greek",
             @"Japaneese",@"Korean",@"Hindi", nil];

    languageSelect = [[UIPickerView alloc] initWithFrame:CGRectMake(10, 50, 300, 1000)];
    languageSelect.showsSelectionIndicator = YES;
    languageSelect.hidden = NO;
    languageSelect.delegate = self;
    [self.view addSubview:languageSelect];

}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView; {
    return 1;
}

    - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:   (NSInteger)component;
{
    return [pickerData count];
}
    - (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {

UILabel *pickerLabel = (UILabel *)view;

    NSString* labelText = [NSString stringWithFormat:@"%@",[pickerData objectAtIndex:row]];

if (pickerLabel == nil) {
    CGSize size = [labelText sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:CGSizeMake(250, 216) lineBreakMode:NSLineBreakByCharWrapping];
    CGRect frame = CGRectMake(0.0, 0.0, 250, size.height + 25);
    pickerLabel = [[UILabel alloc] initWithFrame:frame];
    [pickerLabel setTextAlignment:NSTextAlignmentLeft];
    [pickerLabel setBackgroundColor:[UIColor clearColor]];
    [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    [pickerLabel setLineBreakMode:NSLineBreakByWordWrapping];

        // trying to mess with the UIView of the row itself... to no avail
    //CGRect rowFrame = view.frame;
    //NSLog(@"%f",rowFrame.size.height);
    //rowFrame.size.height = size.height + 25;
    //view.frame = rowFrame;
}

[pickerLabel setText:[pickerData objectAtIndex:row]];

//NSLog(@"%f",[pickerView rowSizeForComponent:component].height);

return pickerLabel;
}

-(NSString*) pickerView:(UIPickerView*)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [pickerData objectAtIndex:row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;
{

}

Output:

I want to do something like this...!!

A: This is a lot of custom work. If you want to achieve that look, you are probably better of trying to use a UITableView. You'll still have to put in quite some effort though.

A:
In pic you can see structure of UIPickerView.
  http://i.stack.imgur.com/QFAKV.png

Maybe removing some layers help you
  http://i.stack.imgur.com/C2xDO.png


text:
Q: Iterate data in anonymous variable I have a DataTable containing some data, and I am going to fetch some data from it using Linq to datatable.
The query looks like this:
var requiredData=dt.AsEnumerable()
  .Where(row => row.Field<byte>("id") == 1)
  .Select(x=> {
    id = x.Field<int>("id"),
    YYYYY = x.Field<string>("ColumnName2"),
    ZZZZZ = x.Field<string>("ColumnName3")
  }
);

Now, Please how do I iterate-through "requiredData"?

A: You could use a foreach loop:
foreach (var item in requiredData)
{
    // TODO: use item.id, item.YYYYY and item.ZZZZZ here
}


text:
Q: personal letters with koma-script KOMA-Script provides  the scrlttr2 and scrletter classes, which, in contrast to the standard class letter,
has the flexible design common to other KOMA-Script classes.
One observation about letter is the very good results, with no configuration,  for personal letters, for example, letters with just a date, salutation, body, and signature.
The design of KOMA-Script letter classes appears to emphasize   templates called Letter Class Options, of which several are included in the distribution, representing formatting standards for business correspondence in various countries. Among these, DIN,
representing a definition given by the German Institute for the Standardization, appears to be loaded by default if none is given explicitly. Such design seems to exclude the possibility of creating a letter with formatting not related to some business standard, except of course through  creating an LCO representing some preferred formatting for a personal letter.
For example,
the KOMA-Script manual (Table 4.19) describes the DIN Letter Class Option set as follows:

parameters for letters on A4 paper, complying with German standard DIN 676;suitable for window envelopes in the sizes C4, C5, C6, and C6/5 (C6 long).

Naturally, windowed envelopes are not generally useful for personal letters, nor is it useful that such a requirement would constrain the formatting of the letter.
An obvious suggestion is not to use KOMA-Script for personal letters, in preference to the standard class, but I have come to value the comparatively flexible design of KOMA-Script classes over the standard ones.
What might be a good way to invoke either scrlttr2 or scrletter without including any formatting details specifically targeted for commercial correspondence?
A minimal example of a personal letter might be one that includes a date, a salutation, a body, and a closing, but not necessarily any address information.

A: You can disable foldmarks, addrfield and firsthead using foldmarks=false,addrfield=false,firsthead=false as class options (with class scrlttr2) or package options (with package scrletter) or using \KOMAoptions{foldmarks=false,addrfield=false,firsthead=false}.
\documentclass{scrlttr2}
\KOMAoptions{foldmarks=false,addrfield=false,firsthead=false}
\usepackage{blindtext}% only for dummy text
\begin{document}
\begin{letter}{}
\opening{Hello,}
\blindtext
\closing{Bye}
\end{letter}
\end{document}

To remove the vertical space reserved for the addresse field add:
\addtoplength[-]{refvpos}{\useplength{toaddrheight}}

If you set the variable fromname and do not want that \closing adds the value of fromname then clear the variable signature:
\setkomavar{fromname}{Max Mustermann}
\setkomavar{signature}{}

Example:
\documentclass{scrlttr2}
\KOMAoptions{foldmarks=false,addrfield=false,firsthead=false}
\addtoplength[-]{refvpos}{\useplength{toaddrheight}}
\setkomavar{fromname}{Max Mustermann}
\setkomavar{signature}{}
\usepackage{blindtext}% only for dummy text
\begin{document}
\begin{letter}{}
\opening{Hello,}
\blindtext
\closing{Bye}
\end{letter}
\end{document}

Note, that most of the predefined lco files expecte paper size a4, eg. the preloaded DIN.lco. If you use another paper sizes, you will get a warning. If you do not need a special position of a letter element (like the position of the address field for windowed envelopes) you can ignore this warning. For paper=letter you can also load letter option UScommercial9 or UScommercial9DW. If you use another paper size, eg. paper=a5, and need special positions of a letter elements, then you have to define an own lco file.


text:
Q: How can I build an AST using ANTLR4? I have an ANTLR3 grammar that builds an abstract syntax tree. I'm looking into upgrading to ANTLR4. However, it appears that ANTLR4 only builds parse trees and not abstract syntax trees. For example, the output=AST option is no longer recognized. Furthermore neither "AST" nor "abstract syntax" appears in the text of "The Definitive ANTLR4 reference".
I'm wondering if I'm missing something.
My application currently knows how to crawl over the AST produced by ANTLR3. Changing it to process a parse tree isn't impossible but it will be a bit of work. I want to be sure it's necessary before I start down that road.

A: ANTLR 4 produces parse trees based on the grammar instead of ASTs based on arbitrary AST operators and/or rewrite rules. This allows ANTLR 4 to automatically produce listener and visitor interfaces that you can implement in the code using your grammar.
The change can be dramatic for users upgrading existing applications from version 3, but as a whole the new system is much easier to use and (especially) maintain.


text:
Q: Can GDB change the assembly code of a running program? I want to add some extra funcionality to /bin/ls.
So I started it on gdb and added a breakpoint at the beginning.
Now question is: how can I change the code of a running program in memory? I can see the assembly code, but I'm not able to modify. How can I do it?
On Windows I can easily do this with olldbg for example. How about on Linux?
(I know that doing this I will only change the code of the process in memory. So then I can dump memory to a file, and then I'll have my changes saved in a binary file).
Thank you.

A: I would recommend a different approach: Download the coreutils package and modify the source code for ls. If possible, you should get the package from your distro's source repositories and apply any patches.

A: compile code command
Introduced around 7.9, it allows code compilation and injection. Documentation: https://sourceware.org/gdb/onlinedocs/gdb/Compiling-and-Injecting-Code.html
I have given a minimal example in this answer.
While it is not actual code modification, it does allow you to compile some code on the fly and run it once immediately, which might be enough.
And the GNU cauldron presentation suggests that actual code modification may be added later on as an extension to this feature, see slide 30 "Fix and continue".
There are a few constructs that did not work as I expected like return, so I've asked why at: In the GDB compile code command, what language constructs behave exactly as if they were present in the original source?

A: You can write binary to memory directly but GDB doesn't have an assembler build in by default you can however do something like set *(unsigned char*)0x80FFDDEE = 0x90 to change the mnemonic at that address to a NOP for example. You could however use NASM to write a shellcode and use perl or python to inject it into the program :)
You might also like this little .gdbinit file to make debugging allot easier: https://gist.github.com/985474

A: You can use gcc-plugin to write an extension to modify your coed and add any additional functionality in easy way during compilation process. if you work on machine level code, you should use binary instrumentation tools like Pin and Dyninst to instrument your binary file on the disk. however, if the overhead is important issue, you should work carefully with such tools.


text:
Q: expectException doesn't detect the exception I am trying to test database records retrieving. My test looks like:
use yii\db\Exception;

class UserTest extends Unit
{
    protected $tester;
    private $_user;

    public function _before()
    {
        $this->_user = new User();
    }

    public function testRetrievingFALSE()
    {
       $this->expectException(Exception::class, function(){
          $this->_user->retrieveRecords();
       });
    }
}

I saw the expectException() method in the documentation. My model method looks like this:
public function retrieveRecords()
{
    $out = ArrayHelper::map(User::find()->all(), 'id', 'username');
    if($out)
        return $out;
    else
        throw new Exception('No records', 'Still no records in db');
}

What am I doing wrong in this scenario?
In terminal:
Frontend\tests.unit Tests (1) ------------------------------------------------------------------------------------------
x UserTest: Retrieving false (0.02s)
------------------------------------------------------------------------------------------------------------------------

Time: 532 ms, Memory: 10.00MB

There was 1 failure:

---------
1) UserTest: Retrieving false
 Test  tests\unit\models\UserTest.php:testRetrievingFALSE
Failed asserting that exception of type "yii\db\Exception" is thrown.

FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

A: You're not using the same method which you're referring to. You should use it on actor instance, not on unit test class itself. So either:
$this->tester->expectException(Exception::class, function(){
    $this->_user->retrieveRecords();
});

Or in acceptance tests:
public function testRetrievingFALSE(AcceptanceTester $I) {
    $I->expectException(Exception::class, function(){
        $this->_user->retrieveRecords();
    });
}

If you call it on $this in test class, method from PHPUnit will be used, which works differently:
public function testRetrievingFALSE() {
    $this->expectException(Exception::class);
    $this->_user->retrieveRecords();
}

See more examples in PHPUnit documentation.


text:
Q: How to change mesos master reregister timeout in DC/OS I'm creating a multi-master multi-slave DC/OS cluster, My problem is that default reregister timeout for mesos is 10min, I would like to change this default to some bigger value, but I couldn't find how to do it in DC/OS install configuration.
Does anyone know how can we change configuration of underlying mesos masters and/or slaves in DC/OS installation?
UPDATE:
Thanks for the answers, I created this ansible script for post-installation. After you installed your DC/OS cluster, run this script on all master nodes:
- name: Post install for dc/os masters
  hosts: masters
  tasks:
  - name: set mesos environment variables 1
    lineinfile:
      dest: /run/dcos/etc/mesos-master
      regexp: "{{ item.regexp }}"
      line: "{{ item.line }}"
      insertafter: "^SyslogIdentifier"
    with_items:
      - { regexp: '^Environment="MESOS_AGENT_REREGISTER_TIMEOUT=', line: 'Environment="MESOS_AGENT_REREGISTER_TIMEOUT=24hrs"' }

  - systemd:
      name: "dcos-mesos-master.service"
      state: restarted
      daemon_reload: yes

A: I suppose you are talking about this Mesos Flag --agent_reregister_timeout=VALUE. For details see the Mesos Documentation.
The distribution unfortunately is not elegant at the moment (as it is not an official DCOS parameter)
Do this for all master node:

*

*ssh into master nodes

*Put desired config in /run/dcos/etc/mesos-master
MESOS_AGENT_REREGISTER_TIMEOUT=<value>

*Restart master service systemctl restart dcos-mesos-master
Confirm that the masters is running successfully via journalctl -fu dcos-mesos-master


text:
Q: How many liters of each acidic solution should be mixed? Chris needs to make 500 L of a 35% acidic solution. He has only two of the acidic solutions available,a 25% solution and a 50% solution. How many liters of each acidic solution should he mix? (Solve by substitution)

A: We have $500$ liters of solution and a $175$ liters of solute.
Let $A$ and $B$ be the amount of solution mixed.
$A+B=500$
$0.25A+0.5B=175$
Then we have $A=500-B$.
Therefore, $0.25(500-B)+0.5B=175$.
Then $125-0.25B+0.5B=175$.
Then, we have $125+0.25B=175$, so $B=200$.
Therefore, $A=300$ and $B =200$.
The equations match this too.
Therefore, $300$ liters of $25\%$ solution and $200$ liters of $50\%$ solution were mixed to form $500$ liters of $35\%$ solution.


text:
Q: How do I access data from a joined table in my index.html.erb? I have a Rails 4 app with two models Campus and Stat. Campus has_many stats and Stat belongs_to Campus.
The problem I have is I can the data from my Campus table in my show action, but not in my index action. Here's the relevant code from the controllers.
  def index
    @stats = Stat.all
  end

  def show
  end

Here's my show.html.erb:

<%= notice %>

  Attendance:
  <%= @stat.attendance %>

  Salvations:
  <%= @stat.salvations %>

  Visitors:
  <%= @stat.visitors %>

  Offering:
  <%= @stat.offering %>

  Campus:
  <%= @stat.campus.name %>

  Date:
  <%= @stat.date %>

<%= link_to 'Edit', edit_stat_path(@stat) %> |
<%= link_to 'Back', stats_path %>

It's outputs the following:
Attendance: 23
Salvations: 0
Visitors: 3
Offering: 5000.0
Campus: Revelstoke
Date: 2013-07-05
Edit | Back
Here's the relevant portion of my index.html.erb:
<% @stats.each do |stat| %>

    <%= stat.attendance %>
    <%= stat.salvations %>
    <%= stat.visitors %>
    <%= stat.offering %>
    <%= stat.date %>
    <%= stat.time %>
    <%= stat.campus.name %>
    <%= link_to 'Show', stat %>
    <%= link_to 'Edit', edit_stat_path(stat) %>
    <%= link_to 'Destroy', stat, method: :delete, data: { confirm: 'Are you sure?' } %>

<% end %>

The output gives me a undefined method `name' for nil:NilClass for the stat.campus.name
I can't figure out why the difference. What am I doing wrong?

A: It looks like you have a stat with no campus associated to it in your database.
To check witch one is it, you could go to the rails console and check the campus_id property, printing Stat.all,
That can happen if you are adding your stats programmatically, or maybe you added a form without every model property.
If you don't want that to happen you can use validates in your model. Check this link.

A: First, you are not initialising @stat in show action, you could do this with:
@stat = Stat.find(params[:id])

Second, you have to be sure @stat has campus associated with it. But as you are not having problems with index, it seems your stat has campus associated, it means that status has a column campus_id which value is a valid id of table campuses.
Update
After reading your comment your stat has not a campus associated, you can show an empty string in these cases with:
  <%= stat.campus.try(:name) %>


text:
Q: WSO2 API manager SSL with nginx I have to use nginx as proxy for an API manager installation using secure SSL connection.
Any hint on how to configure all to make it work?
Thanks
Luca

A: Current version of API manager doesnt support "https" endpoints...We have that in our roadmap and will fix that in future release. But you can use ESB between APIManager and your backend service to route the request

A: As of WSO2 API Manager version 1.3.0, support for invoking secured back-end services has been added. Please see below synapse configuration of a sample API which invokes a secured back-end service. Currently support is only available for services secured over Basic Auth.
<api xmlns="http://ws.apache.org/ns/synapse" name="admin--SecuredAPI" context="/secure" version="1.0.0" version-type="url">
    <resource methods="POST GET OPTIONS DELETE PUT" url-mapping="/*">
        <inSequence>
            <property name="Authorization" expression="fn:concat('Basic ', base64Encode('username:password'))" scope="transport"/>
            <property name="POST_TO_URI" value="true" scope="axis2"/>
            <filter source="$ctx:AM_KEY_TYPE" regex="PRODUCTION">
                <then>
                    <send>
                        <endpoint name="admin--SecuredAPI_APIEndpoint_0">
                            <address uri="https://securebackend.com/search">
                                <timeout>
                                    <duration>30000</duration>
                                    <responseAction>fault</responseAction>
                                </timeout>
                                <suspendOnFailure>
                                    <errorCodes>-1</errorCodes>
                                    <initialDuration>0</initialDuration>
                                    <progressionFactor>1.0</progressionFactor>
                                    <maximumDuration>0</maximumDuration>
                                </suspendOnFailure>
                                <markForSuspension>
                                    <errorCodes>-1</errorCodes>
                                </markForSuspension>
                            </address>
                        </endpoint>
                    </send>
                </then>
                <else>
                    <sequence key="_sandbox_key_error_"/>
                </else>
            </filter>
        </inSequence>
        <outSequence>
            <send/>
        </outSequence>
    </resource>
    <handlers>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler"/>
        <handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageHandler"/>
        <handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtGoogleAnalyticsTrackingHandler"/>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler">
            <property name="id" value="A"/>
            <property name="policyKey" value="gov:/apimgt/applicationdata/tiers.xml"/>
        </handler>
        <handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler"/>
    </handlers>
</api>

Thanks,
Nuwan.


text:
Q: Make a CSS rounded dotted line I would like to create a rounded dotted line in CSS like the picture.
I tried the "border dashed" but the edges are square.

A: Use background:

.box {
  height:10px;
  background:
    radial-gradient(circle closest-side,red 98%,#0000) 50%/40px 100%,
    linear-gradient(90deg,red 50%,#0000 0)             50%/80px 100%;
}


text:
Q: Java script not starting when navigating to a page containing an applet I am trying to run this website, which is supposed to run an applet (?) with Java script. It should look like this; however, the page is blank, except for the heading:

I have downloaded and unzipped the files in the upper right hand corner of the last linked page, although I don't know if I'm supposed to do anything with the downloaded files.
I have also included the website URL on the Exception Site List in the Java Control Panel.
I use Windows 10 and Opera as my browser. JavaScript is enabled in my browser.
Trying with Safari, IE or Chrome has been unsuccessful.

A: It's not JavaScript, it is Java. JavaScript is the scripting engine used by browsers to allow dynamic webpages while Java is an object orientated programming language. They share some similarity in code style, but little more than that.

Java is an Object Oriented Programming (OOP) language created by James Gosling of Sun Microsystems. JavaScript is a scripting language that was created by the fine people at Netscape and was originally known as LiveScript. JavaScript is a (very) distant cousin of Java in that it is also an OOP language. Many of their programming structures are similar. However, JavaScript contains a much smaller and simpler set of commands than does Java. It is easier for the average weekend warrior to understand.

Java has been discontinued for almost all current browsers due to security concerns. Almost no browser supports Java and so you will need to download the "jar" version and run it manually if you want to run it at all.

A: After much chasing around I was able to get the web-site to display correctly:-

*

*I used PaleMoon browser, which supports the Java plug-in, while Opera appears not to recognise it.

*I installed the latest Java version 8 update 161.

*I added https://math.la.asu.edu to the Java Control Panel exception list, without the rest of the address.

Java ran after the unsigned code was accepted, but it was quite slow - around 15 seconds before the content appeared.
Waterfox also supports the Java plug-in, but for some reason the Java content didn't load.
I was testing on Ubuntu, but browsers are generally compatible with Windows versions.


text:
Q: Is it ok to retain and autorelease at the same time? I have the following code:
@interface MyClass : NSObject
{
    NSMutableArray *items;
}
@end

@implementation MyClass

-(Item *)getItem
{
    if(items.count < 1)
    {
        [self buildItemsArray];
    }
    Item *item =  [[[items objectAtIndex:0]retain]autorelease];
    [items removeObjectAtIndex:0];
    return item;
}

-(void)buildItemsArray
{
    // ...
    [items addItem:someNewItem];
    [items addItem:someOtherNewItem];
}
@end

I have a function that returns an item. If the items go down to 0, then the items array is built again inside buildItemsArray. My game logic requires that when I return an item, I need to remove it from the array. So, I am using a retain to ensure that the item is valid till the return line (since the only other known retain happened when the item was added to the items array), and an autorelease to ensure it gets cleaned up later. I have checked that this code neither crashes nor leaks. I wonder if:
a) This is OK - the reason I ask is that I have predominantly seen code with alloc/init/autorelease, and haven't run into this case with retain/autorelease
b) Is there some reason to alloc/init/autorelease instead:
Item *item =  [[Item alloc]initWithItem:[items objectAtIndex:0]autorelease];

Thanks

A: This is generally ok:
Item *item = [[[items objectAtIndex:0] retain] autorelease];
[items removeObjectAtIndex:0];
return item;

Though this would make the intent clearer (returning an autoreleased object):
Item *item = [[items objectAtIndex:0] retain];
[items removeObject:item];
return [item autorelease];

No reason to alloc/init. That just adds unnecessary overhead.
Like I said in my comment, if this is a (relatively) new project, you really really really should be using ARC and not worry about these things anymore.


text:
Q: Finite sets and convergent subsequences Claim: If $(X,d)$ is a metric space and $F \subseteq X$ is a finite subset of $X$, then any sequence $(a_n)$ in $F$ must have a convergent subsequence.
Hint: Reduce this problem to proving that every sequence must have a constant subsequence.
Lemma: If $(a_n)$ is a convergent sequence in a metric space $(X,d)$ and $(a_{kn})$ is a subsequence, then $(a_{kn})$ is convergent.
Suppose $F$ is finite. Then $F=\emptyset$, or $\exists$ bijection $f:F \to \{1,2,3...,n\}$ for some $n \in \mathbb{Z^+}$. If $F=\emptyset$, then $F$ contains no sequence, and thus the claim is vacuously true. Assume $F \ne \emptyset$.
Let $(a_n) \in F$. Because $F$ is finite, then $(a_n)$ has a finite number of terms, so $(a_n)$ must be convergent. Because $F \subseteq X$, with $(X,d)$ a metric space, then $(a_n) \in F \Rightarrow (a_n) \in (X,d)$. By the lemma, this means that subsequence $(a_{kn})$ is convergent. Therefore, any sequence $(a_n) \in F$ must have a convergent subsequence.
I'm not sure this is correct. My understanding is that a sequence in a subset of a metric space is a sequence in the metric space whose every term is in the subset. Any insight would be appreciated!


text:
Q: Limit of a recursive relation from initial iterates. The query: How to find limits of a converging recursive sequence from some (you may take as many as needed) of the consecutive initial iterates?
Example:
I have a recursive relation of the form $\vec{x}(n+3)=a_2 \vec{x}(n+2)+ a_1 \vec{x}(n+1)+ a_0 \vec{x}(n) +\vec{c}$, where  $\vec{x}(k),\vec{c}\in \mathbb{R}^2$  and $a_2,a_1, a_0 \in \mathbb{R}$ are chosen such that the relation converges to a limit point, $\frac{\vec{c}}{1-(a_2+a_1+a_0)}$. If one knows the constants $a_2,a_1, a_0$ and $\vec{c}$,  one could compute the limit point.
However,  I am left with few (say 10) initial iterates of $\vec{x}(k)$. I need to find the limit point. Here is the approach I tried.
Step 1 : Estimate $a_2, a_1$ and $ a_0$  from the iterate values solving the following equation.
for k =1, 2 (or any two values)
$\vec{x}(k+5)-\vec{x}(k+4)$ = $a_2(\vec{x}(k+4)-\vec{x}(k+3))+a_1(\vec{x}(k+3)-\vec{x}(k+2))+a_0(\vec{x}(k+2)-\vec{x}(k+1))$
this is expected to give me four equations for three unknowns (I could generate as many equations as I need from the iterates varying $k$)
Here is the Problem: The system of equations is unsolvable (Matlab solver says the system is inconsistent.)
Step 2: Estimate $\vec{c}$ from the recursive relations.
Step 3: Estimate $x_{limit}$ using aforementioned problem.
Please find attached the sample Matlab code (if you wish to try out).
I observed that the condition number of the matrix formed for solving the linear equations mentioned above is large (which makes the system inconsistent, I guess). Why is it happening?
Any effort made in helping me solve this problem (or even identifying why this is happening) is highly appreciated.
Thanks in advance
%% Sample code

%% Calculating iterates using a sample recursive relation
a_2 = 0.1;
a_1 = 0.1;
a_0 = 0.3;

c=[0.2,1]';

x_limit = c/(1-(a_2+a_1+a_0));%-----(1)
% x_0 = 10*rand(size(c));
x_0 = zeros(size(c));
x_1 = a_0*x_0 +c;
x_2 = a_1*x_1+a_0*x_0 +c;

totla_iterates=200;
X_mat=zeros(length(c),totla_iterates);
X_mat(:,1) = x_0;
X_mat(:,2)=x_1;
X_mat(:,3)=x_2;
for i=4:totla_iterates
   X_mat(:,i)=a_2* X_mat(:,i-1)+a_1* X_mat(:,i-2)+a_0* X_mat(:,i-3)+c;%----(2)
end

%% Note that the recursive relation converges to the limit predicted by (1)

% Now use the first 10 iterates of (2) to predict the limit
%% Step 1: Estimate a_0,a_1
X_difmat=X_mat(:,2:end)-X_mat(:,1:end-1);

syms a2 a1 a0
i=1; % you may try varying the value of i or use more equations to find the soln.
% eqn1 =  X_difmat(1,i)*a2+X_difmat(1,i+1)*a1 +X_difmat(1,i+2)* a0 == X_difmat(1,i+3);
% eqn2 =  X_difmat(2,i)*a2+X_difmat(2,i+1)*a1 +X_difmat(2,i+2)* a0 == X_difmat(2,i+3);
% eqn3 =  X_difmat(1,i+1)*a2+X_difmat(1,i+2)*a1 +X_difmat(1,i+3)* a0 == X_difmat(1,i+4);
% [A,B] = equationsToMatrix([eqn1,eqn2,eqn3], [a2 a1 a0]);
eqn1 =  X_difmat(:,i)*a2+X_difmat(:,i+1)*a1 +X_difmat(:,i+2)* a0 == X_difmat(:,i+3);
eqn2 =  X_difmat(:,i+1)*a2+X_difmat(:,i+2)*a1 +X_difmat(:,i+3)* a0 == X_difmat(:,i+4);
[A,B] = equationsToMatrix([eqn1,eqn2], [a2 a1 a0]);

X=double(linsolve(A,B)); % note that I am unable to calculate a_1 and a_0 here
 disp(num2str(X)) % Ideally this should be X= a_2 a_1 and a_0 , which I am not getting.

```

A: This is an interesting problem which has a surprisingly simple solution. We start with a
simple form of the problem. Suppose $\, x_{n+1} = a_0 x_n + c\,$ for all $\,n.\,$ We want
to solve for $\,a_0,\,c\,$ and compute $\, L := c/(1-a_0).\,$ We solve the linear system
$\, x_1 = a_0 x_0 + c,\, x_2 = a_0 x_1 + c\,$ and find that the expression for the limit $\,L_2\,$ (if it exists) is
$$ L_2 = \frac{x_0 x_2 - x_1 x_1}{x_0 - 2x_1 + x_2}. $$
The numerator is the determinant of a $\,2 \times 2\,$ Hankel matrix formed using $\,(x_0, x_1, x_2).\,$ The
denominator is the Total derivative
of the numerator with all the partial derivatives replaced with $\,1.$ Notice that $\,L_2\,$ is exactly the result
of  Aitken's $\Delta^2$-quared process
This rational expression for $\,L_2\,$ naturally generalizes for linear recurrences with more terms.
For example, suppose that $\, x_{n+2} = a_1 x_{n+1} + a_0 x_n + c\,$ for all $\,n\,$
and the limit $\, L := c/(1-a0-a1).\,$ Solving the linear system
$\, x_2 = a_1 x_1 + a_0 x_0 + c,\, x_3 = a_1 x_2 + a_0 x_1 + c,\,
   x_4 = a_1 x_3 + a_0 x_2 + c\,$ gives the expression for the limit $\,L_3\,$ (if it exists) as
$$ L_3 = \frac{ x_0 x_2 x_4 + 2 x_1 x_2 x_3 - x_2^3 - x_0 x_3^2 - x_1^2 x_4 }
{  (x_0 - 2 x_1 + x_2) (x_2 - 2 x_3 + x_4) - (x_1 - 2 x_2 + x_3)^2}. $$
The reason for this general result is that the numerator of the
limit $\,L\,$ is $\,c\,$ and $\,c=0\,$ is equivalent to the Hankel
determinant of the homogeneous linear system being zero. If the
denominator $\,(1 - a_0 - ... - a_k) = 0,\,$ then the 2nd difference of the
$\,\{x\}\,$ sequence satisfies a linear homogeneous system of equations and
is equivalent to a Hankel determinant being zero.
Of course, this assumes that the limit exists and exact
calculations are used. One issue is that the denominator
and/or the numerator could be zero.
For example, if $\, x_{n+1} = x_n\,$ then
$\, L_2 = 0/0 \,$ which gives no information about the limit of the constant sequence. If $\,\{x\}\,$ is a geometric
sequence given by $\, x_{n+1} = a_0 x_n\,$ then
$\, L_2 = 0/(x_0(1-a_0)^2)\,$ which implies $\, L_2 = 0\,$
if $\,x_0 \ne 0\,$ and $\, a_0 \ne 1,\,$ but the limit is zero only
if $\, |a_0|<1.\,$ The other issue is loss of significance in doing inexact
arithmetic.
For testing purpose, I wrote the following PARI/GP code:
{doit(n, m=1) = for(k=0, n+m-1, x[n+k+1] = c + sum(i=1,n, x[k+i]*a[i]))};
{L3(k=1) = my(x0 = x[k+0], x1 = x[k+1], x2 = x[k+2], x3 = x[k+3], x4 = x[k+4],
   y0 = x0 - 2*x1 + x2, y1 = x1 - 2*x2 + x3, y2 = x2 - 2*x3 + x4);
   (x0*x2*x4 + 2*x1*x2*x3 - x2^3 - x0*x3^2 - x1^2*x4)/(y0*y2 - y1*y1)};
default(realprecision, 9);
ni = 20; x = vector(ni+4); a = [0.2,0.1]; c = 0.02; x[1] = 0.5; x[2] = 0.3;
   doit(2, ni); print(x); print(vector(ni, k, L3(k)));

The resulting output is:
[0.500000000, 0.300000000, 0.150000000, 0.0950000000, 0.0595000000, 0.0449500000, 0.0363950000, 0.0326295000, 0.0305419500, 0.0295800950, 0.0290663995, 0.0288226589, 0.0286955458, 0.0286340864, 0.0286025178, 0.0285870690, 0.0285792105, 0.0285753349, 0.0285733756, 0.0285724045, 0.0285719156, 0.0285716725, 0.0285715504, 0.0285714895]
[0.0285714280, 0.0285714283, 0.0285714283, 0.0285714288, 0.0285714246, 0.0285714317, 0.0285714052, 0.0285716963, 0.0285716927, 0.0285761767, 0.0285658400, 0.0286175962, 0.0286606325, 0.0258589033, 0.0269360081, 0.E-1, 0.E0, -1.34551706, -10.0552618, 33.4275327]

You can see  the original sequence converging, but the approximations to the
limit appear to diverge. This is the result of using only $9$ digits of precision.
If the number of digits of precision is increased to $19$, the problem goes away.

A: If your iterates are indeed coming from the given recurrence, the system must be compatible. In fact, there are four unknown constants and you should work with four equations. Then the coefficients so obtained should let you retrieve the next iterates exactly.
If your problem is numerically unstable, you might be facing significant numerical errors, and it can make sense to work with an overdetermined system and solve it in the least-squares sense (or similar).
If the recurrence is only hypothesized or accepted as an approximation or if the data is noisy, then perforce the systems will be incompatible and you need to resort to a best-fit.

By the way, there is no reason to treat the independent term $\vec c$ differently than the other unknown parameters.


text:
Q: The purpose of threshold in naive bayes algorithm Suppose we have 2 classes. By using naive Bayes classifier we get posterior probabilities P(C1|D) and P(C2|D) for query sample.....suppose P(C1|D) is higher than P(C2|D), then we assign the tag of class 1 to query sample.
My question is this :
Where does the threshold come into picture here and why and how do we use 5-fold cross validated accuracy to find the ideal threshold for Naive Bayes algorithm??

A: In short: The threshold is not a part of the Naive Bayes algorithm
A Naive Bayes algorithm will be able to say for a certain sample, that the probability of it being of C1 is 60% and of C2 is 40%. Then it's up to you to interpret this as a classification in class C1, which would be the case for a 50% threshold. When using accuracy as a metric you essentially count the amount of correct classifications and thus state a definite threshold (like 50%) that is used to determine which class is being predicted for each sample.
You might want to take a look at this answer, and Frank Harrell's  Classification vs. Prediction.
Why cross validation? Because you want to use a separate training/test set and use all your data.
How? You could determine recall & precision for every fold and every threshold and make a choice.
Some sidenote: Naive Bayes has the tendency to push probabilities to extremes (0% and 100%), it's what they call badly calibrated. It's due its basic assumption that all attributes are conditionally independent which is often not the case. The latter is visible in the example below; some metrics are plotted in function of threshold for a Naive Bayes classifier on a spam task.


text:
Q: Camunda returns error HTCL-02007 when calling API on localhost I followed this tutorial Web service call, and it works just fine.
Then I tried to call a simple local API, built in .net 6
https://localhost:7169/WeatherForecast/GetStatus

which returns
{
  "weather": "Good"
}

but when I try to start the process in Camunda task list, I always get error
The process could not be started. :
HTCL-02007 Unable to execute HTTP request

I tried to add cors to my API project, but in vain.
Any help is appreciated.


text:
Q: API working on browser but not on device with phonegap I am developing an app using phonegap. I am using the edmunds API to get pictures of cars. The API works fine on the browser but when I run it on the device it does not show the images. Does anyone know the reason? And is there a way to debug on the device for javascript?
Here is the code:
 <script>
    window.sdkAsyncInit = function() {
        // Instantiate the SDK
        var res = new EDMUNDSAPI('xxxx');
        // Optional parameters
        var options = {};
        var style;
        // Callback function to be called when the API response is returned
        function success(res) {

            style = res.styles[0].id;
            console.log(style);

            showimage(style);

        };
        function showimage(style){

            var opt = {
                "styleId": ""+style+"",
                "comparator": "simple"
            };
        console.log(opt);
            res.api('/v1/api/vehiclephoto/service/findphotosbystyleid', opt, success2, fail);

        }
        function success2(res){
            var body = document.getElementById('image');
            body.innerHTML = "<img src='http://media.ed.edmunds-media.com"+ res[0].photoSrcs[0] +"' />";
        }

        function fail(data) {
            console.log(data);
        }
        // Fire the API call
        var make = localStorage.getItem('make');
        var model = localStorage.getItem('model');
        var year = localStorage.getItem('year');
        console.log(make+model+year);

        res.api('/api/vehicle/v2/'+make+'/'+model+'/'+year+'/styles', options, success, fail);
        // Additional initialization code such as adding Event Listeners goes here
  };
  // Load the SDK asynchronously
  (function(d, s, id){
        var js, sdkjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "./edmunds.api.sdk.js";
        sdkjs.parentNode.insertBefore(js, sdkjs);
   }(document, 'script', 'edmunds-jssdk'));
</script>

A: You can use:
http://debug.phonegap.com/ (also known as weinre)
Did you enable the API in the whitelist?
And do you have an adb logcat?

A: the API was getting the protocol from the window which was not working for the phone app changed it to https and it worked.


text:
Q: Default Java Heap Size and Memory Issues it can cause I have an application whose backend is built on Java 8. Recently I've been seeing that the application restarts by itself, because of OOM. I got to know its because of OOM, by looking at the exit status of the Docker Container. There was no Xmx and Xms values configured for the system and as such it should be using the default heap size, which in case of my server which has 4 gigs of memory should be around 512 MB (I read in some SO answers that deafult heap max size is 1/8th the memory present). After setting the Xms and Xmx values my app now is behaving correctly without any restarts. I also tried increasing the memory in the server to 7 gigs before setting the Xmx and Xms values, but it also didn't help. What i want to know is that, how come the system was going OOM, when there was sufficient memory available for the application.
Does the default heap size extend itself if memory requirement increases for the app ? If memory was getting full, why was GC not getting triggered ?

A:
Does the default heap size extend itself if memory requirement
  increases for the app?

Yes, but only up to the value in -Xmx (or the default for that value that the JVM chose).

If memory was getting full, why was GC not getting triggered?

GC was getting triggered, but it could not collect any garbage. Everything in your heap was non-garbage.

A: The default maximum heap size is 1/4 of main memory.  This assumes the machine is not dedicated to this one process. If it is you might want to increase the maximum heap size.
Note: The heap size is only the size of the heap which is just one memory area the JVM uses.  It is not the total memory consumption.  How much additional memory your JVM needs depends on what it is doing.
The initial size can grow to the size of the maximum. The maximum size doesn't grow, it's the size of heap you would rather the process die than use any more.
Without more information, I would try a 3 GB heap on a 4 GB machine if that is all it is running and see how this goes. You can monitor how much virtual memory the process is trying to use in top
NOTE: Not all OutOfMemoryError(s) are the same and you need to read the error message to determine what is the actual cause of the problem. e.g. you could have run out of threads, perm gen/metaspace or some other low level memory problem.

A:
"how come the system was going OOM, when there was sufficient memory
  available for the application."

There are two possible issues here:

*

*You have not configured enough memory for the memory needs of your application so could you share the values of your configuration?

*There is a memory leak problem caused by the application so you should keep in mind this
Source: http://blog.sysco.no/memory/leak/memory-leak/

One of the main advantages of Java is the use of a garbage collector
  that allows programmers to forget about the memory management. That is
  not the case of languages such as C++ where you have to allocate and
  free memory since your code. In my experience in a big company, I saw
  memory leak problems several times causing the unavailability or the
  bad performance of many applications.
In addition, a memory leak belongs to a class of situations called
  software aging problems. Software aging defines the loss of
  performance over the time because of the gradual accumulation of
  little problems. Other term within this kind of problem is the
  rejuvenation process. For example, rejuvenation happens when the
  system has to be restarted in order to free the memory accumulated by
  a Java Virtual Machine (JVM) process after a period of time (COTRONEO,
  D, et al., 2015).

Basically the garbage collector on the JVM uses a mechanism to reuse the space of objects, which does not have any reference from the root set so when there is a problem within the source code or configuration that keeps objects referenced for ever, little by little the application is going to fill the heap until reaching its limit.
For example, in the following figure just the unreachable objects inside the graph are going to be collected all the reachable objects (even those generated by a bug or bad configuration) are going to be kept in the heap

source http://blog.sysco.no/files/guides/JVMGarbageCollectionV1.1.pdf

"Does the default heap size extend itself if memory requirement
  increases for the app ?"

The answer is not, when tyour application fills the whole new generation, the JVM is going to execute a minor GC to release objects from the new generation and those who survive are moved into the survivor space for some cycles until they reach certain age. When they (objects in the survivor space) are mature enough and still are alive, these objects are promoted into the old generation and when the old generation is full, a full GC is performed. Thus, as it seems to be your application is keeping references (memory leak) at some point the whole heap will be filled up of alive objects so JVM is not able to release them and it does not have a flag to increase the memory in cases like this.

"If memory was getting full, why was GC not getting triggered ?"

In this case I have a question, how do you know whether the GC is getting triggered or not? To tune the garbage collection process you have to measure this so you can try these flags to get information about the GC execution.
-XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:/home/user666/gc.log
In addition, you can use this nice web to analyze the log file
http://gceasy.io/
Las but not least, you can use these flags
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/some/where/your/machine
With these flags you are going to produce a heap dump, which can be analyzed with Memory Analyzer Tool (MAT: https://www.eclipse.org/mat/downloads.php) to determine whether the application has a memory leak or not.


text:
Q: ImportError raised when trying to load 'projects.templatetags.markdown_extras': No module named 'markdown' InvalidTemplateLibrary(
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'projects.templatetags.markdown_extras': No module named 'markdown'
I am getting the above error.
i have django - 4.1 version and python 3.10.5
i have installed the markdown. but getting error in line- import markdown in the templatetags/markdown_extras.py.
not sure what's the problem. can anybody please help?
thank you in advance


text:
Q: Dart style recommendation on importing local file Is there any recommendation how to import local files. In my case I would have 2 options:

*

*import 'package:workshop/feed/item.dart';

*import 'item.dart';

I haven't found anything on that on the guide Effective Dart: Style nor on Google search.

A: There are at least two different recommendations, depending on who you ask.
Either works, I personally recommend the latter, shorter, variant.
It is sufficient and it avoids the issue of hard-coding your package name into every file. If you ever want to rename the package, that will be a drudge.
There is one issue which makes some people recommend the former format.
If you import a package library using a non-package: URI, say by having a file in the bin/ or test/ directory do an import like:
import "../lib/mylib.dart";

then that library is now imported using two different URIs:

*

*package:mypkg/mylib.dart and

*file:///somewhere/mypkg/lib/mylib.dart
Since Dart identifies libraries by their import URIs, these two imports will be treated as different libraries, each with their own global and static variables, which just happen to have the same source code. That's an annoying problem, and can be hard to debug. If you use the long package:... import everywhere, then at least the issue is restricted to the first library you import. If you use a relative import, import "src/helper.dart";, then that library will now also exist in two versions:

*

*package:mypkg/src/helper.dart and

*file:///somewhere/mypkg/lib/src/helper.dart
The real issue here was the first import which contained a /lib/ in the path. You must never have such an import. Using package: URIs for all imports may reduce the issue, but not remove it.
I recommend using the relative path, and making sure that you never have a /lib/ in any import path. Libraries in the /lib/ directory of a pub package are package libraries and should be referred to using package: URIs. If you do that, then relative URIs will be resolved against the package URI and again be a package URI, and all is well.


text:
Q: PANDAS-GEOPANDAS: Localization of points in a shapefile Using pandas and geopandas, I would like to define a function to be applied to each row of a dataframe which operates as follows:
INPUT: column with coordinates
OUTPUT: zone in which the point falls.
I tried with this, but it takes very long.
def zone_assign(point,zones,codes):
    try:
        zone_label=zones[zones['geometry'].contains(point)][codes].values[0]
    except:
        zone_label=np.NaN
    return(zone_label)

where:
point is the cell of the row which contains geographical coordinates;
zones is the shapefile imported with geopandas;
codes is the column of the shapefile which contains label to be assigned to the point.

A: Part of the answer, is taken from another answer I made earlier that needed within rather than contains
Your situation looks like a typical case where spatial joins are useful. The idea of spatial joins is to merge data using geographic coordinates instead of using attributes.
Three possibilities in geopandas:

*

*intersects

*within

*contains
It seems like you want contains, which is possible using the following syntax:
geopandas.sjoin(polygons, points, how="inner", op='contains')

Note: You need to have installed rtree to be able to perform such operations. If you need to install this dependency, use pip or conda to install it
Example
As an example, let's take a random sample of cities and plot countries associated. The two example datasets are
import geopandas
import matplotlib.pyplot as plt

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
cities = geopandas.read_file(geopandas.datasets.get_path('naturalearth_cities'))
cities = cities.sample(n=50, random_state=1)

world.head(2)

    pop_est     continent   name    iso_a3  gdp_md_est  geometry
0   920938  Oceania     Fiji    FJI     8374.0  MULTIPOLYGON (((180.00000 -16.06713, 180.00000...
1   53950935    Africa  Tanzania    TZA     150600.0    POLYGON ((33.90371 -0.95000, 34.07262 -1.05982...

cities.head(3)
    name    geometry
196     Bogota  POINT (-74.08529 4.59837)
95  Tbilisi     POINT (44.78885 41.72696)
173     Seoul   POINT (126.99779 37.56829)

world is a worldwide dataset and cities is a subset.
Both dataset need to be in the same projection system. If not, use .to_crs before merging.
data_merged = geopandas.sjoin(countries, cities, how="inner", op='contains')

Finally, to see the result let's do a map
f, ax = plt.subplots(1, figsize=(20,10))
data_merged.plot(axes=ax)
countries.plot(axes=ax, alpha=0.25, linewidth=0.1)
plt.show()

and the underlying dataset merges together the information we need
data_merged.head(2)

    pop_est     continent   name_left   iso_a3  gdp_md_est  geometry    index_right     name_right
7   6909701     Oceania     Papua New Guinea    PNG     28020.0     MULTIPOLYGON (((141.00021 -2.60015, 142.73525 ...   59  Port Moresby
9   44293293    South America   Argentina   ARG     879400.0    MULTIPOLYGON (((-68.63401 -52.63637, -68.25000...   182     Buenos Aires

Here, I used inner join method but that's a parameter you can change if, for instance, you want to keep all points, including those not within a polygon.


text:
Q: How to create a trigger that returns a value to the console in java I would like to use Postgres to create a trigger that returns whenever new information is added to a specific column in a table and return that data to me in the console. How could I do this?
I was thinking in java I could assign a value to this trigger function and that's how it could print get my values printed but is this the best way?

A: A trigger cannot return information you are wanting; they return either an image of the row (generally NEW) or null. Nor can they have out parameters. You may get what you want with NOTIFY. Something like:
create or replace function send_notify()
  returns trigger
 language plpgsql
as $$
begin
    NOTIFY "my_channel", <what you want on console>;
    return null;
end;
$$;

create trigger send_notify_air
  after insert
     on some_table_name
  for each row
  execute function send_notify();


text:
Q: mutiple radio's in a form (PHP) I created a form and I want multiple radio questions in my form with the same output (Yes,No ).
Here is my script:
<?php
echo '

    '
        .$row1['vraag'].'

        <input type="radio" name="check" onclick="displayResult(this.value)" value="ja">Ja
        <input type="radio" name="check" onclick="displayResult(this.value)" value="nee">Nee

        <input type="hidden" name="vragen'.$aantalBranches.'[]" value="'.$row1['vraag'].'"/>
        <input id="result" type="text" name="antwoorden'.$aantalBranches.'[]"/>

';

As you can see I sent the question with it (vragen) and the answer (antwoorden) when the form is filled.
The problem I have now is when I select the second question also with a radio the output of the first one also changes.
Anyone can help me in the right direction with radio button ?
Thanks in advance

A: All radio buttons with the same name are treated as being in the same group - and only one item from the group can be selected at the same time.  So, your second set of radio boxes need their name set to a different group to the name used by the first.


text:
Q: Can not send curl request. Authorization has been denied for this request I successfully sent request with postman with basic authorization and 1 custom header - token.
Now I need to sent the same request using curl.
This is how postman parameters look like:

And this is my curl command:
curl -k -u my@mail.com:1Qwer432 -H "CERequestToken: 46Yx2fo4t5+p1IX" https://mysite/v54/api/contracts

What am I doing wrong?

A: I found the solution. The problem is that curl does not save cookies. And it's necessary to send cookies with request.


text:
Q: Chern Character of Pushforward of Vector Bundle Let $X$ be a compact, smooth $n$-dimensional Calabi-Yau variety and let $M \subseteq X$ be an $m$-dimensional subvariety.  Here, both $n$ and $m$ are complex dimensions.  I want to take a rank $N$ holomorphic vector bundle $E$ on $M$ and push it forward $i_{*}E$ to $X$ via the natural inclusion.  Finally, what I'm interested in doing is taking the Chern character.
I believe that $\text{ch}_{k}(i_{*}E)=0$ for all $k <n-m$.  But what I really want to show is the following:
$$\text{PD}\big(\text{ch}_{n-m}(i_{*}E) \big) = N[M] \in H_{2m}(X, \mathbb{Z})$$
where "$\text{PD}$" of course denotes Poincare duality.  What I mean by the righthand side is $N$ times the fundamental class of $M$.  Is this true?  If so, how can I go about proving it?
Context: In the string theory literature, we see tons of statements like "take a stack of $N$ D$2m$-branes wrapping some $2m$-dimensional cycle $M$."  I think this corresponds to simply taking a rank $N$ holomorphic vector bundle on $M$.  This indeed would be the correct interpretation if my above claim is true.
By the way, I know my claim is true if $M$ is a curve, but I'm hoping it's more general!  I believe it should rely on $X$ being Calabi-Yau.

A: This is a long comment since I don't know if this will solve your whole question.
Under certain assumptions you can use Grothendieck-Riemann-Roch to tackle this sort of questions. For example in Huybrechts' book the statement reads: Consider a smooth projective morphism $f:X\to Y$ of smooth projective varieties. Let $\mathcal{F}$ be a coherent sheaf on $X$. Then,
$$
\operatorname{ch}\left(\sum(-1)^iR^if_*\mathcal{F}\right)\operatorname{td}(Y)=f_*(\operatorname{ch}(\mathcal{F})\operatorname{td}(X)).
$$
In your particular case the inclusion map is a closed immersion, so the functor $i_*$ is exact and the higher direct images vanish. Then GRR says that
$$
\operatorname{ch}\left(i_*E\right)\operatorname{td}(X)=i_*(\operatorname{ch}(E)\operatorname{td}(M))\Rightarrow \operatorname{ch}\left(i_*E\right)=\frac{i_*(\operatorname{ch}(E)\operatorname{td}(M))}{\operatorname{td}(X)},
$$
where to compute the fraction you use the Taylor series of $\frac{1}{1-x}$. As you mention the fact that $X$ is CY comes into play with the Todd class.

This post in MO and this tag of the stacks project may be helpful when calculating the RHS of GRR.


text:
Q: Native 5k resolution in Windows 10 on retina iMac Is it possible to run the native 5k resolution on my retina iMac when using the official Windows 10 bootcamp? Right now, it seems to be capped at 4k. I have the 4.0 GHz i7 with the m295x GPU.

A: It is as of TODAY - well, for me at least. I have been stuck to 4K for as long as everyone else had, but early this morning the Apple Update utility asked to install a new version of Bootcamp drivers. I let it do its thing and... voila. Native 5K res on the next boot!
Don't know if it had anything to do with Microsoft's own November Update for Windows 10, but I am truly happy it did happen at last (I had given up hope to be honest). Just make sure that you do NOT let a later version of AMD's drivers overwrite these, as it's likely to return the resolution to 4K. I know I won't.


text:
Q: How to hide or view stream data from inspect element and developer tools? I want to know how one might hide data that is being streamed on a website (such as an mp3 file) such that the resource URL cannot be viewed in inspect element or developer tools. Conversely I would also like to know how one might find the resource URL of such 'hidden' data if possible. Whether via JavaScript or otherwise.
An example website is www.saavn.com where I am unable to view any information about the streaming data in the 'Network' tab. Other resources and data are visible however. The transfer readout should have had been giving a readout in MBs instead of KBs to reflect the amount of streaming I have done.
P.s, I can easily see all resource URL's(including the streaming mp3 file) in soundcloud.
Here is a screenshot reflecting the fact:


text:
Q: How to make Excel sheet readonly using asp.net? My Task is to generate excel sheet as read only(i e., columns data should not be editable) using asp.net?
I am getting data from the database,then am generating the excel sheet for that data but it is editable.I want to make my excel sheet as non editable.
How should I do?
Anybody can please help me?
I have written code like this..
Thanks in Advance....

A: Try to look this topic - first and second. Second one offers a solution even for cells.


text:
Q: Calling validation methods from textbox mouse leave Codeigniter Is it possible to call a validation function which is located in a controller from a view elements like "input box". e.g : gmail signup page username field validate when mouse leave...

A: you would need to use ajax to do this.
documentation for $.ajax(); http://api.jquery.com/jQuery.ajax/
$.ajax({
  url: "url/to/controller/validationaction",
  success: function(data){
    //do something since validation
    //passed.
  },
  error: function(d,r,x){
    //do something since validation
    //failed.
  }
});

is a very very remedial example.
Your controller would return an http failure status code using
$this->output->set_status_header(code, 'text');

Link to CI's Output Documentation
list of http status codes
if the validation failed, otherwise return TRUE; or echo a json_encoded array of a message..
$message = array(
  'message' => 'Success!',
  'type' => 'succes',
);
echo json_encode($message);

Using jQuery Validation
You could also rely on jquery/javascript to handle your validation client side, this would prevent you from having to make an http request just to validate the user's input.
One popular plugin for this is: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
It should go noted that, if the user disables jquery/javascript you need to have a failsafe method in place that will validate via codeigniters form validation helper still.


text:
Q: creating a thumbnail itemrenderer for a FileSystemTree - what life cycle functions should i override? i have build an air app that has an extension of a FileSystemTree Component in it, to display only the jpg files and directories in the file system.
a checkbox allows the user to choose whether to see the items in the tree as thumbnails or regular (labels+icons) tree items (the tree has variableRowHeight set to true).
if the checkbox is selected, any time a branch in the tree is opened all the thumbnails of the jpeg files in that directory are rendered first.
this part of the application works fine (the thumbs are created).
my custom itemrenderer is an extension of the TreeItemRenderer class.
the display of the items in the tree is unpredictable and scrolling the tree makes it worse. i am pretty sure that i didn't override the "lifecycle" functions of the component (the invalidation and validation methods) correctly.
i have added a function called thumbToggle which informs the itemrenderer if the checkbox is selected or deselected while the tree is idle.
what is your opinion in overriding set data, invalidateProperties, invalidateSize, invalidateDisplayList, commitProperties, measure, updateDisplayList and other functions to achieve a smooth operation of such a tree?
thanx in advance,
Saar

A: Are you sure you need to override anything besides get data and set data? There's lot of room for errors in invalidate functions.


text:
Q: prevent Adblock blocking tracking pixel I'm currently working at a platform that delivers banners. But these are not those annoying banners that you see on every website. They are interactive banners which expand only if you click on it. The problem is that adblock is not blocking the banner itself, it's blocking the tracking pixel that I'm injecting into the banner.
Why I want to solve this? Well, it will cost me money to deliver that banner, you'll see it and I will not be aware of that.
I'm currently trying to find a method of tracking the banners without a tracking pixel. Any good ideas for this? Thank you guys.

A: Depending on how you serve your imaging pixel, One possibility is to set up a proxy in front of your images and use the logs to track the banners that you serve. Alternately, you can use the proxy to perform some logic and trigger an insert into a database of sorts (although that would likely make the proxy a bit slow).
You can also use the proxy to alias the tracking pixel's name so that it does not have the "ad" text in the filename. This may get it around the adblocker all by itself and can be done with simple pattern matching logic
You can use a proxy like nginx or HA proxy


text:
Q: Receiving an UDP Packet from Arduino in a CrossbarServer in Python I'm new using WAMP protocol and CrossbarIO servers that are based on the WAMP protocol. The problem is. I have and Arduino Uno + EthernetShield and I want to send the information to the CrossbarServer.
The Arduino Uno has not support for Autobahn or WAMP or Crossbar. I just can send normal packages via UDP and websocket with an UNO+Ethernet.
Is there someway that I can read this UDP packet in the CrossbarServer from the arduino?

A: Unfortunately you cannot do so directly at the moment. For the time being, you need to connect the Uno to some component which accepts messages from the Uno and can talk WAMP as well.
We are working on a C library for lower-end devices, but as far as I can tell (I'm not directly involved) something with the specs of the Uno will remain out of the scope of WAMP even then since the initial plan is that the library itself will consume about 8k of RAM.


text:
Q: asynchronous HTTP request in java How to send asynchronous HTTP GET/POST request in java  without waiting/reading response ?I don't want to use any third party libraries ..

A: If you're not interested in reading the response at all you can just use URL.openStream() to create a connection and then immediately close the socket (or ignore it and let it time out, if you feel like being mean to the server).  This isn't strictly asynchronous, but it will be quite a bit faster than any approach that relies upon fetching and parsing the server's response.
This can of course be made asynchronous by offloading the openStream() calls to another thread, either manually or by using the utilities available in java.util.concurrent.

A: java.util.concurrent can be used .
If you interested is using third party libraries then you might want to take a look at
Async Http Client

A: I would suggest using something like the Jetty HttpClient if you don't mind adding the Jetty libraries to your app. Here's a good example from Jetty's wiki page http://wiki.eclipse.org/Jetty/Tutorial/HttpClient.