问:
How to permute an array in PySpark?
I have a DataFrame column with an array of strings. I've tried creating a udf and using numpy to permute (unit is the column name):

```<code>def permute(row):
    return np.random.permutation(row)

udfPermute = udf(permute, ArrayType(StringType()))

print(units.withColumn("shuffled", udfPermute("unit")).head(5))

Py4JJavaError: An error occurred while calling o4246.collectToPython.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 871.0 failed 1 times, most recent failure: Lost task 0.0 in stage 871.0 (TID 1224, localhost, executor driver): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.core.multiarray._reconstruct)
    at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23)
    at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707)
    at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175)
    at net.razorvine.pickle.Unpickler.load(Unpickler.java:99)
    at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:156)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:155)
    at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:333)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply$mcI$sp(Dataset.scala:2745)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2742)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2742)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
    at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2765)
    at org.apache.spark.sql.Dataset.collectToPython(Dataset.scala:2742)
    at sun.reflect.GeneratedMethodAccessor77.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:745)
Caused by: net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.core.multiarray._reconstruct)
    at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23)
    at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707)
    at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175)
    at net.razorvine.pickle.Unpickler.load(Unpickler.java:99)
    at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:156)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:155)
    at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more

In [161]:
</code>```

How can I accomplish this?

答:
You are returning a numpy array, you need to return a list instead.

Change your UDF as below and it should work.

```<code>def permute(row):
    return np.random.permutation(row).tolist()
</code>```

Title: How to permute an array in PySpark?

Body:
I have a DataFrame column with an array of strings. I've tried creating a udf and using numpy to permute (unit is the column name):

def permute(row):
    return np.random.permutation(row)

udfPermute = udf(permute, ArrayType(StringType()))

print(units.withColumn("shuffled", udfPermute("unit")).head(5))

Py4JJavaError: An error occurred while calling o4246.collectToPython.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 871.0 failed 1 times, most recent failure: Lost task 0.0 in stage 871.0 (TID 1224, localhost, executor driver): net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.core.multiarray._reconstruct)
    at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23)
    at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707)
    at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175)
    at net.razorvine.pickle.Unpickler.load(Unpickler.java:99)
    at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:156)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:155)
    at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

Driver stacktrace:
    at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1435)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1423)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1422)
    at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1422)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:802)
    at scala.Option.foreach(Option.scala:257)
    at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:802)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.doOnReceive(DAGScheduler.scala:1650)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1605)
    at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1594)
    at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48)
    at org.apache.spark.scheduler.DAGScheduler.runJob(DAGScheduler.scala:628)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1918)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1931)
    at org.apache.spark.SparkContext.runJob(SparkContext.scala:1944)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:333)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply$mcI$sp(Dataset.scala:2745)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2742)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2742)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
    at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2765)
    at org.apache.spark.sql.Dataset.collectToPython(Dataset.scala:2742)
    at sun.reflect.GeneratedMethodAccessor77.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:745)
Caused by: net.razorvine.pickle.PickleException: expected zero arguments for construction of ClassDict (for numpy.core.multiarray._reconstruct)
    at net.razorvine.pickle.objects.ClassDictConstructor.construct(ClassDictConstructor.java:23)
    at net.razorvine.pickle.Unpickler.load_reduce(Unpickler.java:707)
    at net.razorvine.pickle.Unpickler.dispatch(Unpickler.java:175)
    at net.razorvine.pickle.Unpickler.load(Unpickler.java:99)
    at net.razorvine.pickle.Unpickler.loads(Unpickler.java:112)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:156)
    at org.apache.spark.sql.execution.python.BatchEvalPythonExec$$anonfun$doExecute$1$$anonfun$apply$6.apply(BatchEvalPythonExec.scala:155)
    at scala.collection.Iterator$$anon$12.nextCur(Iterator.scala:434)
    at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:440)
    at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
    at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIterator.processNext(Unknown Source)
    at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
    at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$8$$anon$1.hasNext(WholeStageCodegenExec.scala:377)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:231)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:225)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$25.apply(RDD.scala:826)
    at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:38)
    at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:323)
    at org.apache.spark.rdd.RDD.iterator(RDD.scala:287)
    at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
    at org.apache.spark.scheduler.Task.run(Task.scala:99)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    ... 1 more

In [161]:

How can I accomplish this?

Body:
You are returning a numpy array, you need to return a list instead.

Change your UDF as below and it should work.

def permute(row):
    return np.random.permutation(row).tolist()


来源: stackexchange

问:
Finding a number that is divisible by all numbers from 1 through 10 evenly
I want to find a number that is divisible by all numbers between 1 and 10. My code sample prints out all the numbers that are divisible.  However how would I go about approaching the problem to get just the number that is divisible by ALL numbers from 1 to 10, not just a few:

```<code>public class prob_5 {
public static void main(String args[]) {

    int count = 0;

    for (int x = 1; x <= 3000; x++) {
        for (int i = 1; i <= 10; i++) {

            if (x % i == 0) {

                System.out.println(x);
            }

        }
    }

}
</code>```

}

答:
```<code>package com.test.inter;

/**
 * Class to find the lowest number divisible by 1,2,3...20 * @author Faiz Ahamad
 */
public class TestLowestDivisibleFaiz {

    public static void main(String[] args) {

        int n;
        boolean isDivisible = true;

        for (n = 20; n < 300000000; n++) {

            for (int i = 1; i <= 20; i++) {
                if (n % i != 0) {
                    isDivisible = false;
                    break;
                } else {
                    isDivisible = true;
                }
            }
            // If the number is divisible by all break out of the outer loop to
            // get the exact number
            if (isDivisible)
                break;
        }

        // Print if the number is divisible by all
        if (isDivisible) {
            System.out.println(n);
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to find a number that is divisible by all numbers between 1 and 10. My code sample prints out all the numbers that are divisible.  However how would I go about approaching the problem to get just the number that is divisible by ALL numbers from 1 to 10, not just a few:

public class prob_5 {
public static void main(String args[]) {

    int count = 0;

    for (int x = 1; x <= 3000; x++) {
        for (int i = 1; i <= 10; i++) {

            if (x % i == 0) {

                System.out.println(x);
            }

        }
    }

}

}


问:
Skype for business URI instead of Skype
As we have the option of opening links in skype by just providing the URI:

```<code>skype:xyz?call
</code>```

Can we do something similar to achieve the same functionality but it opens in Skype for Business? Kindly let me know.

Cheers.

答:
you can start a call or IM with Skype for Business, but you need to use the full URI, like

im:sip:ID@company.com

if you just use the ID it will tell you that the contact does not exists, so this will not work:

im:sip:ID

Best Regards from Argentina, Marianok

Title: Skype for business URI instead of Skype

Body:
As we have the option of opening links in skype by just providing the URI:

skype:xyz?call

Can we do something similar to achieve the same functionality but it opens in Skype for Business? Kindly let me know.

Cheers.


问:
Converting to JSTL (Specificlly on calling methods)
I'm in the process of going the full JSTL way, and I've got an issue with the following scriplet, I have already transformed the variable displaying and conditions to the expression language (EL) but I'm not so sure of how to do it with method calling : here's my JSP code its positioned before the html markup:

            UserDTO user = (UserDTO) session.getAttribute("user");

```<code>        OrderDAO lnkOrder = new OrderDAO();
        OrderDTO order = new OrderDTO();

        CoverDAO lnkCover = new CoverDAO();
        CoverDTO cover = new CoverDTO();

        UpgradesDAO lnkUpgrades = new UpgradesDAO();
        UpgradesDTO upgrades = new UpgradesDTO();

        OrderAccessorieDAO lnkOrderAcc = new OrderAccessorieDAO();
        List<OrderAccessorieDTO> orderAccessories = new ArrayList<OrderAccessorieDTO>();

        GroupColorsDAO lnkColors = new GroupColorsDAO();
        List<ColorDTO> ColorList = new ArrayList<ColorDTO>();
        ColorList = lnkColors.getGroupColors(user.getGroup());

        AccessoryDAO lnkAcc = new AccessoryDAO();
        List<AccessoryDTO> groupAccessories = new ArrayList<AccessoryDTO>();
        groupAccessories = lnkAcc.getGroupAccessories(user.getGroup());

        ChangesDAO lnkChanges = new ChangesDAO();
        List<ChangeDTO> orderChanges = new ArrayList<ChangeDTO>();

        String CurrentOrder = request.getParameter("CurrentOrder");

        if (lnkOrder.exists(CurrentOrder)) {
            order = lnkOrder.find(CurrentOrder);
            cover = lnkCover.find(order.getReferenceNumber());
            upgrades = lnkUpgrades.find(order.getReferenceNumber());
            orderAccessories = lnkOrderAcc.getOrderAccessories(order.getReferenceNumber());
            orderChanges = lnkChanges.getOrderChanges(order.getReferenceNumber());
        }
</code>```

As yo can see it's pretty much DAO and DTO objects, I know that it can be done using static methods and making custom taglibs but that would mean writing a code for each method call, any other approach?, suggestions accepted. A brief description of the VIEW(HTML markup) it displays the details of a given order, the order name is extracted from a get request.

Also I have another small question, suppose I port everything to JSTL, would I have to import the corresponding myDTO and myDAO packages to access its getters and setters for each DTO?

Regards Tristian.

答:
"JSTL way" doesn't make sense without full separation between view and logic, as in Model 2 approach.

In Model 2 approach you move this code to the servlet that acts as a controller for your JSTL page, and only use JSP for view markup. Otherwise using JSTL to enforce separation between logic and view with JSTL would be meaningless.

ContentLicense: CC BY-SA 2.5

Body:
I'm in the process of going the full JSTL way, and I've got an issue with the following scriplet, I have already transformed the variable displaying and conditions to the expression language (EL) but I'm not so sure of how to do it with method calling : here's my JSP code its positioned before the html markup:

            UserDTO user = (UserDTO) session.getAttribute("user");

        OrderDAO lnkOrder = new OrderDAO();
        OrderDTO order = new OrderDTO();

        CoverDAO lnkCover = new CoverDAO();
        CoverDTO cover = new CoverDTO();

        UpgradesDAO lnkUpgrades = new UpgradesDAO();
        UpgradesDTO upgrades = new UpgradesDTO();

        OrderAccessorieDAO lnkOrderAcc = new OrderAccessorieDAO();
        List<OrderAccessorieDTO> orderAccessories = new ArrayList<OrderAccessorieDTO>();

        GroupColorsDAO lnkColors = new GroupColorsDAO();
        List<ColorDTO> ColorList = new ArrayList<ColorDTO>();
        ColorList = lnkColors.getGroupColors(user.getGroup());

        AccessoryDAO lnkAcc = new AccessoryDAO();
        List<AccessoryDTO> groupAccessories = new ArrayList<AccessoryDTO>();
        groupAccessories = lnkAcc.getGroupAccessories(user.getGroup());

        ChangesDAO lnkChanges = new ChangesDAO();
        List<ChangeDTO> orderChanges = new ArrayList<ChangeDTO>();

        String CurrentOrder = request.getParameter("CurrentOrder");

        if (lnkOrder.exists(CurrentOrder)) {
            order = lnkOrder.find(CurrentOrder);
            cover = lnkCover.find(order.getReferenceNumber());
            upgrades = lnkUpgrades.find(order.getReferenceNumber());
            orderAccessories = lnkOrderAcc.getOrderAccessories(order.getReferenceNumber());
            orderChanges = lnkChanges.getOrderChanges(order.getReferenceNumber());
        }

As yo can see it's pretty much DAO and DTO objects, I know that it can be done using static methods and making custom taglibs but that would mean writing a code for each method call, any other approach?, suggestions accepted. A brief description of the VIEW(HTML markup) it displays the details of a given order, the order name is extracted from a get request.

Also I have another small question, suppose I port everything to JSTL, would I have to import the corresponding myDTO and myDAO packages to access its getters and setters for each DTO?

Regards Tristian.


问:
jQuery Alert if paragraph is selected and has specific class
I have html code like below.

```<code><div id='p1' class='thread'>
<p>First Paragraph</p>
<p>Abbot and Costello - Africa Screams</p>
</div>

<div id='p2' class='thread selected'>
<p>Second Paragraph</p>
<p class='flag'>Abbot and Costello - Frank/Meet</p>
</div>

<div id='p3' class='thread'>
<p>Third Paragraph</p>
<p>addin</p>
</div>

<div id='p4' class='thread'>
<p>Forth Paragraph</p>
<p>Begins</p>
</div>
</code>```

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.

答:
Codepen: https://codepen.io/anon/pen/GEGLqX</p>

```<code>$('div').on('click', function() {
  if($(this).find('p').hasClass('flag')) {
    alert('flag');
  }
});
</code>```

Body:
I have html code like below.

First Paragraph

Abbot and Costello - Africa Screams

Second Paragraph

Abbot and Costello - Frank/Meet

Third Paragraph

addin

Forth Paragraph

Begins

Every time user clicks on paragraph new class "selected" is added and previous one is removed.

I want to alert('flag'); if a
 has class selected and
 has class flag like in Second Paragraph.

how can I achieve this using "jQuery".

any help is appreciated, Thanks.

Body:
Codepen: https://codepen.io/anon/pen/GEGLqX

$('div').on('click', function() {
  if($(this).find('p').hasClass('flag')) {
    alert('flag');
  }
});


问:
When a pod can't be scheduled, what does the 3 in "Insufficient cpu (3)" refer to?
When I create a Pod that cannot be scheduled because there are no nodes with sufficient CPU to meet the Pod's CPU request, the events output from kubectl describe pod/... contain a message like No nodes are available that match all of the following predicates:: Insufficient cpu (3).

What does the (3) in Insufficient cpu (3) mean?

For example, if I try to create a pod that requests 24 CPU when all of my nodes only have 4 CPUs:

```<code>$ kubectl describe pod/large-cpu-request
Name:           large-cpu-request
Namespace:      default
Node:           /
Labels:         <none>
Annotations:    <none>
Status:         Pending
IP:
Controllers:    <none>
Containers:
  cpuhog:
    ...
    Requests:
      cpu:              24
...
Events:
  FirstSeen     LastSeen        Count   From                    SubObjectPath   Type            Reason                  Message
  ---------     --------        -----   ----                    -------------   --------        ------                  -------
  23m           30s             84      default-scheduler                       Warning         FailedScheduling        No nodes are available that match all of the following predicates:: Insufficient cpu (3).
</code>```

At other times I have seen event messages like No nodes are available that match all of the following predicates:: Insufficient cpu (2), PodToleratesNodeTaints (1) when a pod's resource requests were too high, so the 3 does not seem like a constant number - nor does it seem related to my 24 CPU request either.

答:
A pod can't be scheduled when it requests more CPU than you have in your cluster. For example, if you have 8 Kubernetes CPUs (see this page to calculate how many Kubernetes CPUs you have) in total and if your existing pods have already consumed that much CPU, then you can't schedule more pods unless some of your existing pods are killed by the time you request to schedule a new pod. Here is a simple equation that can be followed in Horizontal Pod Autoscaler (HPA):

RESOURCE REQUEST CPU * HPA MAX PODS <= Total Kubernetes CPU

You can always tune up these numbers. In my case, I adjusted my manifest file for the RESOURCE REQUEST CPU. So it can be 200m or 1000m (= 1 Kubernetes CPU).

Body:
When I create a Pod that cannot be scheduled because there are no nodes with sufficient CPU to meet the Pod's CPU request, the events output from kubectl describe pod/... contain a message like No nodes are available that match all of the following predicates:: Insufficient cpu (3).

What does the (3) in Insufficient cpu (3) mean?

For example, if I try to create a pod that requests 24 CPU when all of my nodes only have 4 CPUs:

$ kubectl describe pod/large-cpu-request
Name:           large-cpu-request
Namespace:      default
Node:           /
Labels:         <none>
Annotations:    <none>
Status:         Pending
IP:
Controllers:    <none>
Containers:
  cpuhog:
    ...
    Requests:
      cpu:              24
...
Events:
  FirstSeen     LastSeen        Count   From                    SubObjectPath   Type            Reason                  Message
  ---------     --------        -----   ----                    -------------   --------        ------                  -------
  23m           30s             84      default-scheduler                       Warning         FailedScheduling        No nodes are available that match all of the following predicates:: Insufficient cpu (3).

At other times I have seen event messages like No nodes are available that match all of the following predicates:: Insufficient cpu (2), PodToleratesNodeTaints (1) when a pod's resource requests were too high, so the 3 does not seem like a constant number - nor does it seem related to my 24 CPU request either.

ContentLicense: CC BY-SA 4.0


问:
Bootstrap Modal + Angularfire2

Hello everyone, im trying to put bootstrap modal working with angularfire2 but im having a error. It doesnt recognize the data that cames from the DB.

<button *ngFor="let utilfaq of (utilfaqsStream | async) | reverse" class="panel panel-default" type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large modal</button>

Tema
{{utilfaq.tema}}

Subtema
{{utilfaq.subtema}}

Erro
{{utilfaq.erro}}

Solução
{{utilfaq.solucao}}

```
</div>
</div>
</p>

<p>This is the HTML where i have the Bootstrap modal.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Subject } from 'rxjs/Subject';
import { moveIn, moveInLeft, fallIn } from '../router.animations';

interface utilfaq {

  erro: string;
  solucao: string;
  programa:string;
  tema:string;
  subtema:string;
  $key?: string;

}

@Component({
  selector: 'app-utilss',
  templateUrl: './utilsst.component.html',
  styleUrls: ['./utilsst.component.css'],
})
export class UtilsstComponent {

  readonly errosPath = "erros";

  formutilfaq: utilfaq = {

    'erro' : '',
    'solucao' : '',
    'programa' : '',
    'tema' : ',',
    'subtema' : ',',

  };

  utilfaqsStream: FirebaseListObservable <utilfaq[]>;
  constructor(db:AngularFireDatabase){
    this.utilfaqsStream = db.list('/erros/', {
      query: {
        orderByChild: 'programa',
        equalTo: 'UtilSST'
      }
    });

  }

}</code>```

And this is .ts file where i have the db config.

The error im getting is

```<code>ERROR TypeError: Cannot read property 'tema' of undefined
    at Object.eval [as updateRenderer] (UtilsstComponent.html:22)
    at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13146)
    at checkAndUpdateView (core.es5.js:12293)
    at callViewAction (core.es5.js:12653)
    at execComponentViewsAction (core.es5.js:12585)
    at checkAndUpdateView (core.es5.js:12294)
    at callViewAction (core.es5.js:12653)
    at execEmbeddedViewsAction (core.es5.js:12611)
    at checkAndUpdateView (core.es5.js:12289)
    at callViewAction (core.es5.js:12653)
View_UtilsstComponent_0 @ UtilsstComponent.html:22
UtilsstComponent.html:22 ERROR CONTEXT DebugContext_
View_UtilsstComponent_0 @ UtilsstComponent.html:22
</code>```

I have no idea why is this happening, if i have the data outside the modal it works.... can someone solve this problem ?

答:
Ah! Of course!

You are looping utilfaqsStream inside the <button> tag, therefore, the variable utilfaq is only defined within that tag.

You should loop also the divs (modals) and reference each one of them.

Try something like this:

```<code>// I removed all the stuff inside the button just for the example, don't remove yours
<button *ngFor="let utilfaq of (utilfaqsStream | async) | reverse" data-toggle="modal" data-target="#{{utilfaq.tema}}">Large modal</button>

<div *ngFor="let utilfaq of (utilfaqsStream | async) | reverse" id="{{utilfaq.tema}}" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
    // all the stuff inside
</div>
</code>```

What we want to do in the button is refence the model of the same utilfaq. So, instead of referencing a class, we reference an id, hence data-target="#{{utilfaq.tema}}".

And, in the modals, we will build the id dynamically, hence: id="{{utilfaq.tema}}".

If your utilfaq object had an id property would be perfect, you could build a nicer modal id, example: id="modal_{{utilfaq.id}}" and data-target="#modal_{{utilfaq.id}}".

Title: Bootstrap Modal + Angularfire2

Body:
Hello everyone, im trying to put bootstrap modal working with angularfire2 but im having a error. It doesnt recognize the data that cames from the DB.

<button *ngFor="let utilfaq of (utilfaqsStream | async) | reverse" class="panel panel-default" type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large modal</button>

Tema
{{utilfaq.tema}}

Subtema
{{utilfaq.subtema}}

Erro
{{utilfaq.erro}}

Solução
{{utilfaq.solucao}}

This is the HTML where i have the Bootstrap modal.

import { Component } from '@angular/core';
import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database';
import { Subject } from 'rxjs/Subject';
import { moveIn, moveInLeft, fallIn } from '../router.animations';

interface utilfaq {

  erro: string;
  solucao: string;
  programa:string;
  tema:string;
  subtema:string;
  $key?: string;

}

@Component({
  selector: 'app-utilss',
  templateUrl: './utilsst.component.html',
  styleUrls: ['./utilsst.component.css'],
})
export class UtilsstComponent {

  readonly errosPath = "erros";

  formutilfaq: utilfaq = {

    'erro' : '',
    'solucao' : '',
    'programa' : '',
    'tema' : ',',
    'subtema' : ',',

  };

  utilfaqsStream: FirebaseListObservable <utilfaq[]>;
  constructor(db:AngularFireDatabase){
    this.utilfaqsStream = db.list('/erros/', {
      query: {
        orderByChild: 'programa',
        equalTo: 'UtilSST'
      }
    });

  }

}

And this is .ts file where i have the db config.

The error im getting is

ERROR TypeError: Cannot read property 'tema' of undefined
    at Object.eval [as updateRenderer] (UtilsstComponent.html:22)
    at Object.debugUpdateRenderer [as updateRenderer] (core.es5.js:13146)
    at checkAndUpdateView (core.es5.js:12293)
    at callViewAction (core.es5.js:12653)
    at execComponentViewsAction (core.es5.js:12585)
    at checkAndUpdateView (core.es5.js:12294)
    at callViewAction (core.es5.js:12653)
    at execEmbeddedViewsAction (core.es5.js:12611)
    at checkAndUpdateView (core.es5.js:12289)
    at callViewAction (core.es5.js:12653)
View_UtilsstComponent_0 @ UtilsstComponent.html:22
UtilsstComponent.html:22 ERROR CONTEXT DebugContext_
View_UtilsstComponent_0 @ UtilsstComponent.html:22

I have no idea why is this happening, if i have the data outside the modal it works.... can someone solve this problem ?

Body:
Ah! Of course!

You are looping utilfaqsStream inside the <button> tag, therefore, the variable utilfaq is only defined within that tag.

You should loop also the divs (modals) and reference each one of them.

Try something like this:

// I removed all the stuff inside the button just for the example, don't remove yours
<button *ngFor="let utilfaq of (utilfaqsStream | async) | reverse" data-toggle="modal" data-target="#{{utilfaq.tema}}">Large modal</button>

<div *ngFor="let utilfaq of (utilfaqsStream | async) | reverse" id="{{utilfaq.tema}}" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
    // all the stuff inside
</div>

What we want to do in the button is refence the model of the same utilfaq. So, instead of referencing a class, we reference an id, hence data-target="#{{utilfaq.tema}}".

And, in the modals, we will build the id dynamically, hence: id="{{utilfaq.tema}}".

If your utilfaq object had an id property would be perfect, you could build a nicer modal id, example: id="modal_{{utilfaq.id}}" and data-target="#modal_{{utilfaq.id}}".


问:
Mobx Inject, Observer and HoC together
Here a code that i have https://jsfiddle.net/v0592ua1/1/

```<code>const {observable, computed, extendObservable} = mobx;
const {observer,  inject, Provider} = mobxReact;
const {Component} = React;
const {render} = ReactDOM
class AppState {
    @observable authenticated = false;
    @observable authenticating = false;
}

class Store2 {
    @observable blah = false;
}

function Protected(Component) {
    @inject("appState")
    @observer
    class AuthenticatedComponent extends Component {
        render() {
            const { authenticated, authenticating } = this.props.appState;
            return (
                <div className="authComponent">
                    {authenticated
                        ? <Component {...this.props} />
                        : !authenticating && !authenticated
                                ? <p> redirect</p>
                                : null}
                </div>
            );
        }
    }
    return AuthenticatedComponent;
}

@inject("s2")
@Protected
@observer
class Comp extends Component {
  componentDidMount() {
        console.log('mount');
  }

    render() {
        return (
            <p>blabla</p>
        )
    }
}

const appS = new AppState();
const s2 = new Store2();

render(
    <Provider appState={appS} s2={s2}>
        <Comp  />
    </Provider>,
    document.getElementById("app")
)
</code>```

Protected HoC is for checking if user is authorized or not.

The problem is that if @inject is outer of Protected - componentDidMount will trigger (once if not auth, and twice if authenticated). And if i put Protected as outside decorator it seems to work as expected  but produce a warning

You are trying to use 'observer' on a component that already has 'inject'.

What is a proper way to handle this?

答:
In function Protected i was redefining React.Component by function argument Component, then i was extending argument, not React.Component.
Solution -> rename argument Component-> Children </p>

```<code>function Protected(Children) {
    @inject("appState")
    @observer
    class AuthenticatedComponent extends Component {
        render() {
            const { authenticated, authenticating } = this.props.appState;
            return (
                <div className="authComponent">
                    {authenticated
                        ? <Children {...this.props} />
                        : !authenticating && !authenticated
                                ? <p> redirect</p>
                                : null}
                </div>
            );
        }
    }
    return AuthenticatedComponent;
}
</code>```

Title: Mobx Inject, Observer and HoC together

Body:
Here a code that i have https://jsfiddle.net/v0592ua1/1/

const {observable, computed, extendObservable} = mobx;
const {observer,  inject, Provider} = mobxReact;
const {Component} = React;
const {render} = ReactDOM
class AppState {
    @observable authenticated = false;
    @observable authenticating = false;
}

class Store2 {
    @observable blah = false;
}

function Protected(Component) {
    @inject("appState")
    @observer
    class AuthenticatedComponent extends Component {
        render() {
            const { authenticated, authenticating } = this.props.appState;
            return (

                    {authenticated
                        ? <Component {...this.props} />
                        : !authenticating && !authenticated
                                ?
 redirect

                                : null}

            );
        }
    }
    return AuthenticatedComponent;
}

@inject("s2")
@Protected
@observer
class Comp extends Component {
  componentDidMount() {
        console.log('mount');
  }

    render() {
        return (

blabla

        )
    }
}

const appS = new AppState();
const s2 = new Store2();

render(
    <Provider appState={appS} s2={s2}>
        <Comp  />
    </Provider>,
    document.getElementById("app")
)

Protected HoC is for checking if user is authorized or not.

The problem is that if @inject is outer of Protected - componentDidMount will trigger (once if not auth, and twice if authenticated). And if i put Protected as outside decorator it seems to work as expected  but produce a warning

You are trying to use 'observer' on a component that already has 'inject'.

What is a proper way to handle this?

Body:
In function Protected i was redefining React.Component by function argument Component, then i was extending argument, not React.Component.
Solution -> rename argument Component-> Children

function Protected(Children) {
    @inject("appState")
    @observer
    class AuthenticatedComponent extends Component {
        render() {
            const { authenticated, authenticating } = this.props.appState;
            return (
                <div className="authComponent">
                    {authenticated
                        ? <Children {...this.props} />
                        : !authenticating && !authenticated
                                ? <p> redirect</p>
                                : null}
                </div>
            );
        }
    }
    return AuthenticatedComponent;
}


问:
What is the point of Auto-Implemented Properties?
An example of Auto-implemented properties in C# is for example:

```<code> public double TotalPurchases { get; set; }
</code>```

I understand what they are, and as they say the "compiler creates a private field that can only be accessed through get and set.

My question is what is the point of this?

I mean in other languages, the point was: You have a variable that you make private and then you declare some functions public through which you can access that variable- NEVER directly. Why? Well because then you can implement that "variable" the way you want it and the user of your class is oblivious to that, he just gets and sets what he sees is a property of the class.

But here, although you have a private variable that can be accessed only through get and set (same as above) you also have a very public variable that actually you access directly, defeating the purpose of get and set in the first place.

I mean if you are going to do

```<code>cust1.TotalPurchases += 499.99;
</code>```

why not just have

```<code>public double TotalPurchases;
</code>```

and be done with it??

EDIT:
This question has been marked as a "possible duplicate" which in my opinion is not, and i will try to explain -in my rather limited english- why it is not.

The author of the "possible duplicate" originally wrote a way that broke totally encapsulation. Later he confessed that he "couldn't bear writing all that " so he just used public fields. After all he didn't care about encapsulation in the first place.

My post is the total opposite. I want to keep encapsulation, since as I previously explained this gives me the liberty to implement TotalPurchases as I see fit. I may use a variable, but I might get that from a DB, or calculate it through a Neural network. The thing is I don't want the user to be oblivious to this.

But, if I have to use get and set as explained I am forced to declare a public variable right?
or if I do this

```<code>private double TotalPurchases {get; set;}
</code>```

are these get and set public? I suspect they are not.

So my question is what is the point of breaking encapsulation?

答:
Changing from a field to a property is a breaking change for libraries because the CIL to access a field is different from the CIL to access a property. If you want the benefits of properties when you write a library (which is that you can replace the auto-synthesized getter/setter with one that does something else) without needing to rebuild the world, you need to plan for it and use the { get; set; } syntax.

As people have already outlined in the comments, there are also some differences in reflection, but they usually aren't things that you want to do in and of themselves.

Body:
An example of Auto-implemented properties in C# is for example:

 public double TotalPurchases { get; set; }

I understand what they are, and as they say the "compiler creates a private field that can only be accessed through get and set.

My question is what is the point of this?

I mean in other languages, the point was: You have a variable that you make private and then you declare some functions public through which you can access that variable- NEVER directly. Why? Well because then you can implement that "variable" the way you want it and the user of your class is oblivious to that, he just gets and sets what he sees is a property of the class.

But here, although you have a private variable that can be accessed only through get and set (same as above) you also have a very public variable that actually you access directly, defeating the purpose of get and set in the first place.

I mean if you are going to do

cust1.TotalPurchases += 499.99;

why not just have

public double TotalPurchases;

and be done with it??

EDIT:
This question has been marked as a "possible duplicate" which in my opinion is not, and i will try to explain -in my rather limited english- why it is not.

The author of the "possible duplicate" originally wrote a way that broke totally encapsulation. Later he confessed that he "couldn't bear writing all that " so he just used public fields. After all he didn't care about encapsulation in the first place.

My post is the total opposite. I want to keep encapsulation, since as I previously explained this gives me the liberty to implement TotalPurchases as I see fit. I may use a variable, but I might get that from a DB, or calculate it through a Neural network. The thing is I don't want the user to be oblivious to this.

But, if I have to use get and set as explained I am forced to declare a public variable right?
or if I do this

private double TotalPurchases {get; set;}

are these get and set public? I suspect they are not.

So my question is what is the point of breaking encapsulation?


问:
UIimagepicker controller image only selection
I have to give functionality to select photos by the user. I have used this:

```<code>ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
</code>```

Now I have to restrict user to select only photos and i want videos to be not displayed on the list. Or somehow user should not select video at all. How to achieve that?

答: UIImagePickerController defaults to only image. Just avoid specifying media types the it will display only images to select.</p>

Body:
I have to give functionality to select photos by the user. I have used this:

ipc.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;

Now I have to restrict user to select only photos and i want videos to be not displayed on the list. Or somehow user should not select video at all. How to achieve that?


问:
Configure NGINX to work with angular issue on reloading page
Well I have read the deployment documentation to deploy an Angular 4 proyect with an NGINX server.But when I reload with a route for the angular app shows me this error:

http://www.mydomain.com.ec/swissecomer/myRoute

code: "MethodNotAllowedError"

message: "GET is not allowed"

Here is my conf file in my nginx server:

```<code>    upstream proyectoWeb {
        ip_hash;
        server localhost:8087;

    }

    server {

        listen 8088;
        proxy_pass proyectoWeb;
        server_name 200.31.25.34 192.168.5.27  www.mydomain.com localhost;
        root /u01/servidores/;

        location swissecomer/ {
            index index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        access_log /var/log/nginx/access_log combined;

    }
</code>```

When i hit these urls, it shows the webpage just fine:

http://www.mydomain.com.ec/swissecomer/index.html

http://www.mydomain.com.ec/swissecomer/

But if i hit the next url http://www.mydomain.com.ec/swissecomer the ngix server keeps loading until it shows a timeout error in the browser.

Thanks for your responses.

答:
I found the answer, the block location needs a little change like this:</p>

```<code>location swissecomer/ {
  index index.html index.htm;
  try_files $uri $uri/ /swissecomer/index.html;
}
</code>```

Body:
Well I have read the deployment documentation to deploy an Angular 4 proyect with an NGINX server.But when I reload with a route for the angular app shows me this error:

http://www.mydomain.com.ec/swissecomer/myRoute

code: "MethodNotAllowedError"

message: "GET is not allowed"

Here is my conf file in my nginx server:

    upstream proyectoWeb {
        ip_hash;
        server localhost:8087;

    }

    server {

        listen 8088;
        proxy_pass proyectoWeb;
        server_name 200.31.25.34 192.168.5.27  www.mydomain.com localhost;
        root /u01/servidores/;

        location swissecomer/ {
            index index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        access_log /var/log/nginx/access_log combined;

    }

When i hit these urls, it shows the webpage just fine:

http://www.mydomain.com.ec/swissecomer/index.html

http://www.mydomain.com.ec/swissecomer/

But if i hit the next url http://www.mydomain.com.ec/swissecomer the ngix server keeps loading until it shows a timeout error in the browser.

Thanks for your responses.

Body:
I found the answer, the block location needs a little change like this:

location swissecomer/ {
  index index.html index.htm;
  try_files $uri $uri/ /swissecomer/index.html;
}


问:
Is there a C compiler that targets the 8086?
I have an 8086 CPU emulator. It emulates only 8086 instructions. I am searching now for a C compiler to target this emulator with. Is there any C compiler out there that can do this?

Also, having a usable libc and such is not important to me. The emulator uses custom(ie, non-PC) hardware and therefor any libc or even ctr0 would probably have to be rewritten anyway

答:
bcc - Bruce's C compiler

From bcc(1) - Linux man page:

Description

Bcc is a simple C compiler that produces 8086 assembler, in addition compiler compile time options allow 80386 or 6809 versions. The compiler understands traditional K&R C with just the restriction that bit fields are mapped to one of the other integer types.

The default operation is to produce an 8086 executable called a.out from the source file.

Open Watcom

From the description of compiler option / 80x86 run-time convention 0 in Open Watcom C/C++ User’s Guide (PDF link):

(16-bit only) The compiler will make use of only 8086 instructions in the generated object code.  This is the
  default.  The resulting code will run on 8086 and all upward compatible processors.  The macro __SW_0
  will be predefined if "0" is selected


问:
How to create a HTML button that when clicked, clicks on multiple HTML social media buttons?
So I have a bunch of HTML buttons that I got from various social media platforms. I want to create a button that clicks on all the social media follows so the user could follow on all platforms without doing much work. Any ideas on how I can do this/what to look into? Thanks so much for your time!

Heres what I got so far:

```<code><html>

<body>
<div id="fb-root"></div>
<script>(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.9";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="https://www.facebook.com/facebook/" data-layout="button" data-action="like" data-size="small" data-show-faces="false" data-share="false"></div>

<a href="https://twitter.com/twitter" class="twitter-follow-button" data-show-count="false">Follow</a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>

<script src="https://apis.google.com/js/platform.js"></script>
<div class="g-ytsubscribe" data-channel="youtube" data-layout="default" data-count="hidden"></div>

<iframe src="https://open.spotify.com/follow/1/?uri=spotify:artist:4O15NlyKLIASxsJ0PrXPfz&size=basic&theme=light&show-count=0" width="200" height="24" scrolling="no" frameborder="0" style="border:none; overflow:hidden;" allowtransparency="true"></iframe>

<button type="button" onclick="alert('placeholder')">Follow All Socials</button>

</body>

</html>
</code>```

答:
Here is an example with jQuery;

$('button').click(function() {
  console.log($(this).text());
});
$('.trigger').click(function() {
  $('.click').click();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="trigger">Trigger clicks on the other buttons</button>
<br>
<br>
<button class="click">Button 1</button>
<br>
<button class="click">Button 2</button>
<br>
<button class="click">Button 3</button>
<br>
<button class="click">Button 4</button></code>```

Here is an example without jQuery:

function myFunction(x) {
  console.log(x.textContent);
}
function triggerFunction() {
  var click = document.getElementsByClassName('click');
  for (i=0;i<click.length;i++) {
    click[i].click();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="trigger" onclick="myFunction(this); triggerFunction()">Trigger clicks on the other buttons</button>
<br>
<br>
<button class="click" onclick="myFunction(this)">Button 1</button>
<br>
<button class="click" onclick="myFunction(this)">Button 2</button>
<br>
<button class="click" onclick="myFunction(this)">Button 3</button>
<br>
<button class="click" onclick="myFunction(this)">Button 4</button></code>```

Body:
So I have a bunch of HTML buttons that I got from various social media platforms. I want to create a button that clicks on all the social media follows so the user could follow on all platforms without doing much work. Any ideas on how I can do this/what to look into? Thanks so much for your time!

Heres what I got so far:

Follow

<button type="button" onclick="alert('placeholder')">Follow All Socials</button>

Body:
Here is an example with jQuery;

$('button').click(function() {
  console.log($(this).text());
});
$('.trigger').click(function() {
  $('.click').click();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="trigger">Trigger clicks on the other buttons</button>
<br>
<br>
<button class="click">Button 1</button>
<br>
<button class="click">Button 2</button>
<br>
<button class="click">Button 3</button>
<br>
<button class="click">Button 4</button>

Here is an example without jQuery:

function myFunction(x) {
  console.log(x.textContent);
}
function triggerFunction() {
  var click = document.getElementsByClassName('click');
  for (i=0;i<click.length;i++) {
    click[i].click();
  }
}

<button class="trigger" onclick="myFunction(this); triggerFunction()">Trigger clicks on the other buttons</button>
<br>
<br>
<button class="click" onclick="myFunction(this)">Button 1</button>
<br>
<button class="click" onclick="myFunction(this)">Button 2</button>
<br>
<button class="click" onclick="myFunction(this)">Button 3</button>
<br>
<button class="click" onclick="myFunction(this)">Button 4</button>


问:
How to generate a random string in rails
In my form i want to generate random strings for the following fields

```<code>  f.input :lti_api_key, label: "LTI API KEY"
    f.input :lti_api_secret, label: "LTI API SECRET"
</code>```

how can i do that?
Please help me...

答:
You can have your f.input as such</p>

```<code><%= f.text_field :name, id: :bug_name, value: "#{SecureRandom.hex(64)}" %>
</code>```

Body:
In my form i want to generate random strings for the following fields

  f.input :lti_api_key, label: "LTI API KEY"
    f.input :lti_api_secret, label: "LTI API SECRET"

how can i do that?
Please help me...

Body:
You can have your f.input as such

<%= f.text_field :name, id: :bug_name, value: "#{SecureRandom.hex(64)}" %>


问:
Generate uncorrelated variables each well correlated with existing response variable
I want to generate two uncorrelated random variables (x1,x2) that show  specified Pearson correlations with an existing variable y, e.g:

cor(x1,y)=0,4;

cor(x2,y)=0,3;

cor(x1,x2)=0,03.

So, I have continuous values, normally distributed, for y (using spatial interpolation technique) and now i want to generate simulated continuous values (e.g. Normal distribution) for two explanatory variables x1 and x2 using the correlation coefficients pointed above.
I tried mvrnorm (MASS) and copula R packages, but i did not find the way to do what i want.

If one can help me getting there i will appreciate a lot. Kind regards.

答:
The mvrnorm function in the MASS package should be able to do this (the copula package as well, I am just less familiar with it).

What did you try and how did the results differ from what you expected?

Here is a quick mvrnorm example:

```<code>> ?MASS::mvrnorm
> library(MASS)
>
> r <- cbind( c(1, 0.4, 0.3),
+             c(0.4, 1, 0.03),
+             c(0.3, 0.03, 1))
>
> xy <- mvrnorm(n=100, mu=c(0,0,0), Sigma=r, empirical=TRUE )
> colnames(xy) <- c('y','x1','x2')
>
> cor(xy)
     y   x1   x2
y  1.0 0.40 0.30
x1 0.4 1.00 0.03
x2 0.3 0.03 1.00
>
</code>```

Edit

Here is one way with an existing y variable:

```<code>y <- rnorm(100)  # existing y

# generate x1 and x2, make sure y is first column
xy <- cbind( y, x1=rnorm(100), x2=rnorm(100))

# center and scale
mns <- apply(xy, 2, mean)
sds <- apply(xy, 2, sd)

xy2 <- sweep(xy, 2, mns, FUN="-")
xy2 <- sweep(xy2, 2, sds, FUN="/")

# find existing correlations
v.obs <- cor(xy2)

# remove correlation
xy3 <- xy2 %*% solve(chol(v.obs))

# check
zapsmall(cor(xy3))

# new correlation

r <- cbind( c(1, 0.4, 0.3),
            c(0.4, 1, 0.03),
            c(0.3, 0.03, 1))

xy4 <- xy3 %*% chol(r)

# undo center and scale

xy4 <- sweep(xy4, 2, sds, FUN="*")
xy4 <- sweep(xy4, 2, mns, FUN="+")

#check
cor(xy4)
all.equal(y, xy[,1])
</code>```

The mvrnorm function uses svd and Eigen values instead of chol.  You could also follow that code using your own y instead of random values for that part of the matrix.

Body:
The mvrnorm function in the MASS package should be able to do this (the copula package as well, I am just less familiar with it).

What did you try and how did the results differ from what you expected?

Here is a quick mvrnorm example:

> ?MASS::mvrnorm
> library(MASS)
>
> r <- cbind( c(1, 0.4, 0.3),
+             c(0.4, 1, 0.03),
+             c(0.3, 0.03, 1))
>
> xy <- mvrnorm(n=100, mu=c(0,0,0), Sigma=r, empirical=TRUE )
> colnames(xy) <- c('y','x1','x2')
>
> cor(xy)
     y   x1   x2
y  1.0 0.40 0.30
x1 0.4 1.00 0.03
x2 0.3 0.03 1.00
>

Edit

Here is one way with an existing y variable:

y <- rnorm(100)  # existing y

# generate x1 and x2, make sure y is first column
xy <- cbind( y, x1=rnorm(100), x2=rnorm(100))

# center and scale
mns <- apply(xy, 2, mean)
sds <- apply(xy, 2, sd)

xy2 <- sweep(xy, 2, mns, FUN="-")
xy2 <- sweep(xy2, 2, sds, FUN="/")

# find existing correlations
v.obs <- cor(xy2)

# remove correlation
xy3 <- xy2 %*% solve(chol(v.obs))

# check
zapsmall(cor(xy3))

# new correlation

r <- cbind( c(1, 0.4, 0.3),
            c(0.4, 1, 0.03),
            c(0.3, 0.03, 1))

xy4 <- xy3 %*% chol(r)

# undo center and scale

xy4 <- sweep(xy4, 2, sds, FUN="*")
xy4 <- sweep(xy4, 2, mns, FUN="+")

#check
cor(xy4)
all.equal(y, xy[,1])

The mvrnorm function uses svd and Eigen values instead of chol.  You could also follow that code using your own y instead of random values for that part of the matrix.


问:
jQuery getJSON Output using Python/Django
So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests.  The address being used is:

```<code>http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296
</code>```

I'm trying to write a simple web view that can access this url and return a JSON packet as the result (worried about actual element values/layout later).

Here's my simple attempt at just alerting/returning the data:

```<code>$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?",
function(json){
    alert(json);
    <!--$.each(json.items, function(i,item){
    });-->
});
</code>```

I am able to access this URL directly, either at http://localhost:8000/api/0.1/tonight-mobile.json or http://localhost:8000/api/0.1/tonight-mobile.json&callback=jsonp1290277462296 and get back a valid JSON packet... So I'm assuming it's in my noob javascript:)

My views.py function that is generating this response looks as follows:

```<code>def tonight_mobile(request):
    callback = request.GET.get('callback=?', '')

    def with_rank(rank, place):
        return (rank > 0)

    place_data = dict(
        Places = [make_mobile_place_dict(request, p) for p in Place.objects.all()]
    )

    xml_bytes = json.dumps(place_data)
    xml_bytes = callback + '(' + xml_bytes + ');'

    return HttpResponse(xml_bytes, mimetype="application/json")
</code>```

With corresponding urls.py configuration:

```<code>(r'^tonight-mobile.json','iphone_api.views.tonight_mobile'),
</code>```

I am still somewhat confused on how to use callbacks, so maybe that is where my issue lies.  Note I am able to call directly a 'blah.json' file that is giving me a response, but not through a wired URL.  Could someone assist me with some direction?

答:
First, callback = request.GET.get('callback=?', '') won't get you the value of callback.

```<code>callback = request.GET.get( 'callback', None )
</code>```

Works much better.

To debug this kind of thing.  You might want to include print statements in your Django view function so you can see what's going on.  For example: print repr(request.GET) is a helpful thing to put in a view function so that you can see the GET dictionary.

Body:
So, I'm trying to make a simple call using jQuery .getJSON to my local web server using python/django to serve up its requests.  The address being used is:

http://localhost:8000/api/0.1/tonight-mobile.json?callback=jsonp1290277462296

I'm trying to write a simple web view that can access this url and return a JSON packet as the result (worried about actual element values/layout later).

Here's my simple attempt at just alerting/returning the data:

$.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?",
function(json){
    alert(json);

});

I am able to access this URL directly, either at http://localhost:8000/api/0.1/tonight-mobile.json or http://localhost:8000/api/0.1/tonight-mobile.json&callback=jsonp1290277462296 and get back a valid JSON packet... So I'm assuming it's in my noob javascript:)

My views.py function that is generating this response looks as follows:

def tonight_mobile(request):
    callback = request.GET.get('callback=?', '')

    def with_rank(rank, place):
        return (rank > 0)

    place_data = dict(
        Places = [make_mobile_place_dict(request, p) for p in Place.objects.all()]
    )

    xml_bytes = json.dumps(place_data)
    xml_bytes = callback + '(' + xml_bytes + ');'

    return HttpResponse(xml_bytes, mimetype="application/json")

With corresponding urls.py configuration:

(r'^tonight-mobile.json','iphone_api.views.tonight_mobile'),

I am still somewhat confused on how to use callbacks, so maybe that is where my issue lies.  Note I am able to call directly a 'blah.json' file that is giving me a response, but not through a wired URL.  Could someone assist me with some direction?

Body:
First, callback = request.GET.get('callback=?', '') won't get you the value of callback.

callback = request.GET.get( 'callback', None )

Works much better.

To debug this kind of thing.  You might want to include print statements in your Django view function so you can see what's going on.  For example: print repr(request.GET) is a helpful thing to put in a view function so that you can see the GET dictionary.


问:
How to select a schema in postgres when using psql?
I have a postgres database with multiple schemas. When I connect to the database from a shell with psql and I run \dt it uses the default connection schema which is public. Is there a flag I can specify or how can I change the schema?

答:
This is old, but I put exports in my alias for connecting to the db:

```<code>alias schema_one.con="PGOPTIONS='--search_path=schema_one' psql -h host -U user -d database etc"
</code>```

And for another schema:

```<code>alias schema_two.con="PGOPTIONS='--search_path=schema_two' psql -h host -U user -d database etc"
</code>```

Body:
This is old, but I put exports in my alias for connecting to the db:

alias schema_one.con="PGOPTIONS='--search_path=schema_one' psql -h host -U user -d database etc"

And for another schema:

alias schema_two.con="PGOPTIONS='--search_path=schema_two' psql -h host -U user -d database etc"


问:
mysql workbench - Create a new schema and import tables and structures from existing schema
I have an existing mysql schema with 10 tables (SCHEMA1). I need to create another schema (SCHEMA2) using the structures of the existing (SCHEMA1). I don't need the data just the structure.

So how do I get the existing 10 tables in the new schema ((SCHEMA2) using mysql workbench?

答:
Inspect the individual table and look at its details. Then go to the tab with the label DDL and just copy those CREATE TABLE statements to your new database. This will just create the tables and structure and then you are free to populate your table as you wish.

The top with the tabs (depending on your version) should look like this:

You should click on the last part over and then look at the table declaration inside.


问:
MVC 5 routeconfig error
```<code>routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new
    {
        controller = "ImageScan",
        action = "ScanImage",
        id = UrlParameter.Optional
    },
    namespaces: new[] { "WebApplication3.Controllers" } );
</code>```

I get the error:

HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Views/ImageScan/ScanImage.cshtml

答:
You do not request a view directly. You should request a controller action which may or may not return the corresponding view.

Try

```<code>yourAppBaseAddress/ImageScan/ScanImage
</code>```

Assuming you do not have any other custom routing definied to override the default routing conventions, This will hit the ScanImage action method inside the ImageScanController. If this action method is returning this view, you should be able to see the result of this views' code executed.

```<code>public ActionResult ScanImage
{
   return View();
}
</code>```

When the line return View gets executed, the MVC framework will look for a view called ScanImage.cshtml in ~/Views/ImageScan and ~/Views/Shared directories.

Title: MVC 5 routeconfig error

Body:
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new
    {
        controller = "ImageScan",
        action = "ScanImage",
        id = UrlParameter.Optional
    },
    namespaces: new[] { "WebApplication3.Controllers" } );

I get the error:

HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Views/ImageScan/ScanImage.cshtml

Body:
You do not request a view directly. You should request a controller action which may or may not return the corresponding view.

Try

yourAppBaseAddress/ImageScan/ScanImage

Assuming you do not have any other custom routing definied to override the default routing conventions, This will hit the ScanImage action method inside the ImageScanController. If this action method is returning this view, you should be able to see the result of this views' code executed.

public ActionResult ScanImage
{
   return View();
}

When the line return View gets executed, the MVC framework will look for a view called ScanImage.cshtml in ~/Views/ImageScan and ~/Views/Shared directories.


问:
GUI Framework for new Windows OSs
Is there any swing like framework for the newer Windows OS's?  Vista and & 7 apps have a different menuing and taskbar thing going and was wondering if there is any GUI components to utilize this new application look for Java.</p>

答:
Java provides a standard look and feel across all platforms, so unfortunately no...

You can only use the standard Swing API, and the classes provided in that

Apple provides extensions to Java, allowing you to access certain other kinds of buttons, but I don't think Microsoft does the same.

Title: GUI Framework for new Windows OSs


问:
Android Marshmallow: Calling a method in the system process without a qualified user:
I have a android device on which am installing my app as a System app. this App has a service and trying to start that service as

```<code>static void startMyService(Context context, String action) {
    Intent service = new Intent(context, MyService.class);
    service.setAction(action);
    context.startService(service);
}
</code>```

Previously I used to run my code on Android 5.1.1 and it used to work fine but now I updated it to 6.0. And now I am getting following logs.

```<code>Line 209209: 01-02 01:30:51.215 I/ActivityManager( 3571): Start proc 5678:com.example.myapp/1000 for broadcast com.example.myapp/.update.GenericBroadcastReceiver
Line 209239: 01-02 01:30:51.377 W/art     ( 5678): <clinit> didn't have expected constructor access flag in class com.example.myapp.update.BootStrapperService in dex file /system/app/myApp.apk
Line 209241: 01-02 01:30:51.378 W/art     ( 5678): <clinit> didn't have expected constructor access flag in class com.example.myapp.update.MyService in dex file /system/app/MyApp.apk
Line 209255: 01-02 01:30:51.393 W/art     ( 5678): <clinit> didn't have expected constructor access flag in class com.example.myapp.update.UpdateState in dex file /system/app/MyApp.apk
Line 209259: 01-02 01:30:51.400 W/ContextImpl( 5678): Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1221 android.content.ContextWrapper.startService:581 android.content.ContextWrapper.startService:581 com.example.myapp.update.MyService.startServiceWithAction:301 com.example.myapp.update.GenericBroadcastReceiver.onReceive:52
Line 209259: 01-02 01:30:51.400 W/ContextImpl( 5678): Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1221 android.content.ContextWrapper.startService:581 android.content.ContextWrapper.startService:581 com.example.myapp.update.MyService.startMyService:301 com.example.myapp.update.GenericBroadcastReceiver.onReceive:52
Line 209263: 01-02 01:30:51.408 E/PersistenceUtil( 5678): unabled to read update configuration
</code>```

I do have constructor in my classes as below
for MyService

```<code>public MyService() {
    super("MyService");
}
</code>```

for BootStrapperService

```<code>public BootStrapperService() {
    super("BootStrapperService");
}
</code>```

Please suggest me a way to resolve this issue

答:
Try calling it as a user , use an handle.
For example :
sending broadcast message in System services</p>

```<code>context.sendBroadcastAsUser(intent,UserHandle.ALL);
</code>```

Body:
I have a android device on which am installing my app as a System app. this App has a service and trying to start that service as

static void startMyService(Context context, String action) {
    Intent service = new Intent(context, MyService.class);
    service.setAction(action);
    context.startService(service);
}

Previously I used to run my code on Android 5.1.1 and it used to work fine but now I updated it to 6.0. And now I am getting following logs.

Line 209209: 01-02 01:30:51.215 I/ActivityManager( 3571): Start proc 5678:com.example.myapp/1000 for broadcast com.example.myapp/.update.GenericBroadcastReceiver
Line 209239: 01-02 01:30:51.377 W/art     ( 5678): <clinit> didn't have expected constructor access flag in class com.example.myapp.update.BootStrapperService in dex file /system/app/myApp.apk
Line 209241: 01-02 01:30:51.378 W/art     ( 5678): <clinit> didn't have expected constructor access flag in class com.example.myapp.update.MyService in dex file /system/app/MyApp.apk
Line 209255: 01-02 01:30:51.393 W/art     ( 5678): <clinit> didn't have expected constructor access flag in class com.example.myapp.update.UpdateState in dex file /system/app/MyApp.apk
Line 209259: 01-02 01:30:51.400 W/ContextImpl( 5678): Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1221 android.content.ContextWrapper.startService:581 android.content.ContextWrapper.startService:581 com.example.myapp.update.MyService.startServiceWithAction:301 com.example.myapp.update.GenericBroadcastReceiver.onReceive:52
Line 209259: 01-02 01:30:51.400 W/ContextImpl( 5678): Calling a method in the system process without a qualified user: android.app.ContextImpl.startService:1221 android.content.ContextWrapper.startService:581 android.content.ContextWrapper.startService:581 com.example.myapp.update.MyService.startMyService:301 com.example.myapp.update.GenericBroadcastReceiver.onReceive:52
Line 209263: 01-02 01:30:51.408 E/PersistenceUtil( 5678): unabled to read update configuration

I do have constructor in my classes as below
for MyService

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

for BootStrapperService

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

Please suggest me a way to resolve this issue

Body:
Try calling it as a user , use an handle.
For example :
sending broadcast message in System services

context.sendBroadcastAsUser(intent,UserHandle.ALL);


问:
SQL Server Select LIKE Regex Equivalent to '?' or '\\s*'
I have a short question is there an equivalent to ? in SQL Server SELECT LIKE regex?

I try to select data from table in SQL Server 2012. Example data from column

```<code>...
<SOMETHING>
    <UNINTERESTING>test</UNINTERESTING>
    <INTERESTING>searchedString</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...
</code>```

or

```<code>...
<SOMETHING>
    <UNINTERESSTING>test</UNINTERESSTING>
    <INTERESING>searchedString but nevertheless wrong</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...
</code>```

I can select these with

```<code>LIKE '%<INTERESING>searchedString</INTERESTING>%'
</code>```

everything works fine, but it is possible that the value between <INTERESTING> ends sometimes with one or more spaces

e.g.

```<code><INTERESING>searchedString </INTERESTING>
<INTERESING>searchedString         </INTERESTING>
</code>```

If I try to select with %, then I got rows, where the search string is found but not between interesting, or between two interestings, or I get the wrong rows like

```<code><INTERESING>searchedString but nevertheless wrong</INTERESTING>
</code>```

I tried to select with _, %, [ ] but nothing of them get me the correct rows.

Is there an equivalent in SQL Server LIKE regex for ? (none or one-time)
or anything like \s* (whitespaces, can be none, one or more-times)

Thanks in advance

best regards

答:
Since you problem is spaces... just replace / remove those and your like statement should work and you can avoid other parsing and worrying about REGEX all together.

where replace(column,' ','') like'%<INTERESING>searchedString</INTERESTING>%'

If you expect TAB or NEWLINE then use replace and CHAR(10) and CHAR(13)

where replace(replace(replace(column,' ',''),char(10),''),char(13),'') like'%<INTERESING>searchedString</INTERESTING>%'

Body:
I have a short question is there an equivalent to ? in SQL Server SELECT LIKE regex?

I try to select data from table in SQL Server 2012. Example data from column

...
<SOMETHING>
    <UNINTERESTING>test</UNINTERESTING>
    <INTERESTING>searchedString</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...

or

...
<SOMETHING>
    <UNINTERESSTING>test</UNINTERESSTING>
    <INTERESING>searchedString but nevertheless wrong</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...

I can select these with

LIKE '%<INTERESING>searchedString</INTERESTING>%'

everything works fine, but it is possible that the value between <INTERESTING> ends sometimes with one or more spaces

e.g.

<INTERESING>searchedString </INTERESTING>
<INTERESING>searchedString         </INTERESTING>

If I try to select with %, then I got rows, where the search string is found but not between interesting, or between two interestings, or I get the wrong rows like

<INTERESING>searchedString but nevertheless wrong</INTERESTING>

I tried to select with _, %, [ ] but nothing of them get me the correct rows.

Is there an equivalent in SQL Server LIKE regex for ? (none or one-time)
or anything like \s* (whitespaces, can be none, one or more-times)

Thanks in advance

best regards


问:
How to override CSS selector?
My page includes a legacy css file which defines a style for the :invalid psuedo-class. I want to use some of the styles from this file, but I do not want invalid inputs to be red by default, I want input fields to use the default styling for input fields defined in the legacy file.

legacy.css

```<code>input:invalid {
  background-color: #F00
}
</code>```

Is there a way to override the style defined in legacy.css, and force it to use some other style from the file? Is there a better option for approaching this?

my.css

```<code>input:invalid {
  // super input:valid
}
</code>```

答:
Use !important; in legacy.css to override the selector in my.css.

OR

Make your selector  in my.css more specific so that it has greater weight over the selector in legacy.css. This is called specificity. More about this here

Title: How to override CSS selector?

Body:
My page includes a legacy css file which defines a style for the :invalid psuedo-class. I want to use some of the styles from this file, but I do not want invalid inputs to be red by default, I want input fields to use the default styling for input fields defined in the legacy file.

legacy.css

input:invalid {
  background-color: #F00
}

Is there a way to override the style defined in legacy.css, and force it to use some other style from the file? Is there a better option for approaching this?

my.css

input:invalid {
  // super input:valid
}


问:
Can't handle an exception in method called by AsyncTask
I can't seem to handle an exception properly. This is my async method:

```<code>private class PostData extends AsyncTask<String, Void, Void>
    {
        String response;
        protected void onPreExecute()
        {
            apply.setText("APPLYING...");
        }
        @Override
        protected Void doInBackground(String... params) {

            try {
                SendHTTPData sendHTTPData = new SendHTTPData();
                response = sendHTTPData.sendData(params);
            }
            catch(Exception e)
            {
                Log.e("someTag", "Caught exception after doinbackground");
                response = "ERROR!";
            }
                return null;
        }
        protected void onPostExecute()
        {
            apply.setText(response);
        }
}
</code>```

Now, whenever the sendData method is called, it returns either an "ERROR" or "APPLIED" string but when the web page is down, the exceptions ConnectException and SQLite Exceptions are generated and then my button gets stuck at "APPLYING" state.

I want to set the button text as "ERROR" whenever there is an error in the sendData method.

Here is my sendHTTPData class just in case:

```<code>public class SendHTTPData {

    public String sendData(String...)
    {
        String POST_DATA = "switch=" + sw + ...
            try {
                URL update = new URL(Utils.WEB_URL+path+"?"+POST_DATA);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(update.openStream()));

                String inputLine;
                while ((inputLine = in.readLine()) != null) {}
                in.close();
                Log.w("someTag", "DONE GET RESPONSE");
                if(inputLine=="1")
                    return "APPLIED";
                else
                    return "ERROR";
            }
            catch (Exception e) {
                Log.e("someTag", "ERROR BC OF EXCEPTION");
                return "ERROR";
            }

        }
}
</code>```

答:
Your onPostExecute is not correct so it's probably never getting called it should look like

```<code>@Override
protected void onPostExecute(Void param)
{
    apply.setText(response);
}
</code>```

Ideally, you should just send your response to your onPostExecute since that's where you use it so everything should look like this

```<code>private class PostData extends AsyncTask<String, Void, String>
    {
        protected void onPreExecute()
        {
            apply.setText("APPLYING...");
        }
        @Override
        protected String doInBackground(String... params) {
            String response;
            try {
                SendHTTPData sendHTTPData = new SendHTTPData();
                response = sendHTTPData.sendData(params);
            }
            catch(Exception e)
            {
                Log.e("someTag", "Caught exception after doinbackground");
                response = "ERROR!";
            }
                return response;
        }
        @Override
        protected void onPostExecute(String response)
        {
            apply.setText(response);
        }
}
</code>```

Body:
I can't seem to handle an exception properly. This is my async method:

private class PostData extends AsyncTask<String, Void, Void>
    {
        String response;
        protected void onPreExecute()
        {
            apply.setText("APPLYING...");
        }
        @Override
        protected Void doInBackground(String... params) {

            try {
                SendHTTPData sendHTTPData = new SendHTTPData();
                response = sendHTTPData.sendData(params);
            }
            catch(Exception e)
            {
                Log.e("someTag", "Caught exception after doinbackground");
                response = "ERROR!";
            }
                return null;
        }
        protected void onPostExecute()
        {
            apply.setText(response);
        }
}

Now, whenever the sendData method is called, it returns either an "ERROR" or "APPLIED" string but when the web page is down, the exceptions ConnectException and SQLite Exceptions are generated and then my button gets stuck at "APPLYING" state.

I want to set the button text as "ERROR" whenever there is an error in the sendData method.

Here is my sendHTTPData class just in case:

public class SendHTTPData {

    public String sendData(String...)
    {
        String POST_DATA = "switch=" + sw + ...
            try {
                URL update = new URL(Utils.WEB_URL+path+"?"+POST_DATA);
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(update.openStream()));

                String inputLine;
                while ((inputLine = in.readLine()) != null) {}
                in.close();
                Log.w("someTag", "DONE GET RESPONSE");
                if(inputLine=="1")
                    return "APPLIED";
                else
                    return "ERROR";
            }
            catch (Exception e) {
                Log.e("someTag", "ERROR BC OF EXCEPTION");
                return "ERROR";
            }

        }
}

Body:
Your onPostExecute is not correct so it's probably never getting called it should look like

@Override
protected void onPostExecute(Void param)
{
    apply.setText(response);
}

Ideally, you should just send your response to your onPostExecute since that's where you use it so everything should look like this

private class PostData extends AsyncTask<String, Void, String>
    {
        protected void onPreExecute()
        {
            apply.setText("APPLYING...");
        }
        @Override
        protected String doInBackground(String... params) {
            String response;
            try {
                SendHTTPData sendHTTPData = new SendHTTPData();
                response = sendHTTPData.sendData(params);
            }
            catch(Exception e)
            {
                Log.e("someTag", "Caught exception after doinbackground");
                response = "ERROR!";
            }
                return response;
        }
        @Override
        protected void onPostExecute(String response)
        {
            apply.setText(response);
        }
}


问:
In python, how can I extract string with regex?
I want to write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, I want to support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.
Examples

```<code># Header will become <h1>Header</h1>

## Header will become <h2>Header</h2>

###### Header will become <h6>Header</h6>
</code>```

Rules are as follows

Header content should only come after the initial hashtag(s) plus a space character.

Invalid headers should just be returned as the markdown that was recieved, no translation necessary.

Spaces before and after both the header content and the hashtag(s) should be ignored in the resulting output.

This is code I made.

```<code>import re
def markdown_parser(markdown):
    results =''
    pattern = re.compile("#+\s")
    matches = pattern.search(markdown.strip())
    if (matches != None):
        tag = matches[0]
        hashTagLen = len(tag) - 1
        htmlTag = "h" + str(hashTagLen)
        content = markdown.strip()[(hashTagLen + 1):]
        results = "<" + htmlTag + ">" + content + "</" + htmlTag + ">"
    else:
        results = markdown
    return results
</code>```

When I run this code, exception has occurred as follows.

Unhandled Exception: '_sre.SRE_Match' object is not subscriptable

I'm not sure why this error has occurred.

When I run the script on my shell, it works well.
But When I run it on unittest environment (import unittest), the error has occurred.

Please help me.

答:
You can use re.sub to substitute one to 6 # followed by a space and a word (the pattern being (#{1,6}) (\w+)) with the html you want.

re.sub can be used with a function to handle the replacement.

```<code>import re

def replacer(m):
    return '<h{level}>{header}</h{level}>'.format(level=len(m.group(1)), header=m.group(2))

def markdown_parser(markdown):
    results = [re.sub(r'(#{1,6}) (\w+)', replacer, line) for line in markdown.split('\n')]
    return "\n".join(results).strip()

sourceText = "##header#content## smaller header#contents### something"
print(markdown_parser(sourceText))
</code>```

Prints ##header#content
smaller
 header#contents
something

Body:
I want to write a simple markdown parser function that will take in a single line of markdown and be translated into the appropriate HTML. To keep it simple, I want to support only one feature of markdown in atx syntax: headers.

Headers are designated by (1-6) hashes followed by a space, followed by text. The number of hashes determines the header level of the HTML output.
Examples

# Header will become
Header

## Header will become
Header

###### Header will become
Header

Rules are as follows

Header content should only come after the initial hashtag(s) plus a space character.

Invalid headers should just be returned as the markdown that was recieved, no translation necessary.

Spaces before and after both the header content and the hashtag(s) should be ignored in the resulting output.

This is code I made.

import re
def markdown_parser(markdown):
    results =''
    pattern = re.compile("#+\s")
    matches = pattern.search(markdown.strip())
    if (matches != None):
        tag = matches[0]
        hashTagLen = len(tag) - 1
        htmlTag = "h" + str(hashTagLen)
        content = markdown.strip()[(hashTagLen + 1):]
        results = "<" + htmlTag + ">" + content + "</" + htmlTag + ">"
    else:
        results = markdown
    return results

When I run this code, exception has occurred as follows.

Unhandled Exception: '_sre.SRE_Match' object is not subscriptable

I'm not sure why this error has occurred.

When I run the script on my shell, it works well.
But When I run it on unittest environment (import unittest), the error has occurred.

Please help me.

Body:
You can use re.sub to substitute one to 6 # followed by a space and a word (the pattern being (#{1,6}) (\w+)) with the html you want.

re.sub can be used with a function to handle the replacement.

import re

def replacer(m):
    return '<h{level}>{header}</h{level}>'.format(level=len(m.group(1)), header=m.group(2))

def markdown_parser(markdown):
    results = [re.sub(r'(#{1,6}) (\w+)', replacer, line) for line in markdown.split('\n')]
    return "\n".join(results).strip()

sourceText = "##header#content## smaller header#contents### something"
print(markdown_parser(sourceText))

Prints ##header#content<h2>smaller</h2> header#contents<h3>something</h3>


问:
R how to partial match vector with another n-length vectors
Please see the following table. I need to check whether Family includes any strings in the column of Appln_ID.

I plan to use

```<code>df$Match[grepl(paste(df$Appln_ID,collapse = "|"),df$Family)]<-"1"
</code>```

but it doesn't work and reports "invalid regular expression CN02822097.8|CN200810105442.7|CN200680019886.8|C"

...

If I generate

```<code>set<-c(Appln_ID[1], Appln_ID[2]....Appln_ID[3000])
</code>```

it works...I don't know why...

答:
EDITED for clarification from OP

I made a fake data frame of the same format:

```<code>set.seed(1)
df <- data.frame( Appln_ID = letters[1:5],
              Family = sapply(1:5, function(x) paste0(letters[round(runif(runif(1)*10)*26)],collapse=";")))
</code>```

Here's what it looks like:

```<code>  Appln_ID            Family
1        a               j;o
2        b e;w;y;q;p;b;e;e;r
3        c             t;m;s
4        d   j;t;x;f;q;c;g;j
5        e             w;i;m
</code>```

To search which rows of Family can be found in all elements of Appln_ID, I use tidyverse and iterators:

```<code>install.packages("tidyverse")
install.packages("iterators")
library(tidyverse)
library(iterators)

search.all <- df %>%
                mutate(dummy = Family) %>%
                nest(dummy) %>%
                rowwise() %>%
                mutate(data = map(data, ~ unlist(strsplit(as.character(Family),";")))) %>%
                ungroup() %>%
                mutate(data = map(data, ~ (sum(sapply(iter(.x), function(y) y %in% Appln_ID) > 0)))) %>%
                unnest() %>%
                filter(data == 1) %>%
                select(-data)
</code>```

The idea is to 1) copy Family as a separate column (dummy), 2) strsplit dummy and save as a nested list, 3) determine whether any element of dummy is in Appln_ID and save as a logical, 4) filter rows where conditional is TRUE.

The output:

```<code>  Appln_ID    Family
1        a m;e;v;q;u
2        d u;a;l;s;r
3        e   v;k;f;b
</code>```

You forgot that e also contains a b.

Body:
Please see the following table. I need to check whether Family includes any strings in the column of Appln_ID.

I plan to use

df$Match[grepl(paste(df$Appln_ID,collapse = "|"),df$Family)]<-"1"

but it doesn't work and reports "invalid regular expression CN02822097.8|CN200810105442.7|CN200680019886.8|C"

...

If I generate

set<-c(Appln_ID[1], Appln_ID[2]....Appln_ID[3000])

it works...I don't know why...

Body:
EDITED for clarification from OP

I made a fake data frame of the same format:

set.seed(1)
df <- data.frame( Appln_ID = letters[1:5],
              Family = sapply(1:5, function(x) paste0(letters[round(runif(runif(1)*10)*26)],collapse=";")))

Here's what it looks like:

  Appln_ID            Family
1        a               j;o
2        b e;w;y;q;p;b;e;e;r
3        c             t;m;s
4        d   j;t;x;f;q;c;g;j
5        e             w;i;m

To search which rows of Family can be found in all elements of Appln_ID, I use tidyverse and iterators:

install.packages("tidyverse")
install.packages("iterators")
library(tidyverse)
library(iterators)

search.all <- df %>%
                mutate(dummy = Family) %>%
                nest(dummy) %>%
                rowwise() %>%
                mutate(data = map(data, ~ unlist(strsplit(as.character(Family),";")))) %>%
                ungroup() %>%
                mutate(data = map(data, ~ (sum(sapply(iter(.x), function(y) y %in% Appln_ID) > 0)))) %>%
                unnest() %>%
                filter(data == 1) %>%
                select(-data)

The idea is to 1) copy Family as a separate column (dummy), 2) strsplit dummy and save as a nested list, 3) determine whether any element of dummy is in Appln_ID and save as a logical, 4) filter rows where conditional is TRUE.

The output:

  Appln_ID    Family
1        a m;e;v;q;u
2        d u;a;l;s;r
3        e   v;k;f;b

You forgot that e also contains a b.


问:
Unable to run the shell script from Dockerfile which container some stdin to complete the script
hello i have script called postrun.sh when we run same script so it aks for user input to run the script , user required to provide  yes , enter , yes

i have docker file

```<code>FROM centos:latest
RUN useradd jenkins -u 1001
RUN echo "jenkins ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
RUN mkdir /opt/SOAtest
RUN mkdir /opt/SOAtest/parasoft
ADD epel.repo /etc/yum.repos.d/epel.repo
ADD RPM-GPG-KEY-EPEL-7  /etc/pki/rpm-gpg/
RUN yum -y clean all
#RUN yum -y install wget
ADD parasoft_soatest_9.7_linux_20140227.sh  /opt/SOAtest/
RUN chmod +x /opt/SOAtest/parasoft_soatest_9.7_linux_20140227.sh
RUN cd  /opt/SOAtest/parasoft
RUN echo "1/yes" | postrun.sh
</code>```

error which i am getting  while building docker image

```<code>**Step 12/12 : RUN echo "1/yes" |     ./parasoft_soatest_9.7_linux_20140227.sh
 ---> Running in 973ce094358a

/bin/sh: ./parasoft_soatest_9.7_linux_20140227.sh: No such file or directory

The command '/bin/sh -c echo "1/yes" | ./parasoft_soatest_9.7_linux_20140227.sh' returned a non-zero code: 127**
</code>```

答:
Atul,

bash gives you answer: "No such file or directory" and error code 127.
Are you sure that you are in right directory?

First you have this:

```<code>ADD parasoft_soatest_9.7_linux_20140227.sh  /opt/SOAtest/
</code>```

then you

```<code>cd  /opt/SOAtest/parasoft
</code>```

and execute postrun.sh

I will repeat my question: are you sure that you have Parasoft SOAtest installation file in /opt/SOAtest/parasoft directory?

Body:
hello i have script called postrun.sh when we run same script so it aks for user input to run the script , user required to provide  yes , enter , yes

i have docker file

FROM centos:latest
RUN useradd jenkins -u 1001
RUN echo "jenkins ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
RUN mkdir /opt/SOAtest
RUN mkdir /opt/SOAtest/parasoft
ADD epel.repo /etc/yum.repos.d/epel.repo
ADD RPM-GPG-KEY-EPEL-7  /etc/pki/rpm-gpg/
RUN yum -y clean all
#RUN yum -y install wget
ADD parasoft_soatest_9.7_linux_20140227.sh  /opt/SOAtest/
RUN chmod +x /opt/SOAtest/parasoft_soatest_9.7_linux_20140227.sh
RUN cd  /opt/SOAtest/parasoft
RUN echo "1/yes" | postrun.sh

error which i am getting  while building docker image

**Step 12/12 : RUN echo "1/yes" |     ./parasoft_soatest_9.7_linux_20140227.sh
 ---> Running in 973ce094358a

/bin/sh: ./parasoft_soatest_9.7_linux_20140227.sh: No such file or directory

The command '/bin/sh -c echo "1/yes" | ./parasoft_soatest_9.7_linux_20140227.sh' returned a non-zero code: 127**

Body:
Atul,

bash gives you answer: "No such file or directory" and error code 127.
Are you sure that you are in right directory?

First you have this:

ADD parasoft_soatest_9.7_linux_20140227.sh  /opt/SOAtest/

then you

cd  /opt/SOAtest/parasoft

and execute postrun.sh

I will repeat my question: are you sure that you have Parasoft SOAtest installation file in /opt/SOAtest/parasoft directory?


问:
$_GET undefined index
By passing a js variable to php code it displays a value at the end of the program.

But the problem is no mather what i try to initialise it with the score disapears at the end.

If i leave it alone everything displays as it should, but with the annoying undefined message until the last screen (where the value actually gets displayed).

```<code>$varOne = $xml->addChild('one', $_GET['resultone']);
</code>```

The variable in the js is being past by using window.location.href

I have tried several isset ways but none of them seem to have succeeded in resolving this annoying problem.

Kind regards.

答:
The $_GET function reads the query string.  So your javascript code should look something like this:

window.location.href="myscript.php?resultone=123"

Is that how you're doing it?

Title: $_GET undefined index

Body:
By passing a js variable to php code it displays a value at the end of the program.

But the problem is no mather what i try to initialise it with the score disapears at the end.

If i leave it alone everything displays as it should, but with the annoying undefined message until the last screen (where the value actually gets displayed).

$varOne = $xml->addChild('one', $_GET['resultone']);

The variable in the js is being past by using window.location.href

I have tried several isset ways but none of them seem to have succeeded in resolving this annoying problem.

Kind regards.