text:
Q: What makes every strong monad on a certain category be a monoidal functor? A concept named Monad is used a lot in functional programming. And in spite their definition is not completely same with the definition of monad in category theory, as I know, Monad on a programming language is equivalent to certain category theoretical monad. The category has data types as objects and pure functions between them as morphisms. Since data types can be seen as a set of values, it's simply a subcategory of Set.
I found that in functional programming, a Monad is always an Applicative Functor, which is said to be 'programming equivalent of a lax monoidal functor with tensorial strength in category theory.'
Exactly how is this possible? Specifically, What makes monad on Set always be a monoidal functor?
I tried to prove this from that every monad in Set are strong monad, but failed. The only thing I could find was that strong monads are monoidal if they are commutative. The problem is that even in the category of sets, monads are not commmutative in general. There are many monad which are not commutative in Set, including free monoid monad.
Just proving that every monad in Set are monoidal functor perhaps not be that hard. I rather want to know more fundamental, or generalizable reason behind that. (If exist.) What makes every strong monad in certain category be always monoidal functor, even when they are not commutative?

A: $\require{AMScd}$
Suppose $T$ has two tensorial strengths:
$$σ : A \otimes TB → T (A \otimes B) \\ τ : TA \otimes B → T (A \otimes B)$$
with the compatibility condition:
$$
\begin{CD}
A \otimes(TB \otimes C) @>{α}>> (A \otimes TB) \otimes C \\
@V{A \otimes τ}VV @VV{σ \otimes C}V \\
A \otimes T (B \otimes C) @. T(A \otimes B) \otimes C \\
@V{σ}VV @VV{τ}V \\
T(A \otimes (B \otimes C)) @>>{Tα}> T((A \otimes B) \otimes C)
\end{CD}
$$
This is apparently known as a bistrength. Then we can try to define a monoidal multiplication as:
$$m : T A \otimes T B → T(A \otimes B) \\
m = μ \circ Tσ \circ τ$$
I assume only the associativity is in question. That is the diagram:
$$
\begin{CD}
TA \otimes (TB \otimes TC) @>{α}>> (TA \otimes TB) \otimes TC \\
@V{TA \otimes m}VV @VV{m \otimes TC}V \\
TA \otimes T(B \otimes C) @. T(A \otimes B) \otimes TC \\
@V{m}VV @VV{m}V \\
T (A \otimes (B \otimes C)) @>>{Tα}> T((A \otimes B) \otimes C)
\end{CD}
$$
Here's an equational proof:
$$
\begin{align}
&\ μ ∘ Tσ ∘ τ ∘ ((μ ∘ Tσ ∘ τ)⊗TC) ∘ α
\\ = &\ μ ∘ Tσ ∘ τ ∘ (μ⊗TC) ∘ ((Tσ ∘ τ)⊗TC) ∘ α
\\ = &\ μ ∘ Tσ ∘ μ ∘ Tτ ∘ τ ∘ ((Tσ ∘ τ)⊗TC) ∘ α
\\ = &\ μ ∘ μ ∘ TTσ ∘ Tτ ∘ τ ∘ ((Tσ ∘ τ)⊗TC) ∘ α
\\ = &\ μ ∘ μ ∘ TTσ ∘ Tτ ∘ τ ∘ (Tσ⊗TC) ∘ (τ⊗TC) ∘ α
\\ = &\ μ ∘ μ ∘ TTσ ∘ Tτ ∘ T(σ⊗TC) ∘ τ ∘ (τ⊗TC) ∘ α
\\ = &\ μ ∘ μ ∘ TTσ ∘ Tτ ∘ T(σ⊗TC) ∘ Tα ∘ τ
\\ = &\ μ ∘ μ ∘ TTσ ∘ T(τ ∘ (σ⊗TC) ∘ α) ∘ τ
\\ = &\ μ ∘ μ ∘ TTσ ∘ T(Tα ∘ σ ∘ (A⊗τ)) ∘ τ
\\ = &\ μ ∘ μ ∘ TTσ ∘ TTα ∘ Tσ ∘ T(A⊗τ) ∘ τ
\\ = &\ μ ∘ μ ∘ TT(σ ∘ α) ∘ Tσ ∘ T(A⊗τ) ∘ τ
\\ = &\ μ ∘ μ ∘ TT(Tα ∘ σ ∘ (A⊗σ)) ∘ Tσ ∘ T(A⊗τ) ∘ τ
\\ = &\ μ ∘ μ ∘ TTTα ∘ TTσ ∘ TT(A⊗σ) ∘ Tσ ∘ T(A⊗τ) ∘ τ
\\ = &\ μ ∘ μ ∘ TTTα ∘ TTσ ∘ T(T(A⊗σ) ∘ σ) ∘ T(A⊗τ) ∘ τ
\\ = &\ μ ∘ μ ∘ TTTα ∘ TTσ ∘ T(σ ∘ (A⊗Tσ)) ∘ T(A⊗τ) ∘ τ
\\ = &\ μ ∘ μ ∘ TTTα ∘ TTσ ∘ Tσ ∘ T(A⊗Tσ) ∘ T(A⊗τ) ∘ τ
\\ = &\ μ ∘ μ ∘ TTTα ∘ TTσ ∘ Tσ ∘ T(A⊗(Tσ ∘ τ))) ∘ τ
\\ = &\ μ ∘ μ ∘ TTTα ∘ TTσ ∘ T(σ ∘ (A⊗(Tσ ∘ τ))) ∘ τ
\\ = &\ μ ∘ μ ∘ TTTα ∘ T(Tσ ∘ σ ∘ (A⊗(Tσ ∘ τ))) ∘ τ
\\ = &\ μ ∘ Tμ ∘ TTTα ∘ T(Tσ ∘ σ ∘ (A⊗(Tσ ∘ τ))) ∘ τ
\\ = &\ μ ∘ TTα ∘ Tμ ∘ T(Tσ ∘ σ ∘ (A⊗(Tσ ∘ τ))) ∘ τ
\\ = &\ μ ∘ TTα ∘ T(μ ∘ Tσ ∘ σ ∘ (A⊗(Tσ ∘ τ))) ∘ τ
\\ = &\ μ ∘ TTα ∘ T(σ ∘ (A⊗(μ ∘ Tσ ∘ τ))) ∘ τ
\\ = &\ μ ∘ TTα ∘ Tσ ∘ T(A⊗(μ ∘ Tσ ∘ τ)) ∘ τ
\\ = &\ Tα ∘ μ ∘ Tσ ∘ T(A⊗(μ ∘ Tσ ∘ τ)) ∘ τ
\\ = &\ Tα ∘ μ ∘ Tσ ∘ τ ∘ (TA⊗(μ ∘ Tσ ∘ τ))
\end{align}
$$
There's also the opposite order multiplication which does $τ$ after $σ$, and should have a similar proof.
The informal answer is: this sort of tensorial bi-strength lets us go from $T A \otimes TB$ to $T^2(A \otimes B)$. Then the monad multiplication lets us flatten down to $T(A \otimes B)$. This is associative as long as the two strengths are 'the same' operation just for opposite sides of the tensor.


text:
Q: Closed sets and subtraction of elements. Let $X$ be a normed vector space, $A,B\subset X$ closed and $M=A-B:=\{x\in X:x=a-b ,\quad a\in A, b \in B\}$.
I am looking for an example where $A,B\quad$ closed $\Longrightarrow\quad M\quad$ closed
is wrong.

A: Consider $A = \mathbb N_{\ge 2}$ and $B = \{ n + \tfrac1n \mid n\in A \}.$
Notice that $A,B$ are in fact closed. For example, for any sequence $b_k = n_k + \frac{1}{n_k}\in B$ we have
 $$ |b_k - b_l| \ge |n_k - n_l| - \left| \frac{1}{n_k} - \frac{1}{n_k}  \right| \ge |n_k - n_l| - \frac{1}{2}. $$
So, $b_k$ converges if and only if $b_k$ is eventually constant.
Now, $M = A-B$ contains the sequence $m_k = -\frac{1}{1+k}$, which converges to $0\notin M$. That is, $M$ isn't closed

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Can I Tell If a Transaction Is In Progress with JDBC? I'm using a JDBC Connection with autocommit turned off.  In my cleanup method I want to check to ensure that there is not a transaction currently in progress but I can't see any way of obtaining this information.  How can I find out if a transaction is in progress given a JDBC Connection?
Update
Although there's nothing in JDBC natively, the Tomcat JDBC connection pool has the concept of interceptors and I'm wondering if one could be written to track transactions at that level.

A: JDBC Connection doesnt have any helper methods to know the status, but if you can get javax.transaction.UserTransaction, you can use "getStatus" method to find the status. More info on oracle site.


text:
Q: Need to determine how to send REST Parameter for list I am trying to test out a REST service I created to add a entry to the database.  The class that defines this looks like this:
public string OrderNumber
public string FirstName
public string LastName
Public List<Items> Items

The "Items" class is defined as:
public string Material
public int Amount
public decimal Quantity

My question is how to format a REST "POST" to send the List Items over?
Below is what I tried to use to send over the list of items but it fails and the items do not come over.
http://mytesturl.com/CreateOrder?OrderNumber=ABC123&FirstName=Mark&LastName=Jones&Items=Items[]{"Material": "IPHONE", "Quantity": 1, "Amount": 45.50}

A: First of all you should pass that data as form body in the request and not with query string. Thus in your API method should use [FromBody]. In your current case that List<Item> would become a JSON array and thus send it like
&Items=[
        {"Material": "IPHONE", "Quantity": 1, "Amount": 45.50},
        {"Material": "Samsung", "Quantity": 1, "Amount": 35.50}
       ]

A: Thanks everyone, I would have prefaced that this was my first time trying to use Postman for testing REST calls.  I didnt realize it supported sending JSON requests.  Once I used JSON request, everything worked perfectly.
Here is the JSON request I used if anyone is interested:
{
"OrderNumber":"ABC123",
"FirstName":"Mark",
"LastName":"Jones",
"Items":
[
{
"Material":"IPHONE",
"Quantity":1,
"Amount":59.8
},
{
"Material":"SAMSUNG",
"Quantity":29,
"Amount":65.27
}
]
}


text:
Q: ClassNotFound Exception while running a Swing App as a jar file inside another Swing App I am working on the integration of two developed swing applications (host and guest). The guest application is included as a jar file in the host project. For communication between them, I created an interface inside the guest and implemented it inside the host.
// inside host
GUEST guest= GUEST.getInstance( );
Socket2host socket = new Socket2host() {
               .
               .
               .
                };
guest.setSocket(socket);

Everything works well. However, after release, I noticed that the guest cannot load a class from its own source. Indeed, the guest application tries to reload a project using a Serializer from an xml file(the developer used simpleframework library for this). Here you can look inside the code:
Serializer serializer = new Persister();
setInstanceFromXML(serializer, *xml string);

    public static void setInstanceFromXML(Serializer s, String in){
        try {
            s.read(SingletonHolder.instance, in);
        } catch (Exception ex) {
            // Logging
        }
    }

When I run the project in Eclipse, it works well and I can see the desired class in the current thread. but when I run the release version, the following error is logged on the console.
java.lang.ClassNotFoundException: ipad.experimentSettings.IPADExperimental1DSVSSettings
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at org.simpleframework.xml.strategy.TreeStrategy.getClass(TreeStrategy.java:270)
        at org.simpleframework.xml.strategy.TreeStrategy.getValue(TreeStrategy.java:183)
        at org.simpleframework.xml.strategy.TreeStrategy.getElement(TreeStrategy.java:123)
        at org.simpleframework.xml.core.Source.getOverride(Source.java:330)
        at org.simpleframework.xml.core.Factory.getConversion(Factory.java:144)
        at org.simpleframework.xml.core.Factory.getOverride(Factory.java:100)
        at org.simpleframework.xml.core.ObjectFactory.getInstance(ObjectFactory.java:64)
        at org.simpleframework.xml.core.Composite.read(Composite.java:125)
        at org.simpleframework.xml.core.Composite.readObject(Composite.java:621)
        at org.simpleframework.xml.core.Composite.read(Composite.java:567)
        at org.simpleframework.xml.core.Composite.readElement(Composite.java:548)
        at org.simpleframework.xml.core.Composite.readElements(Composite.java:464)
        at org.simpleframework.xml.core.Composite.read(Composite.java:350)
        at org.simpleframework.xml.core.Composite.read(Composite.java:158)
        at org.simpleframework.xml.core.Traverser.read(Traverser.java:106)
        at org.simpleframework.xml.core.Persister.read(Persister.java:707)
        at org.simpleframework.xml.core.Persister.read(Persister.java:687)
        at org.simpleframework.xml.core.Persister.read(Persister.java:667)
        at org.simpleframework.xml.core.Persister.read(Persister.java:648)
        at org.simpleframework.xml.core.Persister.read(Persister.java:565)
        at ipad.IPADConditions.setInstanceFromXML(IPADConditions.java:89)
        at ipad.IPADApp.reloadFitProject(IPADApp.java:2974)
        at ipad.IPADApp.loadFitProject(IPADApp.java:2901)
        at ipad.ui.IPADMenuBar.actionPerformed(IPADMenuBar.java:257)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.AbstractButton.doClick(Unknown Source)
        at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
        at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)
        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
        at java.awt.EventQueue.access$500(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.awt.EventQueue$3.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
        at java.awt.EventQueue$4.run(Unknown Source)
        at java.awt.EventQueue$4.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
        at java.awt.EventQueue.dispatchEvent(Unknown Source)
        at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
        at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
        at java.awt.EventDispatchThread.run(Unknown Source)

here is the snippet of xml file:(ipad.experimentSettings.IPADExperimental1DSVSSettings is desired class)
<experimentalParameterSettings class="ipad.experimentSettings.IPADExperimental1DSVSSettings">
      <numberOfResponses>1</numberOfResponses>
      <TEsDefined>true</TEsDefined>
      <TRsDefined>false</TRsDefined>
      <TSsDefined>false</TSsDefined>
      <TIsDefined>false</TIsDefined>
      <TMsDefined>false</TMsDefined>
      <TOthersDefined>false</TOthersDefined>
      <TEs length="1">
         <double>0.0</double>
      </TEs>
      <TRs length="1">
         <double>0.0</double>
      </TRs>
      <TSs length="1">
         <double>30.0</double>
      </TSs>
      <TIs length="1">
         <double>0.0</double>
      </TIs>
      <TMs length="1">
         <double>0.0</double>
      </TMs>
      <TOthers length="1">
         <double>0.0</double>
      </TOthers>
      <currentExperimentType>SVS_1D</currentExperimentType>
   </experimentalParameterSettings>

I already added the guest application(as a JAR file) to the classpath, So this post didn't help me. I defined the classpath as what I had on eclipse but it did not work. I checked the "current thread", but the app could not find the desired class.
Here you can find a minimal reproducible example of loading the guest's class.
// host app
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
    JFrame f=new JFrame("minimal reproducible example");
    final JTextField tf=new JTextField();
    tf.setBounds(50,50, 150,20);
    JButton b=new JButton("Click Here");
    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            Guest guest = Guest.getInstance;
        }
    });
    f.setLayout(null);
    f.setVisible(true);
}
}

// guest app
public class Guest extends JFrame implements ActionListener {
private static Guest theInstance = null;
public Guest (){
String in = <address to desired class in the package>
try {
 System.out.println(Thread.currentThread().getContextClassLoader().loadClass(in));
} catch (Exception ex) {
    System.out.println(ex);
}
}

public static Guest getInstance( )
{
    if ( theInstance == null )
    {
        theInstance = new Guest ( );
    }

    return theInstance;
}

// desired class for loading
public class DesiredClass{
    public DesiredClass() {
    }
}

Additional info: the below code runs the released version.
set javaFile="C:\Program Files (x86)\Java\jre1.8.0_202\bin\java"
cd /d %~dp0
set path=%path%;%CD%\lib
%javaFile% -Xss2m -Xmx900m -Djava.library.path=lib -jar lib/mrui.jar %*
pause

I was wondering why the classes of the guest appear in Eclipse but it cannot be loaded in the released version.


text:
Q: When writing a test for a service class, throws a NullPointerException exception due to the repository object used in the service class I am trying to test a service method. The method looks like this:
@Component
public class TaskServiceImpl implements TaskService {

    @Autowired
    public TaskRepository taskRepository;

    //tested method
    @Override
    public boolean addTask(Task task) {

        if (taskNameIsNull(task) || taskNameAndDescriptionIsNull(task)) {
            return false;
        }

        taskRepository.save(task);
        return true;
    }

    //other code

}

So, I write test for method addTask using JUnit5 and mockito:
class TaskServiceImplTest {

    private TaskServiceImpl taskService = new TaskServiceImpl();

    @Mock
    private TaskRepository taskRepository;

    @Test
    void addTaskTest(){
        Task task = new Task();
        task.setName("SomeName");
        task.setDescription("SomeDescription");
        assertEquals(true, taskService.addTask(task));
    }

And when I start test method addTaskTest I get NullPointerException:
java.lang.NullPointerException
    at com.spring_project.nadia.tasks_timer.service.TaskServiceImplTest.addTask(TaskServiceImplTest.java:25)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:436)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:170)
    at org.junit.jupiter.engine.execution.ThrowableCollector.execute(ThrowableCollector.java:40)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:166)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:113)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:58)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:112)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$2(HierarchicalTestExecutor.java:120)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.lambda$executeRecursively$3(HierarchicalTestExecutor.java:120)
    at org.junit.platform.engine.support.hierarchical.SingleTestExecutor.executeSafely(SingleTestExecutor.java:66)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.executeRecursively(HierarchicalTestExecutor.java:108)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor$NodeExecutor.execute(HierarchicalTestExecutor.java:79)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:55)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:43)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:170)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:154)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:90)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

As far as I understand, the NullPointerException is thrown because of the TaskRepository class object. I thing so because other tests of the addTask method test cases when this method returns false passed.
What am I doing wrong?
P.S. This doesn't a Spring Boot application, but just Spring Framework.

A: You have created a mock repository, but not injected into your service. As you wrote, other tests of the addTask method passed when this method returns false, because in this case your repo isn't invoked.
Also add one of the annotations above the test-class depending on which version of JUnit you are using:
@RunWith(MockitoJUnitRunner.class)  // for JUnit4
@ExtendWith(MockitoExtension.class)  // for JUnit5
class TaskServiceImplTest {

    @InjectMocks // inject mocks into class under test
    private TaskServiceImpl taskService;

    @Mock
    private TaskRepository taskRepository;

    @Test
    void addTaskTest(){
        Task task = new Task();
        task.setName("SomeName");
        task.setDescription("SomeDescription");
        assertTrue(taskService.addTask(task));
    }

A: This is not very relevant to the question, but here's advice...
Please, prefer constructor injection instead of field injection, it's a good practice.
@Component
public class TaskServiceImpl implements TaskService {

    public final TaskRepository taskRepository;

    public TaskServiceImpl(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }
}

Then you can just:
class TaskServiceImplTest {

    @Mock
    private TaskRepository taskRepository;
    @InjectMocks
    private TaskServiceImpl taskService
}

Or
class TaskServiceImplTest {

    private TaskRepository taskRepository;
    private TaskServiceImpl taskService

    @BeforeEach
    void setUp() {
        taskRepository = mock(TaskRepository.class);
        taskService = new TaskServiceImpl(taskRepository);
    }
}


text:
Q: Как отправить во Vue.js get запрос в контроллер laravel Подскажите, как отправить get-запрос vue.js в контроллер laravel, то есть чтобы записать данные в методе get (Route::get).
Пробовал через axios, в итоге не работает.
methods: {
    handleSwitch(){
        axios.get("/", { sequence:item.name }).then((response)=> { console.log(item.name) });
                 }
         }

Установил уже даже Vue resource, что-то тоже пробывал и не работает.
Повторюсь, у меня все уже готово, только нужно чтобы в get-запрос отправились данные, и выполнить постановку без обновления страницы.


text:
Q: Douglas Crockford on Class Free OOP in JavaScript Douglas Crockford has a really good talk on "The Better Parts" of ES6. Among other things, he encourages a move away from prototypal inheritance in favor of class free OOP.
Here he says he stopped using new, Object.create, and this, but didn't really explain an alternative. Could anyone fill me in on how that might look?

A: You should watch the whole video, he explains it at later in the video.
function constructor(spec) {
  let {member} = spec,
      {other}  = other_constructor(spec),
      method   = function () {
        // accesses member, other, method, spec
      };

  return Object.freeze({
      method,
      other
  });
}

It's the revealing module pattern returning a frozen object.

A: Example

*

*Approach A: Objects w/ Functions

*

*This is faster than classes / prototypes (there's no extra table lookups on the functions, such as greet), but may use (mostly negligible) more memory (a pointer per function, essentially).

*Approach B: Value Objects (pure JSON, no functions on the object)

*

*The big (capital P) Person has the methods (such as save) - the only downside to this is that you always wrap the function you want to use if it needs to be in a callback and preserve context.

Neither of these approaches require arrow functions or bind or anything like that, which means that your code will both parse and run faster.
var Person = {};

Person.create = function (tmpl) {
  var person = {
    name: tmpl.name || 'No Name',
    age: tmpl.age || 0,

  };

  // Approach A
  person.greet = function (other) {
    return `Hello ${other.name}! I'm ${person.name}!`;
  };

  return person;
};

// Approach B
Person.save = async function (p) {
  if (p.id) {
    await request({
      method: "PUT",
      url: `/api/people/${p.id}`,
      json: p
    });
    return p;
  }

  var resp = await request({
    method: "POST",
    url: `/api/people/`,
    json: p
  });
  p = resp.body;
  return p;
};

You can combine the approaches, but if you at all incorporate Approach A just be sure that your constructor faithfully reproduces objects with JSON with the required functions and without overwriting existing values with default values.


text:
Q: Apple App Upload Icon Validation Error I'm uploading a free app to the Mac App Store and I keep getting this error during validation that says,

The application bundle does not contain an icon in ICNS format, containing both a 512x512 and a 512x512@2x image. For further assistance, see the Apple Human Interface Guidelines.

The only thing is, there are files called icon_512x512.png and icon_512x512@2x.png, as well as files for all the other necessary resolutions.
Since Apple is absolutely no help, I was hoping someone would know how to fix this or at least go about creating an icon that meets the specifications.

A: As I understand it, if you create the .icns in Icon Composer it will fail validation even if a proper 512x512@2x is present. Use iconutil to convert the .icns back into an iconset, and then use iconutil to create a new .icns from the iconset.
For instance:
resources $ iconutil -c iconset icon.icns
resources $ iconutil -c icns icon.iconset

More info on iconutil is here.

A: That fixed my problem but I used cd to go to the folder, then I entered
iconutil -c iconset icon.icns
iconutil -c icns icon.iconset

the icon name must be icon as in the command.

A: you should prepare 2 pictures with png extension, one is 512x512 pixels named icon_512x512.png, one is  1024x1024 pixels named icon_512x512@2x.png, put the 2 pictures in a folder(named icon for example), then out the folder use command iconutil -c icns icon, you will get a icon.icns, drag it to Xcode and drop on the target's App icon.

A: Also, make sure you include the .icns file extension in your plist when specifying the name of your icon. At some point this became required by iTunes Connect.

A: just create the icon 1024x1024 then add that icon to the folder Images.xcassets/AppIcon.appiconset
After these you will see the icon under xcode as "unsigned"
just drag that icon to empty icon field. thats it .


text:
Q: $\det:U\to\mathbb{R}$ has surjective derivative for every $x$ $\iff$ no matrix in $U$ has dimension $\le n-2$ Let $U\subset \mathbb{R}^{n^2}$ be a open set of matrices $n\times n$. Show that the function $\det:U\to\mathbb{R}$ is a submersion (its derivative is surjective for every $x$) $\iff$ no matrix in $U$ has dimension $\le n-2$
My book solves this as following:
The $n^2$ coordinates of the jacobian matrix are the numbers $(-1)^{i+j}X_{ij}$ where $X_{ij}$ is the determinant of the $(n-1)\times (n-1)$ matrix you get when omiting the $i$-th columns and $j$-th line (or the reverse, don' t remember). So $x$ is a critical point of $\det\iff X_{ij}$ is $0$ for every submatrix of our matrix which implies that if all the submatrices determinants $X_{ij}$ are $0$ our matrix has dimension $n-2$. WHY?? Also, what is the connection of the derivative being surjective with all of this???

A: I'm assuming by dimension you mean rank.

*

*$\forall (i,j), X_{i,j} = 0 \iff \det x=0$
This comes from the Laplace expansion.
And $\det x = 0 \iff x$ is not invertible $\iff$ the rank of $x$ is not $n$.

*$\forall (i,j), X_{i,j} = 0 \iff$ the rank of $x$ isn't $n-1$.
This comes from the fact that the rank of a matrix is the size of the largest non-vanishing minor.
Thus, $x$ is a critical point $\iff x$ has rank $\leq n-2$.
Now, what's the link with $\det$ being a submersion ? Well, $D_{\det} \in \mathcal{L}(\mathbb{R}^{n^2}, \mathbb{R}^{n^2})$, and thus it is a surjection iff it is an injection, iff its kernel is $\{0\}$.
Does that make it more clear?


text:
Q: SQL IF CONSTRAINT I have the following table,
-- Booking Table
CREATE TABLE Bookings (
booking_id      INTEGER GENERATED ALWAYS AS IDENTITY,
hotel           INTEGER,
check_in        DATE NOT NULL,
check_out       DATE NOT NULL,
size            VARCHAR(20) NOT NULL,
quantity        INTEGER NOT NULL,
pin             INTEGER NOT NULL,
url             VARCHAR(30) NOT NULL,
extra_bed       INTEGER DEFAULT 0,
assigned        VARCHAR(5) NOT NULL,
assignedroom    INTEGER,

-- Constraints
CONSTRAINT assigned_ck CHECK (assigned IN ('Yes', 'No')),

-- If we have assigned a room to the booking ("assigned" = 'Yes') then "assignedroom" CANNOT be NULL
CONSTRAINT assignedroom_ck CHECK (assigned = 'Yes' AND assignedroom NOT NULL),

-- If we have NOT assigned a room, then "assignedroom" = NULL
CONSTRAINT assignedroom_ck1 CHECK (assigned = 'No' AND assignedroom NULL),

CONSTRAINT booking_size_ck CHECK (size IN ('Single', 'Twin', 'Queen', 'Executive', 'Suite')),
CONSTRAINT extra_bed_ck CHECK (extra_bed IN (0,1)),
CONSTRAINT pin_ck CHECK (pin > 999 AND pin <= 9999),
-- because the single rooms are numbered 1 - 15, can check that single room
-- cannot have extra bed
--CONSTRAINT single_extra_ck CHECK(room_num < 16 AND extra_bed NOT IN (1));
-- Keys
FOREIGN KEY (hotel) REFERENCES Hotels(id),
PRIMARY KEY(booking_id)

);
I'm getting an error at the CONSTRAINT assignedroom_ck part. The error is Syntax error: Encountered "NOT".
With CONSTRAINT assignedroom_ck and CONSTRAINT assignedroom_ck1, I'm trying to achieve:
1) If assigned = 'Yes', then assignedroom CANNOT be NULL.
2) If assigned = 'No' then assignedroom MUST be NULL
Could someone please help me with the correct syntax?
Thank you.

A: You are missing IS:
CONSTRAINT assignedroom_ck CHECK (assigned = 'Yes' AND assignedroom IS NOT NULL),
CONSTRAINT assignedroom_ck1 CHECK (assigned = 'No' AND assignedroom IS NULL),

EDIT: As obviously both constraints can never be met, so you cannot insert anything, you need to combine the constraints:
CONSTRAINT assignedroom_ck CHECK
(
  (assigned = 'Yes' AND assignedroom IS NOT NULL)
  OR
  (assigned = 'No' AND assignedroom IS NULL)
),

A: You need to combine both of your checks for assigned room because you don't want any check constraint to return false:
CONSTRAINT assignedroom_ck CHECK (
    (assigned = 'Yes' AND assignedroom IS NOT NULL) or
    (assigned = 'No' and assignedroom IS NULL)
)

With it as two separate constraints, one of them will always be FALSE and so no row can ever be inserted.


text:
Q: Find a plane perpendicular to another plane, parallel to line and from a distance to a given point Could you please help me to solve this problem?
Given: Space $\rm R^{3}$, plane $\alpha$ as a cartesian equation, line $e$ as parameter equation, point P (x, y, z). Find a plane perpendicular to $\alpha$, parallel to the line $e$, and at a distance of $\sqrt{32}$ from P.
Let's name the plane that we are searching as $\beta$ ($Ax+By+Cz+D=0$, in total 4 parameters have to be found) if $\beta\perp\alpha$ than the normal vectors of these planes are $\perp$ too. From the dot product, we can get an equation for A, B, and C.
The normal vector of $\beta$ is $\perp$ to line $e$, so given that the direction of the line is known, we can get another equation for A, B, and C.
But last part is out of my understanding: from the formula of distance from the point to the plane we can get the quite complicated equation:
$\sqrt{32} = \frac{|Ax+By+Cz+D|}{\sqrt{A^2+B^2+C^2}}$.
I get stuck here, could someone help me?
Solution: (thanks guys for a hint!)  Use normal vector for the plane $\alpha$ and direction of the line $e$ to construct a cross product, which will give the normal of the plane $\beta$ (three out of 4 parameters will be known then, namely A, B, and C). Use these to solve the last equation, where the D can be obtained.


text:
Q: How can I list the models has I brand that I selected with Json? I want to list in second  tag the models  of the brand I selected. I need this for my homework. I do not know what to do. Please help me.

  function notlariListele(param) {
      var httpistegi = new XMLHttpRequest();
      var adres = "https://raw.githubusercontent.com/atakanbalta/Moto-karsilastirma/master/markalar.json";

      httpistegi.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          var myArr = JSON.parse(this.responseText);
          var list1 = document.querySelector("#slc1");
          myArr.forEach(function(params) {
            list1.innerHTML += '<option value="'+ params.marka +'">' + params.marka + '</option>';
          });
        }
      };
      httpistegi.open("GET", adres, true);
      httpistegi.send();
    }

    notlariListele();
select {
  width:100px;
  height:20px;
}
<select id="slc1"></select>
<select id="slc2"></select>

A: You want to load populate two drop downs from the results of an HTTP request, where the value of the first drop down determines what options appear in the second. Your response looks something like this:
[
  {
    "marka": "BMW",
    "modeller": [
      "BMW 1000RR",
      "R 1200 Rs",
      ...
    ]
  },
  {
    "marka": "SUZUKI",
    "modeller": [
      "HAYABUSA",
      "RAIDER",
      ...
    ]
  },
  ...
]

Let's first simplify the question by ignoring the HTTP request, since it seems like you've got that part working. We can just hard code that result for now so we can focus on how the drop downs interact.
The key here is that when you change the value of the brand drop down, you need to re-populate the model drop down. You do this by listening to the change event of the brand drop down:
<select>.addEventListener("change", function(event) {
  ...
});

Then search for the brand the user is interested in by using the value that was selected. This can be done many in ways, but for this example, we'll use find:
var myItem = myArr.find(function(params){ return <some condition> });

Putting it together, we get something like this:

const jsonData = [{
    "marka": "BMW",
    "modeller": [
      "BMW 1000RR",
      "R 1200 Rs",
      "S1000rr",
      "K 1600B",
      "K 1600Gtl",
      "K 1600 gt",
      "R 1200 rt",
      "R 1200r",
      "R 1200 Gs",
      "F 750 GS",
      "G 450 X",
      "S 1000 XR"
    ]
  },
  {
    "marka": "SUZUKI",
    "modeller": [
      "HAYABUSA",
      "RAIDER",
      "GSX 1000R",
      "Gsx r1000 abs",
      "V-strom 1000",
      "V-strom  650",
      "Burgman 400z",
      "Burgman650z",
      "V-strom 250"
    ]
  },
];

const brandList = document.getElementById("brandList");
const modelList = document.getElementById("modelList");

function populateBrandList() {
  brandList.innerHTML = '';
  jsonData.forEach(function(params) {
    brandList.innerHTML += '<option value="' + params.marka + '">' + params.marka + '</option>';
  });
}
function populateModelList(brand) {
  var brandInfo = jsonData.find(function(params){ return params.marka === brand });
  if (brandInfo) {
    modelList.innerHTML = '';
    brandInfo.modeller.forEach(function(params) {
      modelList.innerHTML += '<option value="' + params + '">' + params + '</option>';
    });
  }
}

brandList.addEventListener("change", function(event) {
  populateModelList(event.target.value);
});
populateBrandList();
<select id="brandList"></select>
<select id="modelList"></select>

A: There are a couple of things to consider:

*

*As your list of models are nested at the same level as the maker in the JSON object, you can use the index of that object to more efficiently find the list of models of a selected maker. That means that instead of having the value of <option> as your maker, you would use the index in the array. For this you will have to add the index parameter to your forEach: myArr.forEach(params, index)

*For showing the relevant models when one item is selected, you will need to make use of the onchange JavaScript event, but also trigger this event at the start of page when list1 is preselected with the first value.

*For cleaner code, you will need to have access to myArr, list1 and supposedly list2 from a higher scope, so you will have to declare them outside your onreadystatechange event handler.
Having all the above considered, try to think how you could achieve this with the aid of the referenced links. Once you got it (or at least attempted), look at the code snippet below on how this could be achieved. Remember that there is no one unique way of resolving this issue but there are always better ways than others – this one should do pretty well by keeping coherence in your code.

function notlariListele(param) {
  var httpistegi = new XMLHttpRequest();
  var adres = "https://raw.githubusercontent.com/atakanbalta/Moto-karsilastirma/master/markalar.json";
  var myArr; // Store array here so that it is accessible in both functions
  var list1 = document.querySelector("#slc1");
  var list2 = document.querySelector("#slc2");

  list1.onchange = function() {
    // Empty second list first
    list2.innerHTML = '';
    myArr[this.value].modeller.forEach(function(model) {
      list2.innerHTML += '<option value="' + model + '">' + model + '</option>';
    });
  }

  httpistegi.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      myArr = JSON.parse(this.responseText);
      myArr.forEach(function(params, index) {
        list1.innerHTML += '<option value="' + index + '">' + params.marka + '</option>';
      });
      list1.onchange(); // Trigger once to populate list at first.
    }
  };
  httpistegi.open("GET", adres, true);
  httpistegi.send();

}

notlariListele();
select {
  width: 100px;
  height: 20px;
}
<select id="slc1"></select>
<select id="slc2"></select>


text:
Q: Android Service with a loop? I need to create a background service that starts and stops with two buttons. My service will cycle every 5 minutes and it will take data from an online database. I read somewhere that IntentService class is not used for loops. I would override onStartCommand so it will return START_STICKY. If i do that in this class my service doesn't start. How can I do this?
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void start(View view){
        startService(new Intent(this, ForegroundService.class));
    }

    public void stop(View view){
        stopService(new Intent(this, ForegroundService.class));
    }
}

public class ForegroundService extends IntentService{

    private boolean stato;

    public ForegroundService(){
        super("ForegroundService");
    }

    @Override
    public void onCreate(){
        super.onCreate();
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onHandleIntent(Intent i){
        stato = true;
        int n=0;
        while(stato)
        {
            Log.i("PROVA SERVICE", "Evento n."+n++);
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e)
            { }
        }
    }

    @Override
    public void onDestroy() {
        stato = false;
        Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }

}

A: Only have a service running when it is actively delivering value to the user. Sitting and watching the clock tick is not actively delivering value to the user.
Also, please understand that what you want ("cycle every 5 minutes and it will take data from an online database") may not be what the user wants and certainly is not what Google wants. Too many developers are doing stuff like this, and battery life is suffering as a result.
Generally speaking, your best solution (given your stated objective) is JobScheduler, perhaps falling back to AlarmManager if your minSdkVersion is below 21. Both of those allow you to schedule periodic work. Your process does not need to be running in between those bits of work. You teach JobScheduler or AlarmManager how frequently to trigger the work, and you do the work in a JobService or IntentService.
Just bear in mind that on Android 6.0+, unless the user tells Android via the Settings app to leave your app alone, your app will eventually enter Doze mode or app standby mode, and you will not be able to get control every five minutes.


text:
Q: cocos2d/box2d trouble I have just started working with cocos2d and box2d for iOS SDK, and have a few problems. I got the templates working, and got the test app (the one where you click the screen and a box with a random letter appears) to compile.
My first problem is that I can't figure out how to get a blank template. Is there a quick way to do this when I begin a new app?
My second problem is that I can't figure out how to just simply change the color of an object. I can define something like this:
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;

bodyDef.position.Set(p.x/PTM_RATIO, p.y/PTM_RATIO);
b2Body *body = world->CreateBody(&bodyDef);

b2CircleShape circle;
circle.m_radius = .5f;//These are mid points for our 1m box

b2FixtureDef fixtureDef;
fixtureDef.shape = &circle;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.3f;
body->CreateFixture(&fixtureDef);

But is there a simple way to make something a certain color?
Final question: does this sample app have the accelerometer-gravity enabled?
Thanks!

A: For making a certain body a specific color, assign 'userData' to the body. userData is your sprite with specific color you wanted
And reply to your final answer is YES.

A: For making blank template do the following

*

*Remove these lines from -(id) init

CCSpriteBatchNode *batch = [CCSpriteBatchNode batchNodeWithFile:@"blocks.png" capacity:150];
[self addChild:batch z:0 tag:kTagBatchNode];
[self addNewSpriteWithCoords:ccp(screenSize.width/2, screenSize.height/2)];

CCLabelTTF *label = [CCLabelTTF labelWithString:@"Tap screen" fontName:@"Marker Felt" fontSize:32];
[self addChild:label z:0];
[label setColor:ccc3(0,0,255)];
label.position = ccp( screenSize.width/2, screenSize.height-50);

*

*Remove the function

-(void) addNewSpriteWithCoords:(CGPoint)p

*

*Remove the following line from - (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

[self addNewSpriteWithCoords: location];
Try it out. :)


text:
Q: "Microsoft.Scripting.Math.BigInteger" has been removed from "MMicrosoft.Dynamic.dll" in IronPython 2.7.11 I have a plan to upgrade Iron Python of my project from V2.3.7 to 2.7.11.
When I am replacing the new IronPython package, I found that "Microsoft.Scripting.Math.BigInteger" has been removed from Microsoft.Dynamic.dll and it makes my code error.
Could you show me where to get BigInteger class to replace or any solution to fix this issue?
Thank you!

A: BigInteger was previously shipped with the dlr for older .NET (pre 4.0) versions. Given that IronPython no longer supports those targets, they removed it quite some time ago.
Nowadays you probably want to use System.Numerics.BigInteger which is supported starting with .NET 4.0.


text:
Q: Upload via Media to old folder in Wordpress I am trying to upload image from Media section in Wordpress Admin but it is taking old year folder 2015 instead of 2016. but when i upload same image from Post section then it comes to 2016 folder...
Can you please let me know how to resolve this issue?
Thanks in advance

A: *

*Go to Dashboard -> Settings -> Media

*Enter the desired location in Store uploads in this folder

*Uncheck organize my uploads into month - and year - based folders

This specify the global upload location. To specify a per-file upload location, you will need to use a Plugin, such as WP Easy Uploader
Try this...it will solve your issue.


text:
Q: "compile" vs. "compiling" vs. "compilation" From Nginx HTTP Server:

Again, problems might occur at compile time.

The phrase "compile time" confuses me because "compile" is a verb; It sounds ungrammatical to me.
The author also uses "compilation" for the same process.

If the compilation process was successful, you are ready for...

So I have two questions:
(1) Is "compile time" grammatical?
(2) Are these three phrases valid and interchangeable?

compile time
compiling time
compilation time

A: Yes, the phrase at compile time is absolutely grammatical. If something happens at compile time, it happens during the compilation process. It's actually a fixed expression and that at is very important because it's part of the expression. The only thing that might possibly be wrong with it is the fact that it's missing a hyphen between compile and time: at compile-time. You will see both versions used in technical literature. Though I prefer the one with a hyphen because grammatically it looks less confusing. If you keep reading your computer books, you will soon find out about the existence of its cousin phrase at run-time which means during the time when the program is running.
compile-time and run-time can also be used as adjectives. The most common phrasings are compile-time errors and run-time errors. Compile-time errors happen at compile-time (during the compilation process) and run-time errors happen at run-time (when the program is actually running).
Although the phrases compiling time and compilation time by themselves might be considered valid expressions in a slightly different context, at compiling-time and at compilation-time are basically non-phrases. Thus, it's a moot point to discuss them. at compile time is the one you want to stick with.

A: 'Compile' in this sense refers to the moment when a piece of written software language is run through a process called a 'compiler' which transforms it into final written, usable code. A bit like baking a cake.
'Compile-time' is the time at which this happens. It should or could be hyphenated.
Compiling time and compilation time are not used in this special context, as another answerer has explained.
The activity is spoken of usually only in terms of 'to compile'.
You could say 'my program is still compiling'. 'It's still compiling'.
You wouldn't say 'my compilation has finished' though. You'd probably say 'my compile has finished'.


text:
Q: What character encoding is this, I do not recognize it? I'm pulling data from a JSON source, and it contains a field of name, but sometimes names are outside ASCII range (special characters).
In particular, I'm working with this:

*

*Source name: Màrrát

*JSON: "char_name":"M\u00e0rr\u00e1t"

My question is: what is the encoding method used by the JSON site, so I can check if they match?


text:
Q: helper view with haml and simple_form I tried to insert a simple_form helper into a view helper (sorry for the pun) and using it with the  Haml::Helpers, example:
def front_box_search_html(form_object)
    my_custom_wrapper() do
        non_haml do
            simple_form_for( form_object ||= Form::Search.new, :url => front_search_path ) do |f|
                haml_concat f.input :phrase
                haml_concat f.button :submit
            end
        end
    end
end

but this code is not rendered correctly: all html code appears (the various html tags wrapper, the inputs and the labels) but without the  tag, As you can see this is the result (testing with RSpec, but in the browser is the same thing):
Failure/Error: helper.capture_haml{ helper.front_box_search_html }.should have_xpath("/html/body/div[@*]/form")
expected following text to match xpath /html/body/div[@*]/form:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

search title

     word
    <input class="string optional" id="form_search_phrase" name="form_search[phrase]" type="text">

    <input class = "button" id="form_search_submit" name="commit" type="submit" value="search">

to be honest I have not fully understood how to use various methods of  Haml::Helpers,  about the documentation is poor.

my env: rails 3.0.7, haml 3.1.4, simple_form 1.5.2

A: Just a guess but the 'simple_form_for' helper also outputs html so I think it should be:
haml_concat simple_form_for( form_object ||= Form::Search.new, :url => front_search_path ) do |f|
  haml_concat f.input :phrase
  haml_concat f.button :submit
end


text:
Q: Decision between an user-based and item-based filter I'm working on an algorithm to generate recommendations for a platform where you can review restaurants. So the database exists of 3 tables, 'Users', 'Restaurants' and 'Reviews'. Reviews have a rating of 1-5. Each restaurant can have multiple reviews, and users can have multiple reviews. A review can only have 1 user and 1 restaurant.
First I'll explain my current research/conclusions
I have implemented most of an user-based system, but I'm encountering several issues that come from this way of generating recommendations.
First of all, the data sparsity issue, because there is a possibility that users have a few reviews on very different restaurants, it's very difficult to determine a correlation between users.
Second I have encountered the cold-start problem. Before being able to calculate a correlation between users, you'll need around 4 reviews per review on exactly the same restaurants.
I have found a 'solution' for this by using a content-based filter. I personally don't like this way of filtering when there are better solutions (I.e. Item-based filtering)
And last, the scalability issue. Because (Hopefully) the app will become a huge success, it's going to be very heavy on the performance to calculate these correlations for each user.
Because of these issues I have decided to do some research on an item-based filter. I just would like some feedback to be sure my recommendations will be correct and to be sure I understand how this works fully.
First, you'll have to calculate a similarity correlation between restaurants, based on reviews left on said restaurants.
Example of a matrix (If I'm correct) where R1 = restaurant 1, etc.
   |  R1  |  R2  |  R3  |  R4  |
R1 |  1   | 0.75 | 0.64 | 0.23 |
R2 | 0.75 |  1   | 0.45 | 0.98 |
R3 | 0.64 | 0.45 |  1   | 0.36 |
R4 | 0.23 | 0.98 | 0.36 |  1   |

To generate recommendations for a user, you'll have to create a list of restaurants the user has reviewed positively.
Then check the matrix to see which restaurants are similar to these restaurants.
After this, you will have to check which of these restaurants the user hasn't reviewed yet. These will be recommendations for the user.
Using the item-based filter will solve most issues you'll encounter when using the user-based filter.

*

*Data sparsity. Because you don't rely on similar users anymore, you won't have the problem of 'Not enough reviews'.

*Cold start problem. Because you can base your recommendations on 1 review of the user, you won't have the cold start issues (Apart from having null data about the user)

*Scalability. You don't have to generate the similarity matrix a lot. You can do this once a day or even week. And for generating the recommendations, you can simply consult the matrix and retrieve restaurants from that.
Now my questions:
I would really like some opinions. I'm not saying any of my research are facts, I'm just wondering if I'm doing things correctly.
Am I doing everything correctly? I have done plenty of research, but since every scenario is different, I find it difficult to determine if I'm doing the right thing.
Is it true that an item-based filter is much better than an user-based one?
How exactly would you calculate a similarity between restaurants? I understand the angle between vectors, but how do you determine the points on the vectors? You can't just take reviews and put them against other reviews, since then all highest rated restaurants will be very similar. How do you set up these vectors?
In my scenario, what would be the best solution, and what similarity coefficient would be best?
Also, what would happen when my review matrix looks like this?
       |  R1  |  R2  |
User 1 |  ?   |  5   |
User 2 |  ?   |  3   |
User 3 |  5   |  ?   |
User 4 |  3   |  ?   |

Is it possible to calculate a similarity between these two restaurants? And if not, how could I fix that?
Any feedback on this would be greatly appreciated!


text:
Q: Reducing space between LineLegend row and top of frame? I am trying to reduce the space between my plot's FrameLabel, which is in the form of a LineLegend, and the top of the plot's frame. Is there an easy way to do this? A simplified version of my code is:
Plot1 = Plot[1000*Exp[-0.03*t], {t, 0, 100},
  ImageSize -> Automatic -> Medium, PlotStyle -> {Black},
  PlotRange -> {0, 1}, Frame -> {{True, True}, {True, True}},
  FrameLabel -> {None, None,
    LineLegend[{Gray, Red, Black}, {"test1", "test2", "test3"},
     LegendLayout -> {"Row", 1},
     LegendMarkers -> {{"\[FilledSquare]",
        20}, {"\[FilledUpTriangle]", 20}, {"\[FilledCircle]", 20}}]}]

A: p1 = Plot[1000*Exp[-0.03*t]
  , {t, 0, 100}
  , ImageSize -> Automatic -> Medium
  , PlotStyle -> {Black}
  , PlotRange -> {0, 1000}
  , Frame -> {{True, True}, {True, True}}
  , FrameLabel -> {{None, None}, {None, None}}
  , ImagePadding -> {{40, 10}, {30, 10}}
  ];

g1 = Graphics[
  Inset[
   LineLegend[{Gray, Red, Black}
    , {"test1", "test2", "test3"}
    , LegendLayout -> {"Row", 1}
    , LegendMarkers -> {{"\[FilledSquare]",
       20}, {"\[FilledUpTriangle]", 20}, {"\[FilledCircle]", 20}}
    , LegendMargins -> 0
    ]
   , {50, 1000}
   ]
  , PlotRange -> {{0, 100}, {995, 1005}}
  ];

Grid[{{g1}, {p1}}, Spacings -> {0, -0.4}]


text:
Q: Merge multiple dataframes - how to assign column names automatically? Let's say I have five dataframe. They all have two columns with names 'item' and 'price'. Each table represents prices of supermarket items for period 0, 1, 2, 3 and 4.
I want to merge these tables such that I have a table that shows prices of each item for different period.
In the new table I want to columns to be named price_0, price_1, price_2 etc
Is there a way to achieve this using the pd.merge function?

A: Here is one way to do it with pd.concat -

*

*First create a list of dfs

*Enumerate over the list of dfs and set 'item' as index, and add suffix to 'price' using the enumerate

*Next concatenate the list of dfs on index 'item' and reset the index.

df1 = pd.DataFrame([[1,2],[3,4],[5,6],[7,8]], columns=['item','price'])
df2 = pd.DataFrame([[1,2],[3,4],[4,6],[6,8]], columns=['item','price'])
df3 = pd.DataFrame([[1,2],[4,4],[5,6],[6,8]], columns=['item','price'])

dfs = [df1,df2,df3]
dfs = [j.set_index('item').add_suffix('_'+str(i)) for i,j in enumerate(dfs)]
print(pd.concat(dfs, axis=1).reset_index())

   item  price_0  price_1  price_2
0     1      2.0      2.0      2.0
1     3      4.0      4.0      NaN
2     4      NaN      6.0      4.0
3     5      6.0      NaN      6.0
4     6      NaN      8.0      8.0
5     7      8.0      NaN      NaN

By default pd.concat does outer joins but you can set it to do inner joins by changint it to pd.concat(dfs, axis=1, join='inner')

A: After you have merged your columns, use this list comprehension:
df.columns = [f'Price_{idx}' for idx, col in enumerate(df.columns)]


text:
Q: jQuery getJSON data not loading into tmpl I am attempting to load some json into a jQuery tmpl.
The page is here: http://stefairclough.com/jsontest/
$(document).ready(function() {

    $.getJSON("http://stefairclough.com/jsontest/json.json",
            function(data){
                $("#news_articles").empty();
                $("#news_template").tmpl( data ).appendTo("#news_articles");
            })
            .error(function(xhr) {
                    console.log(xhr)
            });
});

The json is at http://stefairclough.com/jsontest/json.js
I can't seem to figure out why it won't work.

A: Your json test file has a trailing ; remove that
[
    {"Headline": "Headline Test 1", "Url": "http://stefairclough.com"},
    {"Headline": "Headline Test 2", "Url": "http://stefairclough.com"},
    {"Headline": "Headline Test 3", "Url": "http://stefairclough.com"}
]; <--- here

A: just put your JS files above your script template
1.

2.

*Then

    $(document).ready(function() {
    $.getJSON("http://stefairclough.com/jsontest/json.js",
            function(data){
                $("#news_articles").empty();
                $("#news_template").tmpl( data ).appendTo("#news_articles");
            })
            .error(function(xhr) {
                    console.log(xhr)
            });
});
</script>

A: Seems that your XHR request is failing. Try to provide a JSON header with your JSON file. Try renaming your file :
http://stefairclough.com/jsontest/json.json

A: Your JSON does not appear to be valid JSON.
Please try linting your JSON using the following: http://pro.jsonlint.com/


text:
Q: How to Get Left Join old ID My tlb_comments are given,this table are tlb_comments table
tlb_comments :
| ID |  post_id    |   user_id     | comments  |  cm_parent  |
+----+-------------+---------------+-----------+-------------+
| 11 |      18     |  29           |  Nice     | 11          |
| 12 |      24     |  30           |  Good     | 12          |

tlb_avatar Table are Given ,this table are tlb_avatar table
tlb_avatar:
| id |  vw_id      |   image                                 |
+----+-------------+-----------------------------------------+
|  1 |      29     |  1510553363_User_Avatar_2.png           |
|  2 |      30     |  d968c2fe95629e238b04ee34599c5013.jpg   |

tlb_viewer Are Given this table are tlb_viewer table
tlb_viewer:
| id |  name         |
+----+---------------+
|  1 |      john     |
|  2 |      Quotos   |

My Left Join Query Output.
This Out put was perfect working,but I  want add to the tbl_comments id to The each row.Now time it is does not call the tbl_comments id
| id  |  post_id|  user_id | comments|  cm_parent|  vw_id | image |
+----+----------+----------+---------+-----------+--------+-------+
|  29 |  18     |   29     |  Nice   |  11       | 29     | 2.png |
|  30 |  24     |   30     |  Good   |  12       | 30     | 2.png |

Its Query Output was Good. However I want tlb comment Id(tbl_comments id)   to each row.
I'm Explain Given  table. Here we want last column tbl_comments id(comment ID).
This table is I'm Expecting Table.HOW TO GET???????
| id  |  post_id|  user_id | comments|  cm_parent|  vw_id |comment ID  |
+----+----------+----------+---------+-----------+--------+------------+
|  29 |  18     |   29     |  Nice   |  11       | 29     | 11         |
|  30 |  24     |   30     |  Good   |  12       | 30     | 12         |

MYSQLI QUERY:
That Query is my mysqli query :
$qid = $quotos->id;

 $avatar = mysqli_query($conn,"SELECT * FROM tlb_comments LEFT JOIN     tlb_avatar ON tlb_avatar.vw_id = tlb_comments.user_id LEFT JOIN tlb_viewer
                                                        ON tlb_viewer.id = tlb_comments.user_id  WHERE   tlb_comments.post_id = '".$qid."'"  );
                            while($comments = mysqli_fetch_object($avatar)){}

A: If you use select * then the column lists of the joined tables are output in the same order as their tables are joined. If you want the columns in a different order then list the columns.
select user_id as id,
    post_id, user_id, comments, cm_parent,
    vw_id, image,
    tlb_comments.ID as 'comment ID'
from tlb_comments
left join tlb_avatar
...


text:
Q: VARBINARY(SQLSERVER) to RAW(ORACLE) via CSV created using SQLCMD I am trying to export JBPM tables from SQLSERVER in CSV file using SQLCMD and I wish to import it to ORACLE DB. Table structures as follows:
SOURCE table columns(SQLSERVER) :
[PROCESSFILE_] [numeric](19, 0) ,
[BYTES_] [varbinary](1024) ,
[INDEX_] [int]

TARGET table columns (ORACLE) :
[PROCESSFILE_] NUMBER(19,0) ,
[BYTES_] RAW(1024),
[INDEX_] NUMBER(10,0)

I am using SQLLDR to load the data into ORACLE and I'm getting following error:
Record 53: Rejected - Error on table JBPM_BYTEBLOCK_TEST, column BYTES_.
Field in data file exceeds maximum length

My controlfile looks something like this:
load data
    infile 'JBPM_BYTEBLOCK.csv'
           into table JBPM_BYTEBLOCK_TEST
fields terminated by ","
(PROCESSFILE_, BYTES_ ,INDEX_)

Can anyone suggest how to fix this and get the hex data imported to oracle? Is it even possible through CSV?
Since I'm new to this i'd also like to know is there any better approach than CSV?
Note: My target DB is on AWS and we have connectivity issues between the two databases.


text:
Q: Android: what should I use for android push notification? Google Cloud Messaging or Parse.com I am working on an android project. Can anyone give me an idea what should I use for notification ? Using GCM it seems to be hard to implement where as using parse.com its seems easier. But is it recommended to use parse.com for notification?
Thanks in advance...

A: Nil, you have not mentioned two things. Is your app communicates with cloud/Server? And what is the backend your using, parse.com or something else(PHP,Java,.Net)?
Well, if you're using Parse.com as your backend support, i would recommend to use Parse push notifications. Parse uses GCM for Android push notifications.
If your backend is some other server, i will opt for GCM as you don't need to maintain data again on the parse. If you have different backend and want to use parse, app should communicate with the two servers one for actual communication and other for storing your device ID into parse.


text:
Q: Azure Data Factory web activity to retrieve bearer token I want to invoke an api that returns bearer token (GET method). I can fetch Bearer Token successfully using .Net code. But with ADF I get only 'OK' and I see no option to fetch the Bearer Token.
Example:
ApiUrl = "https://myapi.mysite.org/api/ApiToken?user=u111&password=p111"
if status code = 'OK' then deserialize result content to fetch toekn.
Sample .Net code I used to fetch Bearer Token successfully:
var result = client.PostAsync(ApiUrl).Result;
string strRes = result.StatusCode.ToString();
if (strRes == "OK")
{
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject(result.Content.ReadAsStringAsync().Result);
varToken = obj.Token;
}

A: Use POST method in Azure data factory web activity to get the access token from an API.
Add header as content-Type: application/x-www-form-urlencoded and pass the access credentials in the body part.
You can refer to this link1 & link2 for working examples.


text:
Q: Correct Way for Celery Process Architecture and demonizing I have a Python/Django Project running on uwsgi/nginx. For asynchronous task we are using rabbitmq/celeryd and supervisord to manage all the daemons
Versions:

*

*python: 2.7

*django: 1.9.7

*celery: 3.1.23

*django-celery: 3.1.17

Celery has 10 queue of type Direct (say queue1, queue2, ...)
Each queue is handled by a separate celeryd process which is manage via supervisord. each supervisord process looks as following
[program:app_queue_worker]
command=/var/www/myproj/venv/bin/celery worker -A myproj -c 2 --queue=queue1 --loglevel=INFO
directory=/var/www/myproj/
user=ubuntu
numprocs=1
autostart=true
autorestart=true
startsecs=10
exitcodes=1
stopwaitsecs = 600
killasgroup=true
priority=1000

Hence Supervisord is running 10 Mainprocess and 20 Worker process
Other Thing I have noticed is uwsgi also spawns some celery workers(Dont understand how and why, YET )  with concurrency=2. So if I have 4 uwsgi process running i will have an addition 10 celery workers running
All these workers are each taking 200-300M memory? Something is wrong here I feel it but I am not able to put my finger on it. Celery shouldn't be running such memory heavy process?
Note: Debug=False, there is no memory leakage due to debug
Can someone please comment on the architecture if it is correct or wrong?
Would it be better to run 2-3 celery MainProcesses which listen all queues at once and increase its concurrency?
Update : celery.py Config
from celery import Celery

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings')

from django.conf import settings  # noqa
from chatterbox import celery_settings

app = Celery('MyProject')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')

app.conf.update(
    CELERY_RESULT_BACKEND='djcelery.backends.database:DatabaseBackend',
    CELERYD_CONCURRENCY=1,
)

app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

A: There is no simple answer to this.
To me, the fact that uwsgi spawns celery workers is wrong.
Creating only worker processes that consume all queues might lead to the situation where long running tasks make some queues overflow whereas separate workers that consume specific queues with short running tasks could make the situation better. Everything depends on your use case.
The 300mb residual memory is quite a lot. If the tasks are i/o bound go multi-thread/gevent. However, if the tasks are CPU bound, you have no other option than to scale process wise.

A: If you start a celery worker with concurrency of n, it will spawn n + 1 process by default. Since you are spawning 10 workers with a concurrency of 2, celery will start 30 processes.
Each worker consumes ~60MB(~30MB for main process & 2*~15MB for subprocesses) of memory when not consuming queues. It might vary depending what your worker is doing. If you start 10 workers, it will consume ~600MB of memory.
I am not sure how you came to know that uwsgi also spawns some celery workers. Only supervisor should spawn the process.
You can run just 1 celery worker which listens to all queues with a concurrency of 20. This will reduce your memory usage at the cost of flexibility. With this setup, you can't start/stop consuming from selected queues. Also, there is no guarantee that all queues will be consumed equally.


text:
Q: Problem installing oniguruma gem on Snow Leopard I'm on Snow Leopard 10.6.4, Intel architecture.
I've got rvm and ruby 1.9.2 installed:
$ rvm list
rvm rubies

=> ruby-1.9.2-p0 [ x86_64 ]

I installed oniguruma5 like this:
port install oniguruma5

Then, as per Conventional Wisdom, I tried to install the oniguruma gem like this:
sudo gem install oniguruma -- --with-opt-dir=/opt/local

But I get a compile error:
Julie:lender bhaupt$ sudo gem install oniguruma -- --with-opt-dir=/opt/local
Building native extensions.  This could take a while...
ERROR:  Error installing oniguruma:
 ERROR: Failed to build gem native extension.

/Users/bhaupt/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb --with-opt-dir=/opt/local
checking for main() in -lonig... yes
creating Makefile

make
gcc -I. -I/Users/bhaupt/.rvm/rubies/ruby-1.9.2-p0/include/ruby-1.9.1/x86_64-darwin10.4.0 -I/Users/bhaupt/.rvm/rubies/ruby-1.9.2-p0/include/ruby-1.9.1/ruby/backward -I/Users/bhaupt/.rvm/rubies/ruby-1.9.2-p0/include/ruby-1.9.1 -I. -I/opt/local/include -D_XOPEN_SOURCE -D_DARWIN_C_SOURCE   -fno-common -Wall  -o oregexp.o -c oregexp.c
oregexp.c: In function 'name_callback':
oregexp.c:111: warning: pointer targets in passing argument 1 of 'strlen' differ in signedness
oregexp.c:111: warning: pointer targets in passing argument 1 of 'rb_intern2' differ in signedness
oregexp.c:111: warning: pointer targets in passing argument 1 of 'rb_intern' differ in signedness
oregexp.c: In function 'oregexp_initialize':
oregexp.c:123: error: 'struct RString' has no member named 'ptr'
oregexp.c:124: error: 'struct RString' has no member named 'len'
oregexp.c:138: warning: pointer targets in passing argument 1 of 'onig_error_code_to_str' differ in signedness
oregexp.c: In function 'oregexp_make_match_data':
oregexp.c:176: warning: passing argument 2 of 'onig_foreach_name' from incompatible pointer type
oregexp.c: In function 'oregexp_match':
oregexp.c:211: warning: statement with no effect
oregexp.c:215: error: 'struct RString' has no member named 'ptr'
oregexp.c:216: error: 'struct RString' has no member named 'len'
oregexp.c:244: warning: pointer targets in passing argument 1 of 'onig_error_code_to_str' differ in signedness
oregexp.c: In function 'oregexp_append_replacement':
oregexp.c:267: error: 'struct RString' has no member named 'len'
oregexp.c:268: error: 'struct RString' has no member named 'ptr'
oregexp.c:277: error: 'struct RString' has no member named 'ptr'
oregexp.c:278: error: 'struct RString' has no member named 'len'
oregexp.c:286: warning: format '%d' expects type 'int', but argument 2 has type 'OnigCodePoint'
oregexp.c:293: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:297: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:328: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:332: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:336: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:341: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:350: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:371: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:379: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:385: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:392: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c: In function 'str_mod_check':
oregexp.c:405: error: 'struct RString' has no member named 'ptr'
oregexp.c:405: error: 'struct RString' has no member named 'len'
oregexp.c: In function 'oregexp_gsub':
oregexp.c:444: error: 'struct RString' has no member named 'ptr'
oregexp.c:445: error: 'struct RString' has no member named 'len'
oregexp.c:462: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:484: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c:491: warning: pointer targets in passing argument 2 of 'rb_str_buf_cat' differ in signedness
oregexp.c: In function 'oregexp_safe_gsub':
oregexp.c:527: warning: passing argument 3 of 'rb_ensure' from incompatible pointer type
oregexp.c: In function 'oregexp_scan':
oregexp.c:614: error: 'struct RString' has no member named 'ptr'
oregexp.c:615: error: 'struct RString' has no member named 'len'
oregexp.c: In function 'oregexp_m_scan':
oregexp.c:671: warning: passing argument 3 of 'rb_ensure' from incompatible pointer type
make: *** [oregexp.o] Error 1

Gem files will remain installed in /Users/bhaupt/.rvm/gems/ruby-1.9.2-p0/gems/oniguruma-1.1.0 for inspection.
Results logged to /Users/bhaupt/.rvm/gems/ruby-1.9.2-p0/gems/oniguruma-1.1.0/ext/gem_make.out

Ideas?
I have confirmed that /opt/local/include contains oniggnu.h, onigposix.h, and oniguruma.h

A: My solution is the simplest (if you are a mac user):
brew install oniguruma

A: I am Dizan, oniguruma and ultraviolet's main developer, sorry for taking so long to answer this!
As Jo Liss comments, the purpose of the oniguruma bindings was to provide access to some advanced regular expression functionality that is now standard with Ruby 1.9. So, in principle, there is no need for this on 1.9.
Compiling the oniguruma bindings for 1.9, it is completely untested so you're more or less in your own, but, in principle, it would be easy to patch both ultraviolet and textpow to use standard regexps in 1.9. Of course that's in my todo list but, unfortunately, right now I barely have the time for that. On the other hand, some people has expressed interest in forking or taking over the project(s) which would make things faster. I will keep you posted on this.
One last alternative would be to do the patch yourself which is not as daunting as it sounds: as far as I remember,  all you have to do is to replace all calls to ORegexp#new by the standard Regexp#new, if you decide to go that way I would be happy to provide assitance an to include your patch in the next release of ultraviolet/textpow.

A: (I'm having the same problem when I try install oniguruma-ruby with Ruby 1.9 on Debian.)
So, http://oniguruma.rubyforge.org/ says:

This library provides bindings to Oniguruma, a regular expression library which is standard with Ruby 1.9. It allows users of Ruby 1.8 to access the extended functionality without the need to recompile or to upgrade Ruby.

It doesn't sound like oniguruma-ruby can be installed on 1.9 at all.
Question to Dizan (to whom I've sent a pointer to this question): But even if Oniguruma is standard in Ruby 1.9, if I want to run a module that has require 'origuruma', I'll still need origuruma-ruby, right?  So having it compatible with Ruby 1.9 would still kindof make sense, as there is no other way to get, say, Textpow or Ultraviolet running on Ruby 1.9 -- or am I missing something?

A: Oniguruma use Ultraviolet, Ultraviolet uses, Textpow, and you will use Tylenol to get all of these dependencies lined up.
Once you get all of the dependencies lined up make sure you include the library for ultraviolet with config.gem 'oniguruma', :lib => 'ultraviolet'
I will double check that library later, I'm on another computer but not including it was a problem for me.

A: I'd had the same error, but I tried
sudo port install oniguruma

and got told
Error: Target org.macports.fetch returned:

        Please use either
            oniguruma4 (for ruby support)
        or
            oniguruma5 (for unicode support)

since I was trying to build a ruby gem, I installed oniguruma4 instead of oniguruma5.  Having done that, the gem installed cleanly except for a warning while generating the documentation (No definition for oregexp_initialize)


text:
Q: How can I make that php webpages expire in certain time For security reasons, several articles recommend "do not cache pages". So I usually put the following at the beginning of my web pages
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

That works very well, but many of the visitors likes to use the history buttons. So, I need to allow it for a short period.
I tried to use the following headers
header("Cache-Control: maxage=".$expires.", must-revalidate");
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');

where $expires is the time I need. The problem is that pages do not expire, as if those headers were not there. How can I solve this?

A: In short: Browser history caching is something different that you can not entirely control. There is a perfect and exhaustive answer to another question, that also answers your question over here:
Why both no-cache and no-store should be used in HTTP response?


text:
Q: Using reflection to get namespace from ASP.NET template code-behind class? I'm trying to get the namespace from ASP.NET template (.aspx) code-behind class. The code-behind file contains something like:
namespace MyTopNamespace.SubNamespace
{
    public partial class PageClass : System.Web.UI.Page
    {
        // ...
    }
}

And I'm passing an instance of this PageClass to the following method.
private static string GetNamespace(Page page)
{
    const string desiredPart = "MyTopNamespace";
    if (page == null)
    {
        throw new ArgumentNullException("page");
    }
    string pageNamespace = page.GetType().FullName;

    // For debugging
    string pageAssembly = page.GetType().Assembly.FullName;
    string pageAsmQualified = page.GetType().AssemblyQualifiedName;

    if (!pageNamespace.Contains(desiredPart) &&
        !pageAssembly.Contains(desiredPart) &&
        !pageAsmQualified.Contains(desiredPart))
    {
        throw new ApplicationException(string.Format(
            "Unexpected namespace or assembly: \n\n'{0}'\n'{1}'\n'{2}'",
             pageNamespace, pageAssembly, pageAsmQualified));
    }
    // Remaining implementation ...
}

Exception output:

Unexpected namespace or assembly:
'ASP.pageclass_aspx'
'App_Web_pageclass.aspx.cdcab7d2.v4dudq3x, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
'ASP.pageclass_aspx, App_Web_pageclass.aspx.cdcab7d2.v4dudq3x,
  Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'

What happened to MyTopNamespace, and can it be obtained from the type using reflection?

A: This is because the page is compiled at runtime, which then gives it a temporary assembly, namespace and sometimes a temporary class name as well (it seems not in this example). There is no way to retrieve the previous namespace from a page instance that has been instantiated through runtime compilation.


text:
Q: SQL Combining data from 3 tables to from a 4th table based on some conditions I have 3 tables:-
table1 :-
ReportType | ResourceId
  t2         123
  t3           5

table2:-
   Id | Name | Created
   1     A      10
   2     B      11
   123   C      12

table3:-
Id | Name | Created
4     D       13
5     E       14
6     F       15

table1's ResourceId and table2 and 3's Id column have same values
I want to create a 4th table like this:-
ReportType | ResourceId | Name | Created
t2             123         C      12
t3              5          E      14

such that wherever table1's ReportType is t2 I want the Name and Created value from table2 for the condition table1.ResourceId = table2.Id and wherever table1's ResourceType is t3 I want the Name and Created value from table3 for the condition table1.ResourceId = table3.Id.
PS: This isn't some sort of HomeWork. I have been stuck at this query for the past 1 hour, I have read various answers and tried a few queries of my own before posting the question. Any help would really be appreciated.

A: Explanation in comments :)
--here we join first and second table, but we filter results to include only ReportType = t2
select t1.ReportType, t1.ResourceId, t2.Name, t2.Created from table1 as t1 join table2 as t2 on t1.ResourceId = t2.id
where t1.ReportType = 't2'

union all

--here we join first and third table, but we filter results to include only ReportType = t3
select t1.ReportType, t1.ResourceId, t3.Name, t3.Created from table1 as t1 join table3 as t3 on t1.ResourceId = t3.id
where t1.ReportType = 't3'

A: You can use the below query:
select report_type, resourceid,name, created from dbo.t2, dbo.t1
where report_type='t2' and ResourceId=id
UNION
select report_type, resourceid,name, created from dbo.t3, dbo.t1
where report_type='t3' and ResourceId=id;


text:
Q: Pdf does not showing product image? Magento 2 When printing the order pdf, product image is not showing. When I var dump the imagePath I get result:
string(150) "http://mysite/media/catalog/product/cache/15/thumbnail/75x75/beff4985b56e3afdbeabfc89641a4582/b/j/bj9660_02_reebok_les_mills_zenski_sorc.jpg"

This is the code that returns an image:
$image = [
      'items_small_image' => [
      'value' => '',
      'label' => __('Product image'),
   ],
];

But, when I hard code the image path the the image is showing:
$image = [
      'items_small_image' => [
      'value' => '',
      'label' => __('Product image'),
   ],
];

What is the problem with variable? Did anybody had the same issue?


text:
Q: Load an Object using Gson Forgive me if this is trivial or not possible but I'm having a Monday morning moment here.
I'd like to create a method that implements some methods from the Gson library to loaded some settings Objects. Basically, I have a bunch of different settings objects but I don't want to habe to override the load method for each class to I'd like to have something like:
public class ConfigLoader {
    public static void main(final String[] args) {
        final ConfigurationSettings loadedConfigSettigs =
            load("testSettings.json", ConfigurationSettings.class);

        final AlternativeConfigurationSettings alternativeConfigSettigs =
            load("testSettings2.json", AlternativeConfigurationSettings .class);
    }

    public T load(final InputStream inputStream, final Class<T> clazz) {
        try {
            if (inputStream != null) {
                final Gson gson = new Gson();
                final BufferedReader reader =
                    new BufferedReader(new InputStreamReader(inputStream));
                return gson.fromJson(reader, clazz);
            }
        } catch (final Exception e) {
        }
        return null;
    }
}

where I can pass in the InputStream and the class of the object I want to return. Is there a simple way to do this (I don't want to have to create a method for each Class I want to be able to load, nor do I want to have to create a specific loader for each class)?

A: The following code works (requires Java 1.5 or above):
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import com.google.gson.Gson;

public class ConfigLoader {
    public static void main(final String[] args) {
        final ConfigurationSettings loadedConfigSettigs = load(new FileInputStream(new File("testSettings.json")),
                ConfigurationSettings.class);

        final AlternativeConfigurationSettings alternativeConfigSettigs = load(new FileInputStream(new File("testSettings2.json")),
                AlternativeConfigurationSettings.class);
    }

    public static <T> T load(final InputStream inputStream, final Class<T> clazz) {
        try {
            if (inputStream != null) {
                final Gson gson = new Gson();
                final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                return gson.fromJson(reader, clazz);
            }
        } catch (final Exception e) {
        }
        return null;
    }
}


text:
Q: Matching occurrence in string with regex for value replacement? I've spent some time on this problem but really need help from a regex guru.
So far I have the following which doesn't quite give me what I need.
[.*?]\s[=><]+\s[@]\w+
From the following sample string, I need all occurrences of a field followed by a parameter\variable. A parameter starts with an '@'.
I am then going to use the result to replace the contents of each value in .net.
Therefore, the regex expression would match
[System.TeamProject] = @project
[Microsoft.VSTS.Common.ClosedDate] >= @startOfDay
[Microsoft.VSTS.Common.ClosedDate] >= @startOfDay

Note [System.State] = 'Closed' is not matched.
Sample string
select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = @project and [Microsoft.VSTS.Common.ClosedDate] >= @startOfDay and [System.State] = 'Closed' and [Microsoft.VSTS.Common.ClosedDate] >= @startOfDay

Thanks heaps!

A: This regex should do what you want:
\[([^]]*)]\s+[><=]+\s+(\@\w+)

The main change is that the [ and ] in the initial part of your regex needed to be escaped. I have also added capture groups to collect the field name (group 1) and parameter value (group 2).
Demo on regex101

A: My guess is that maybe you're trying to write some similar expression to:
\[([^\]]*)\]\s*(=|>=|<=)\s*(@\w+)

and replace with some string similar to:
[new_value] $2 $3

I've added some capturing groups, wasn't sure about the desired output, you can simply remove or modify those if/as you wish.
Demo
Test
using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\[([^\]]*)\]\s*(=|>=|<=)\s*(@\w+)";
        string substitution = @"[new_value] $2 $3";
        string input = @"select [System.Id], [System.WorkItemType], [System.Title], [System.AssignedTo], [System.State], [System.Tags] from WorkItems where [System.TeamProject] = @project and [Microsoft.VSTS.Common.ClosedDate] >= @startOfDay and [System.State] = 'Closed' and [Microsoft.VSTS.Common.ClosedDate] >= @startOfDay

Note [System.State] = 'Closed' is not matched.";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

RegEx Circuit
jex.im visualizes regular expressions:


text:
Q: In php, how to include the exact content (not string form) from another file? Let be an annex file named annex.txt , whose content is: "text1","text2","text3"
Now, I have a php file which contains this line:
$alfa = array ("text1","text2","text3");

How can I include the array elements using the external file annex.txt ?
Something like this:
$alfa = array ( file_get_contents('/annex.txt') ) ;

But, in this variant, $alfa will have just one element: $alfa[0] , which includes all the text as a whole string. So, how can I obtain $alfa[0] = "text1" , $alfa[1] = "text2" , $alfa[2] = "text3" ?
I know the function file() returns an array, but I wouldn't like to use it. I want to use file_get_contents().

A: You should use fgetcsv or str_getcsv.
$alfa = str_getcvs(file_get_contents('annex.txt'));

A: $alfa =  file_get_contents('annex.txt') ;
$pieces = explode(",", $alfa);
echo $pieces[0]; // text1
echo $pieces[1]; // text2
....
....

A: Try something like this:
$alfa = explode(',', file_get_contents('/annex.txt'));


text:
Q: How to set item height equal to FlatList height in react native? I have a vertical flat list with paging enabled. I want to make each item covering the flat list height.

A: You can specify the height of each rendered item to the window height
height : Dimensions.get('window').height

A: Setting flexGrow:0 for the Flatlist solved it for me! Thanks all

A: I'm using a ScrollView Horizontal. For me fixed setting height: 100% for the items list.
before fixed
after fixed


text:
Q: Optimize sql request for statistics I would like to perform some request in mysql that i know will be really slow:
I have 3 tables:
Users:
id, username, email

Question:
id, date, question

Answer
id_question, id_user, response, score

And i would like to do some statistics like the top X users with the best score (sum of all the scores) for all time or for a given amount of time (last month for example). Or it could be users between the 100th and the 110th range
I will have thousands of users and hundred of questions so the requests could be very long since I'll need to order by sum of scores, limit to a given range and sometimes only select some questions depending on the date, ...
I would like to know if there are some methods to optimize the requests!

A: For archived statistics, you can create tables that store rankings that won't move (last year, last month, last day). Try to calculated as much as possible statistics in such tables, put indexes on id_user, date, type_of_ranking...
Try to limit as much as possible subqueries.

A: If you have a lot of data no other choices, Only you can optimize it with creating new table that will somehow summarizes data in every day/week or month. Maybe summarizes scores by each week for users and stamps by that weeks date, or by month. As the range of summing longer as much your query works fast.


text:
Q: P: TDA y PUNTEROS en c Alguien sabe como puedo solucionar este "error", lo que necesito hacer es acceder a la variable puntaje pero tengo que acceder a cartonJugador primero algo asi ---> j->cartonJugador[0].puntaje pero por algo motivo me tira error cuando hago eso o j->cartonJugador[0]->puntaje tampco me funciona.
¿Alguien tiene alguna solución para este problema que tengo?
#include <stdio.h>
#include <stdlib.h>
struct Carton{

    int puntaje;
};
typedef struct Carton *cartones;

struct Jugador {

    cartones cartonJugador[3];

};
typedef struct Jugador *jugadores;

int main()
{

    return 0;
}

void prueba(cartones c){

jugadores j;

j->cartonJugador[0].puntaje; // acá
j->cartonJugador[0]->puntaje; //y acá

}

A: cartonJugador es un arreglo de apuntadores así que primero tienes que indicar cual cartonJugador estas tratando de usar para luego ir con la flecha.... y si no me equivoco, dado que estas usando apuntadores, vas a tener que reservar memoria para poder usarlos (usar malloc, calloc y tal). Sacando el tema de reservar la memoria del problema, la forma de utilizarlo seria:
j->cartonJugador[0]->puntaje // el índice puede ir de 0 a 2


text:
Q: Setting chrome capabilities in application.properties file using QAF Automation framework is not working I'm new to using QAF Automation framework. I followed the documentation on this page - https://qmetry.github.io/qaf/latest/setting_driver_capabilities.html
My requirement is: I have to download a file in my test and the download should go to my project's download folder and not on macbook/test machine's download folder.
I'm using chromeDriver and have to set chrome capabilities in the application.properties file within QAF framework. I added the below but it's not working
chrome.capabilities.profile.default_content_settings.popups=0
chrome.capabilities.download.default_directory=/downloads
chrome.capabilities.credentials_enable_service=false
chrome.capabilities.profile.password_manager_enabled=false
chrome.capabilities.CapabilityType.ACCEPT_SSL_CERTS=true
chrome.additional.capabilities={"chrome options":{"args":["--headless -
-disable-gpu"]}}

I also tried directly using chrome.additional.capabilities for all the capabilities I wanted to set, like below, and it didn't work either
 chrome.additional.capabilities={"chrome options":{"args":["--allow-
 outdated-plugins","--always-authorize-plugins","--headless --disable-
 gpu","-disable-extensions"]},"prefs":
 [{"profile.default_content_settings.popups":0},
 {"download.default_directory":"/downloads"},
 {"credentials_enable_service":false},
 {"profile.password_manager_enabled":false}]}

When I execute my test, the test runs successfully and passes but the file is downloaded to my macbook download directory and not within my project specific download folder I've set using capabilities.
I tried using chromeDriver.capabilities instead of chrome.capabilities with no success.
Can anyone who used QAF before, help me with solving this issue?

A: Few correction needs in additional capability value:

*

*Key for chrome options is chromeOptions

*preferences is also one of the option which requires map with key prefs

*Try providing absolute path for download directory.

Your additional capability should look like below (make sure there is no line break):
 chrome.additional.capabilities={"chromeOptions":{"args":["--allow-
 outdated-plugins","--always-authorize-plugins","--headless --disable-
 gpu","-disable-extensions"],"prefs":
 {"profile.default_content_settings.popups":0,
 "download.default_directory":"/usr/workspace/testproject/downloads",
 "credentials_enable_service":false,
 "profile.password_manager_enabled":false}}}

Refer chromeOptions-object
EDIT:
depending on driver version, you may required to add goog prefix in chrome specific capabilites, for example:
chrome.additional.capabilities={"goog:chromeOptions":{"args":["start-maximized","--ignore-certificate-errors"]}}

Below example shows how you can append capability with complex object before driver initialization using listener. For instance, in order to use Firefox profile you can utilize qaf driver listener.
@Override
public void beforeInitialize(Capabilities desiredCapabilities) {
    FirefoxProfile profile= new FirefoxProfile();
    //create and set profile as per need
    profile.setPreference( "layout.css.devPixelsPerPx", "0.9" );
    ((DesiredCapabilities)desiredCapabilities).setCapability(FirefoxDriver.PROFILE, profile);

   //you also can provide existing profile name. AFAIK firefoxdriver supports existing profile name as well.
   //((DesiredCapabilities)desiredCapabilities).setCapability(FirefoxDriver.PROFILE, "my-profile");
}

@Override
    public void beforeInitialize(Capabilities desiredCapabilities) {
        ChromeOptions options = new ChromeOptions();
        //set options and merge to capabilites
        //options.addExtensions(paths);
        desiredCapabilities.merge(options);
    }

A: Below settings are placed in application.properties file.
For Chrome:
driver.name=chromeDriver
chrome.capabilities={"chromeOptions":{"args":["--allow-outdated-plugins","--always-authorize-plugins","--headless --disable-gpu","-disable-extensions"],"prefs":{"profile.default_content_settings.popups":0,"download.default_directory":"C:\\server","credentials_enable_service":false,"profile.password_manager_enabled":false}}}
webdriver.chrome.driver =C:/server/chromedriver.exe

Below setting worked for me for IE11
driver.name=iExplorerdriver
system.webdriver.ie.driver = C:/server/IEDriverServer.exe
iexplorer.additional.capabilities={'ignoreProtectedModeSettings':true}
iexplorer.additional.capabilities={'nativeEvents':false}
iexplorer.additional.capabilities={'unexpectedAlertBehaviour':accept}
iexplorer.additional.capabilities={'enablePersistentHover':true}
iexplorer.additional.capabilities={'ignoreZoomSetting':true}
iexplorer.additional.capabilities={'requireWindowFocus':true}
iexplorer.additional.capabilities={"ignoreProtectedModeSettings":"true",'nativeEvents':false,'unexpectedAlertBehaviour':accept,'enablePersistentHover':true,'ignoreZoomSetting':true,'requireWindowFocus':true}
iexplorer.additional.capabilities={'ignoreProtectedModeSettings':true,'nativeEvents':false,'unexpectedAlertBehaviour':accept,'enablePersistentHover':true,'ignoreZoomSetting':true,'requireWindowFocus':true}

A: Thanks @user861594 for answering the question.
I recently found out an easier way to set this chrome capabilities in the BaseTestCase class itself and not in application.properties.
Here is what I did and it worked wonderfully!!
Declare your filePath = "xyz";
String chromePrefs = "{'acceptSslCerts': true,'chromeOptions':   {'prefs': {'prompt_for_download': false,'download.default_directory': '"+filePath+"'}}}";
      ConfigurationManager.getBundle().setProperty("chrome.additional.capabilities", chromePrefs);

Enjoy automating!


text:
Q: How to set 404 page response header IIS? I have a custom 404 page I've made (hardcoded page in html / tiny bit of php)
I'm using iis7, and am using the web.config file to redirect to my 404 page:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
    <httpErrors errorMode="Custom">
        <remove statusCode="404" subStatusCode="-1" />
        <error statusCode="404" prefixLanguageFilePath="" path="/404.php" responseMode="Redirect" />
    </httpErrors>
</system.webServer>
</configuration>

This is producing a "soft 404" - in other words the response header is giving code 200 (all ok) instead of code 404.
How do I change that to give a response header of code 404.
Do I do that on the page, or in the web.config file?
I've read a lot of posts on this and tried a lot of things without success, so any pointers would be very much appreciated!
Thanks,
Phil.

A: I found the answer.
All you need to do is add a line in php to set the header:
<?php
    header("HTTP/1.0 404 Not Found");
?>