问:
Cannibal numbers with target incorrect return
I'm trying to write a function that, when given a list of numbers or string of numbers separated by commas as well as a target number, will find the number of numbers in that list that are equal to the target or can become the target.

Numbers can change by eating numbers that are smaller than or equal to them, after eating a number the larger number will have grown by 1 and the smaller number disappears.

The function checks all the numbers in the provided list so if you have [27,9,11,10,8] and your target is 12 then the function should return 3 because 11 can eat 10 to become 12, 10 can eat 9 and 8 to become 12, and 9 can eat 8 then it can now eat 10 and then 11 to become 12.

My issue is that when provided with something like [3,3,3,2,2,2,1,1,1] with target 4, my function returns the wrong value (value should be 9). For some reason my function does not recognise numbers that are equal as numbers that can be eaten even though in the if statement there is a ">=".

```<code>def cannibal(l, target):

     try:
         l = l.split(",")
         l.sort(reverse = True)
         l = list(map(int, l))
         print (l)

     except:
         l.sort(reverse = True)
         print (l)

     finally:

         eatingl = l[:]
         count = 0
         flag = True

         for i in range(0,len(l)-1):

             if l[i] > target:
                 print (l[i],"got skipped at",i)
                 continue

             if l[i] == target:
                 print (l[i],"at",i,"got added")
                 count += 1
                 continue

             if l[i] < target:

                 while flag:

                     if eatingl[i] < target and len(eatingl) == 1:
                         flag = False
                         break

                     if eatingl[i] == target:
                             (eatingl[i],"at",i,"got added")
                             count +=1
                             flag = False
                             break

                     for j in range(0,len(eatingl)):

                         if eatingl[i] == eatingl[j]:
                             continue

                         print (eatingl[i],eatingl[j])

                         if eatingl[i] >= eatingl[j]:
                             print (eatingl[i],"is eating",eatingl[j])
                             eatingl.remove(eatingl[j])
                             eatingl[i] += 1
                             break

                         if eatingl[i] > target:
                             flag = False
                             break

         print (count)
         return count
</code>```

答:
my function does not recognise numbers that are equal as numbers that can be eaten even though in the if statement there is a ">=".

There is only one >= in your code, and not far above it is this:

                         if eatingl[i] == eatingl[j]:
                             continue
```

<p>This line stops a number from eating an equal number.  Did you want this line to stop a number from eating itself?  If so, you need the condition above to be <code>if i == j:</code> instead.</p>

<p>There are, however, a few other problems with your code:</p>

<ul>
<li><p>Once you've found one number that can reach the target, you need to reset the list for the next number.  You already have a line <code>eatingl = l[:]</code> which will do this, but it's outside the <code>for i in ...</code> loop.  Move it inside.</p></li>
<li><p>Secondly, under the line <code>if eatingl[i] == target:</code> you have the following line.</p>

```                     (eatingl[i],"at",i,"got added")
```

<p>This puts together a tuple with four items in it and then throws it away because nothing is done with it.  I'm guessing you are missing a <code>print</code> here.</p></li>
<li><p>Thirdly, your variable <code>flag</code> is set to <code>True</code> before the <code>for i in ...</code> loop starts.  As soon as this variable gets set to <code>False</code>, the <code>while</code> loop never gets entered again, so your program will never find any more than one cannibal number.  Instead, move the line <code>flag = True</code> to immediately above the <code>while</code> loop.</p></li>
<li><p>Next, when a number gets eaten you remove it from the list <code>eatingl</code>.  This doesn't cause a problem when <code>j > i</code>, but it does when <code>j < i</code>, because removing the number at index <code>j</code> will move the number at index <code>i</code> to index <code>i - 1</code>, after which you then increment the number at index <code>i</code>, which might be a different number.</p>

<p>Adding to or removing items from a list that you are iterating through often causes problems.  Instead of removing the numbers it is simpler to replace them with a placeholder value such as <code>0</code>, <code>-1</code> or <code>None</code>.  You would need to be sure that you don't attempt to eat a number that has already been eaten, and you can do this by checking that <code>eatingl[j]</code> isn't the placeholder just before checking whether <code>eatingl[i] >= eatingl[j]</code>.</p></li>
<li><p>If your program gets to the end of the <code>j</code> loop without <code>break</code>ing out of it, then there aren't enough other numbers that <code>eatingl[i]</code> could eat to reach the target.  In this situation you would want to <code>break</code> out of the <code>while</code> loop.  The easiest way to do this is to add an <code>else</code> clause to the <code>for</code> loop:</p>

<pre class="lang-py prettyprint-override"><code>                     else:
                         print("Could do no more for", eatingl[i])
                         flag = False
                         break
</code>```

The else line in the above should line up with the for j in ... line.  A for loop can have an else block, and the code in the else block runs if the code in the for loop did not break.

Finally, your i loop should be for i in range(0,len(l)): rather than for i in range(0,len(l)-1):.  If you have a unique smallest number, as in your example 27,9,11,10,8 then this isn't a problem: a unique smallest number cannot eat any other numbers so skipping it doesn't do any harm.  But in your example 3,3,3,2,2,2,1,1,1, where the smallest number is 1 and there are three of them, each of the 1s can eat the other two 1s and then a 2 to become a 4.

I made these changes to your code and it gave me the output I expected it to.

Body:
I'm trying to write a function that, when given a list of numbers or string of numbers separated by commas as well as a target number, will find the number of numbers in that list that are equal to the target or can become the target.

Numbers can change by eating numbers that are smaller than or equal to them, after eating a number the larger number will have grown by 1 and the smaller number disappears.

The function checks all the numbers in the provided list so if you have [27,9,11,10,8] and your target is 12 then the function should return 3 because 11 can eat 10 to become 12, 10 can eat 9 and 8 to become 12, and 9 can eat 8 then it can now eat 10 and then 11 to become 12.

My issue is that when provided with something like [3,3,3,2,2,2,1,1,1] with target 4, my function returns the wrong value (value should be 9). For some reason my function does not recognise numbers that are equal as numbers that can be eaten even though in the if statement there is a ">=".

def cannibal(l, target):

     try:
         l = l.split(",")
         l.sort(reverse = True)
         l = list(map(int, l))
         print (l)

     except:
         l.sort(reverse = True)
         print (l)

     finally:

         eatingl = l[:]
         count = 0
         flag = True

         for i in range(0,len(l)-1):

             if l[i] > target:
                 print (l[i],"got skipped at",i)
                 continue

             if l[i] == target:
                 print (l[i],"at",i,"got added")
                 count += 1
                 continue

             if l[i] < target:

                 while flag:

                     if eatingl[i] < target and len(eatingl) == 1:
                         flag = False
                         break

                     if eatingl[i] == target:
                             (eatingl[i],"at",i,"got added")
                             count +=1
                             flag = False
                             break

                     for j in range(0,len(eatingl)):

                         if eatingl[i] == eatingl[j]:
                             continue

                         print (eatingl[i],eatingl[j])

                         if eatingl[i] >= eatingl[j]:
                             print (eatingl[i],"is eating",eatingl[j])
                             eatingl.remove(eatingl[j])
                             eatingl[i] += 1
                             break

                         if eatingl[i] > target:
                             flag = False
                             break

         print (count)
         return count

Body:
my function does not recognise numbers that are equal as numbers that can be eaten even though in the if statement there is a ">=".

There is only one >= in your code, and not far above it is this:

                         if eatingl[i] == eatingl[j]:
                             continue

This line stops a number from eating an equal number.  Did you want this line to stop a number from eating itself?  If so, you need the condition above to be if i == j: instead.

There are, however, a few other problems with your code:

Once you've found one number that can reach the target, you need to reset the list for the next number.  You already have a line eatingl = l[:] which will do this, but it's outside the for i in ... loop.  Move it inside.

Secondly, under the line if eatingl[i] == target: you have the following line.

                     (eatingl[i],"at",i,"got added")

This puts together a tuple with four items in it and then throws it away because nothing is done with it.  I'm guessing you are missing a print here.

Thirdly, your variable flag is set to True before the for i in ... loop starts.  As soon as this variable gets set to False, the while loop never gets entered again, so your program will never find any more than one cannibal number.  Instead, move the line flag = True to immediately above the while loop.

Next, when a number gets eaten you remove it from the list eatingl.  This doesn't cause a problem when j > i, but it does when j < i, because removing the number at index j will move the number at index i to index i - 1, after which you then increment the number at index i, which might be a different number.

Adding to or removing items from a list that you are iterating through often causes problems.  Instead of removing the numbers it is simpler to replace them with a placeholder value such as 0, -1 or None.  You would need to be sure that you don't attempt to eat a number that has already been eaten, and you can do this by checking that eatingl[j] isn't the placeholder just before checking whether eatingl[i] >= eatingl[j].

If your program gets to the end of the j loop without breaking out of it, then there aren't enough other numbers that eatingl[i] could eat to reach the target.  In this situation you would want to break out of the while loop.  The easiest way to do this is to add an else clause to the for loop:

                     else:
                         print("Could do no more for", eatingl[i])
                         flag = False
                         break

The else line in the above should line up with the for j in ... line.  A for loop can have an else block, and the code in the else block runs if the code in the for loop did not break.

Finally, your i loop should be for i in range(0,len(l)): rather than for i in range(0,len(l)-1):.  If you have a unique smallest number, as in your example 27,9,11,10,8 then this isn't a problem: a unique smallest number cannot eat any other numbers so skipping it doesn't do any harm.  But in your example 3,3,3,2,2,2,1,1,1, where the smallest number is 1 and there are three of them, each of the 1s can eat the other two 1s and then a 2 to become a 4.

I made these changes to your code and it gave me the output I expected it to.


来源: stackexchange

问:
How and where does SSL signing apply to emails?
I am trying to find out how SSL signing of emails work and if it gets signed server side or MTA side? I know this is a bit vague maybe but any resources to read or documentation would help a lot :D

Like for example I use a ezComponents mail object to send a mail object to the MTA server. DO I have to sign the mail object inside of PHP by using something

OR

Does the signing happen on the sending server (MTA)?

Just to add some clarity, I would like to use this functionality to send secure emails to customers for their monthly statements and reports. But implementation is irrelevant at this stage, I am interested in docs and resources and wisdom from people that knows :D

EDIT: Okay so I am using S/MIME. does anybody have an idea how to do this? I can't find any good PHP examples.

答: Email signing happens in the client's MUA. All you need is to generate an S/MIME email message and send it using your MTA as a regular message.</p>

ContentLicense: CC BY-SA 3.0


问:
object FlinkKafkaConsumer010 is not a member of package org.apache.flink.streaming.connectors.kafka
I am trying to assembly a little program to connect to kafka topic using apache flink. I need to use FlinkKafkaConsumer010.

```<code>package uimp
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.util.serialization.SimpleStringSchema
import org.apache.flink.streaming.connectors.kafka.{FlinkKafkaConsumer010}
import java.util.Properties

object Silocompro {
  def main(args: Array[String]): Unit = {
 // set up the execution environment
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)

    val propertiesTopicDemographic = new Properties()
    propertiesTopicDemographic.setProperty("bootstrap.servers", "bigdata.dataspartan.com:19093")
    propertiesTopicDemographic.setProperty("group.id", "demographic")

    val myConsumerDemographic = new FlinkKafkaConsumer010[String]("topic_demographic", new
    SimpleStringSchema(), propertiesTopicDemographic)

    val messageStreamDemographic = env
      .addSource(myConsumerDemographic)
      .print()

    env.execute("Flink Scala API Skeleton")

   }
 }
</code>```

My problem is when a try to assembly my program with this build.sbt, the compiler returns an error "object FlinkKafkaConsumer010 is not a member of package org.apache.flink.streaming.connectors.kafka":

```<code>      ThisBuild / resolvers ++= Seq("Apache Development Snapshot Repository" at
      "https://repository.apache.org/content/repositories/snapshots/",Resolver.mavenLocal)

      name := "silocompro"

      version := "1.0"

      organization := "uimp"

      ThisBuild / scalaVersion := "2.12.11"

      val flinkVersion = "1.9.0"

      val flinkDependencies = Seq(
         "org.apache.flink" %% "flink-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-streaming-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-core"% flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka-base" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-clients" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka" % flinkVersion % "provided")

      lazy val root = (project in file(".")).
      settings( libraryDependencies ++= flinkDependencies)

      assembly / mainClass := Some("uimp.Silocompro")

      Compile / run  := Defaults.runTask(Compile / fullClasspath,
                               Compile / run / mainClass,
                               Compile / run / runner
                              ).evaluated

      Compile / run / fork := true
      Global / cancelable := true

      assembly / assemblyOption  := (assembly / assemblyOption).value.copy(includeScala = false)
</code>```

What is the reason of this dependency error?

答:
The connectors are not part of the flink-binary, this means that you need to have connectors in compile scope, so this basically means that you need to remove the provided from those dependencies. In this setting the app will work on cluster.

BUT, if You want to run it locally without starting the cluster then You should have all the flink dependencies in compile scope i.e. remove all provided scope declarations.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to assembly a little program to connect to kafka topic using apache flink. I need to use FlinkKafkaConsumer010.

package uimp
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.util.serialization.SimpleStringSchema
import org.apache.flink.streaming.connectors.kafka.{FlinkKafkaConsumer010}
import java.util.Properties

object Silocompro {
  def main(args: Array[String]): Unit = {
 // set up the execution environment
    val env = StreamExecutionEnvironment.getExecutionEnvironment
    env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)

    val propertiesTopicDemographic = new Properties()
    propertiesTopicDemographic.setProperty("bootstrap.servers", "bigdata.dataspartan.com:19093")
    propertiesTopicDemographic.setProperty("group.id", "demographic")

    val myConsumerDemographic = new FlinkKafkaConsumer010[String]("topic_demographic", new
    SimpleStringSchema(), propertiesTopicDemographic)

    val messageStreamDemographic = env
      .addSource(myConsumerDemographic)
      .print()

    env.execute("Flink Scala API Skeleton")

   }
 }

My problem is when a try to assembly my program with this build.sbt, the compiler returns an error "object FlinkKafkaConsumer010 is not a member of package org.apache.flink.streaming.connectors.kafka":

      ThisBuild / resolvers ++= Seq("Apache Development Snapshot Repository" at
      "https://repository.apache.org/content/repositories/snapshots/",Resolver.mavenLocal)

      name := "silocompro"

      version := "1.0"

      organization := "uimp"

      ThisBuild / scalaVersion := "2.12.11"

      val flinkVersion = "1.9.0"

      val flinkDependencies = Seq(
         "org.apache.flink" %% "flink-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-streaming-scala" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-core"% flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka-base" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-clients" % flinkVersion % "provided",
         "org.apache.flink" %% "flink-connector-kafka" % flinkVersion % "provided")

      lazy val root = (project in file(".")).
      settings( libraryDependencies ++= flinkDependencies)

      assembly / mainClass := Some("uimp.Silocompro")

      Compile / run  := Defaults.runTask(Compile / fullClasspath,
                               Compile / run / mainClass,
                               Compile / run / runner
                              ).evaluated

      Compile / run / fork := true
      Global / cancelable := true

      assembly / assemblyOption  := (assembly / assemblyOption).value.copy(includeScala = false)

What is the reason of this dependency error?


问:
Why am I getting "ValueError: I/O operation on closed file." when I run the last block of code in Jupyter?
Why am I getting "ValueError: I/O operation on closed file." when I run the last block of code in Jupyter?</p>

```<code># Dependencies
import os
import csv

#Set lists to hold values
months = []
revenue = []
monthly_change = []

# Set path for file
bank_csv_path = os.path.join("Resources", "budget_data.csv")

# Open and read file
with open(bank_csv_path, newline="") as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=",")
    csv_header = next(csv_reader)

    # read thru each row after the header and list months
    for row in csv_reader:
        months.append(row[0])
        revenue.append(row[1])
</code>```

答:
Try changing this:

```<code>bank_csv_path = os.path.join("Resources", "budget_data.csv")
</code>```

to

```<code>bank_csv_path = os.path.join(os.getcwd(), "Resources", "budget_data.csv")
print(bank_csv_path)
</code>```

See if what is printed is what you expected…

Body:
Why am I getting "ValueError: I/O operation on closed file." when I run the last block of code in Jupyter?

# Dependencies
import os
import csv

#Set lists to hold values
months = []
revenue = []
monthly_change = []

# Set path for file
bank_csv_path = os.path.join("Resources", "budget_data.csv")

# Open and read file
with open(bank_csv_path, newline="") as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=",")
    csv_header = next(csv_reader)

    # read thru each row after the header and list months
    for row in csv_reader:
        months.append(row[0])
        revenue.append(row[1])

Body:
Try changing this:

bank_csv_path = os.path.join("Resources", "budget_data.csv")

to

bank_csv_path = os.path.join(os.getcwd(), "Resources", "budget_data.csv")
print(bank_csv_path)

See if what is printed is what you expected…


问:
Warning from gcc: braces around scalar initializer, how to fix?
At rewriting kernel driver I got this warning:

```<code>msm-cirrus-playback.c:545:2: warning: braces around scalar initializer
</code>```

Read that this warning appears when I am declaring one structure's field in {}:

```<code>struct random_struct test = {
    { .name = "StackOverflow" },
    { .name = "StackExchange" },
};
</code>```

But my structure have 2-3 fields in {}:

```<code>static struct device_attribute *opalum_dev_attr = {
    {
    .attr->name = "temp-acc",
    .show = opsl_temp_acc_show,
    .store = opsl_temp_acc_store,
    },
    {
    .attr->name = "count",
    .show = opsl_count_show,
    .store = opsl_count_store,
    },
    {
    .attr->name = "ambient",
    .show = opsl_ambient_show,
    .store = opsl_ambient_store,
    },
    {
    .attr->name = "f0",
    .show = opsl_f0_show,
    .store = opsl_f0_store,
    },
    {
    .attr->name = "pass",
    .show = opsl_pass_show,
    },
    {
    .attr->name = "start",
    .show = opsl_cali_start,
    },
};
</code>```

This structure:

```<code>struct device_attribute {
    struct attribute    attr;
    ssize_t (*show)(struct device *dev, struct device_attribute *attr,
            char *buf);
     ssize_t (*store)(struct device *dev, struct device_attribute *attr,
             const char *buf, size_t count);
};
</code>```

How can I fix this warning? Qualcomm kernels are building with -Werror flag, so this warning is critical.

答:
It is because you initialize the pointer to the struct not the struct itself.

you need to assign the reference to the struct for example by using compound literals

```<code>struct x
{
    int a,b,c;
}a = {1,2,3};

void foo()
{
    struct x a = {1,2,3};
    struct x *b = {1,2,3}; // wrong warning here
    struct x *x = &(struct x){1,2,3}; // correct reference to the struct assigned (using compound literal
    struct x *y = (struct x[]){{1,2,3}, {4,5,6}, {4,5,6}, };
    struct x z[] = {{1,2,3}, {4,5,6}, {4,5,6}, };

}
</code>```

Body:
At rewriting kernel driver I got this warning:

msm-cirrus-playback.c:545:2: warning: braces around scalar initializer

Read that this warning appears when I am declaring one structure's field in {}:

struct random_struct test = {
    { .name = "StackOverflow" },
    { .name = "StackExchange" },
};

But my structure have 2-3 fields in {}:

static struct device_attribute *opalum_dev_attr = {
    {
    .attr->name = "temp-acc",
    .show = opsl_temp_acc_show,
    .store = opsl_temp_acc_store,
    },
    {
    .attr->name = "count",
    .show = opsl_count_show,
    .store = opsl_count_store,
    },
    {
    .attr->name = "ambient",
    .show = opsl_ambient_show,
    .store = opsl_ambient_store,
    },
    {
    .attr->name = "f0",
    .show = opsl_f0_show,
    .store = opsl_f0_store,
    },
    {
    .attr->name = "pass",
    .show = opsl_pass_show,
    },
    {
    .attr->name = "start",
    .show = opsl_cali_start,
    },
};

This structure:

struct device_attribute {
    struct attribute    attr;
    ssize_t (*show)(struct device *dev, struct device_attribute *attr,
            char *buf);
     ssize_t (*store)(struct device *dev, struct device_attribute *attr,
             const char *buf, size_t count);
};

How can I fix this warning? Qualcomm kernels are building with -Werror flag, so this warning is critical.

Body:
It is because you initialize the pointer to the struct not the struct itself.

you need to assign the reference to the struct for example by using compound literals

struct x
{
    int a,b,c;
}a = {1,2,3};

void foo()
{
    struct x a = {1,2,3};
    struct x *b = {1,2,3}; // wrong warning here
    struct x *x = &(struct x){1,2,3}; // correct reference to the struct assigned (using compound literal
    struct x *y = (struct x[]){{1,2,3}, {4,5,6}, {4,5,6}, };
    struct x z[] = {{1,2,3}, {4,5,6}, {4,5,6}, };

}


问:
How to find the Big-O complexity mentioned below
Could you guys help in understanding the time complexity of the below code -

```<code>int count = 0;
for (int i = N; i > 0; i /= 2) {
    for (int j = 0; j < i; j++) {
        count += 1;
    }
}
</code>```

It was my underdstanding that this should be O(nlogn) but that is wrong.
Just to update why I thought it would be O(nlogn) because in the first loop, we are dividing the i by 2 meaning we are cutting it in half, so that would be log n and in the inner loop we are running it till i, so it would be N, so complexity would be O(nlogn)
Thanks in advance

答:
One of the common mistakes of people when they approach to these tasks are looking at things as "straightforward", But this is not the case on many scenarios (like this one).

The right way to figure out the time complexity (also in memory complexity) is trying to "follow" the steps of calculation the program will execute and how much time each step will take.

I would recommend writing down what will happen at the first 5+- iterations and try to see what is the pattern.

So, in this case, the first loop is gonna start from N until 0 while the index is reduced by half each iteration. You were right that it implies for O(log(N)), but lets write the index down for some of the first iterations:

```<code>i=N
i=N/2
i=N/4
i=N/8
i=N/16
...
</code>```

Now, the real thing happens in the second for which inside the first loop.
First, you can see that the second index j has a dependency with i which should immediately raise a red flag and we should pay special attention to it.
The second loop goes from 0 to i of the current iteration with increment of one. At first, you would probably say it is O(n) because the change is an increment of one and it goes from 0 to a specific known integer. But since that integer is dynamically change, you can't really say that, and you must know what i is gonna be.
So lets write the first iterations of the inner loop for each of the iterations above:

```<code>i=N       ->  |  j=0  |  j=1  |  j=2  | ... |  j=N    |
i=N/2     ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/2  |
i=N/4     ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/4  |
i=N/8     ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/8  |
i=N/16    ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/16 |
...
</code>```

Now, each "box" (|    |) I wrote above is a step the program executes. As I said before, we need to know also how much time each step is gonna take. In this case, each step (each iteration) includes one operation of variable (count) increment, which we consider as O(1) (a constant).

The last thing we should do is to sum up all the steps we mentioned above with their costs:

First row will run N times (0,1,2,..,N) - each time the step will cost O(1). -> So it's going to be N*1 = N
Second row will run N/2 times (0,1,2,..,N/2) - each time the step will cost O(1). -> So it's going to be (N/2)*1 = N/2
Third row will run N/4 times (0,1,2,..,N/4) - each time the step will cost O(1). -> So it's going to be (N/4)*1 = N/4
And so on..

When we sum it up, the program cost will be: N+(N/2)+(N/4)+(N/8)+...+~(N/N) = N * ( 1 + (1/2) + (1/4) + (1/8) +... )
( 1 + (1/2) + (1/4) + (1/8) +... ) is a simple known math series. (You can get help from some websites or little google search to learn the results of those or more complicated series).
This one Equals to 2-(2/N) at most.

So the final cost will be: N * ( 2 - (2/N) ) = 2N - 2 which is O(N) overall.

This answer is pretty long and well detailed for this question but I was trying to show a "way of thinking" more than just solving the problem. I hope it helped you (and others) to think different on questions like these, Trying to take each loop and each step and check carefully how many steps are going to happen here and more importantly (and mostly forgotten) what is the cost of each step.

Body:
Could you guys help in understanding the time complexity of the below code -

int count = 0;
for (int i = N; i > 0; i /= 2) {
    for (int j = 0; j < i; j++) {
        count += 1;
    }
}

It was my underdstanding that this should be O(nlogn) but that is wrong.
Just to update why I thought it would be O(nlogn) because in the first loop, we are dividing the i by 2 meaning we are cutting it in half, so that would be log n and in the inner loop we are running it till i, so it would be N, so complexity would be O(nlogn)
Thanks in advance

Body:
One of the common mistakes of people when they approach to these tasks are looking at things as "straightforward", But this is not the case on many scenarios (like this one).

The right way to figure out the time complexity (also in memory complexity) is trying to "follow" the steps of calculation the program will execute and how much time each step will take.

I would recommend writing down what will happen at the first 5+- iterations and try to see what is the pattern.

So, in this case, the first loop is gonna start from N until 0 while the index is reduced by half each iteration. You were right that it implies for O(log(N)), but lets write the index down for some of the first iterations:

i=N
i=N/2
i=N/4
i=N/8
i=N/16
...

Now, the real thing happens in the second for which inside the first loop.
First, you can see that the second index j has a dependency with i which should immediately raise a red flag and we should pay special attention to it.
The second loop goes from 0 to i of the current iteration with increment of one. At first, you would probably say it is O(n) because the change is an increment of one and it goes from 0 to a specific known integer. But since that integer is dynamically change, you can't really say that, and you must know what i is gonna be.
So lets write the first iterations of the inner loop for each of the iterations above:

i=N       ->  |  j=0  |  j=1  |  j=2  | ... |  j=N    |
i=N/2     ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/2  |
i=N/4     ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/4  |
i=N/8     ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/8  |
i=N/16    ->  |  j=0  |  j=1  |  j=2  | ... |  j=N/16 |
...

Now, each "box" (|    |) I wrote above is a step the program executes. As I said before, we need to know also how much time each step is gonna take. In this case, each step (each iteration) includes one operation of variable (count) increment, which we consider as O(1) (a constant).

The last thing we should do is to sum up all the steps we mentioned above with their costs:

First row will run N times (0,1,2,..,N) - each time the step will cost O(1). -> So it's going to be N*1 = N
Second row will run N/2 times (0,1,2,..,N/2) - each time the step will cost O(1). -> So it's going to be (N/2)*1 = N/2
Third row will run N/4 times (0,1,2,..,N/4) - each time the step will cost O(1). -> So it's going to be (N/4)*1 = N/4
And so on..

When we sum it up, the program cost will be: N+(N/2)+(N/4)+(N/8)+...+~(N/N) = N * ( 1 + (1/2) + (1/4) + (1/8) +... )
( 1 + (1/2) + (1/4) + (1/8) +... ) is a simple known math series. (You can get help from some websites or little google search to learn the results of those or more complicated series).
This one Equals to 2-(2/N) at most.

So the final cost will be: N * ( 2 - (2/N) ) = 2N - 2 which is O(N) overall.

This answer is pretty long and well detailed for this question but I was trying to show a "way of thinking" more than just solving the problem. I hope it helped you (and others) to think different on questions like these, Trying to take each loop and each step and check carefully how many steps are going to happen here and more importantly (and mostly forgotten) what is the cost of each step.


问:
Get a vector with the count of consecutive specific values in R
I have a dataframe that looks like this:

```<code>    (TimeDate,Movement,Booked)

    1   2017-01-02 09:00:13 FALSE   TRUE
    2   2017-01-02 09:01:13 FALSE   TRUE
    3   2017-01-02 09:02:15 TRUE    TRUE
    4   2017-01-02 09:03:13 TRUE    TRUE
    5   2017-01-02 09:04:13 FALSE   FALSE
    6   2017-01-02 09:05:13 FALSE   FALSE
    7   2017-01-02 09:06:13 FALSE   TRUE
    8   2017-01-02 09:07:13 FALSE   TRUE
    9   2017-01-02 09:08:14 TRUE    TRUE
    10  2017-01-02 09:09:13 FALSE   TRUE
</code>```

It has a minute by minute log with two booleans corresponding to movement detected and room booked. What I want to obtain is a vector that counts the consecutive occurrences of (FALSE,TRUE) for Movement and Booked comumns, so in this case I would want a resulting vector like this one:

```<code>    c(2,2,1)
</code>```

Where the first element is the count of lines 1 and 2, the second for lines 7 and 8 and the last one for line 10.

Honestly I don't even know how to start with this.
Thanks!

答:
Edit: Did not see Roman's identical solution when posting.

We would like something like:

```<code>tmp <- rle(with(df, !Movement & Booked))
tmp$lengths[tmp$values]
</code>```

The indexing by tmp$values ensures you only get the rows corresponding to the pattern you've specified.

Hope this helps!

Body:
I have a dataframe that looks like this:

    (TimeDate,Movement,Booked)

    1   2017-01-02 09:00:13 FALSE   TRUE
    2   2017-01-02 09:01:13 FALSE   TRUE
    3   2017-01-02 09:02:15 TRUE    TRUE
    4   2017-01-02 09:03:13 TRUE    TRUE
    5   2017-01-02 09:04:13 FALSE   FALSE
    6   2017-01-02 09:05:13 FALSE   FALSE
    7   2017-01-02 09:06:13 FALSE   TRUE
    8   2017-01-02 09:07:13 FALSE   TRUE
    9   2017-01-02 09:08:14 TRUE    TRUE
    10  2017-01-02 09:09:13 FALSE   TRUE

It has a minute by minute log with two booleans corresponding to movement detected and room booked. What I want to obtain is a vector that counts the consecutive occurrences of (FALSE,TRUE) for Movement and Booked comumns, so in this case I would want a resulting vector like this one:

    c(2,2,1)

Where the first element is the count of lines 1 and 2, the second for lines 7 and 8 and the last one for line 10.

Honestly I don't even know how to start with this.
Thanks!

Body:
Edit: Did not see Roman's identical solution when posting.

We would like something like:

tmp <- rle(with(df, !Movement & Booked))
tmp$lengths[tmp$values]

The indexing by tmp$values ensures you only get the rows corresponding to the pattern you've specified.

Hope this helps!


问:
How to get a live preview of data-img-src from a select form?
tl;dr

I have a dropdown list with the names of png symbols and would like to present a live preview of what the image looks like next to the dropdown before the user hits 'submit'.

More detailed information:

I have a leaflet.js map where the user can place markers. When the user does, a popup opens where a symbol for the marker can be choosen. This is where the dropdown menu sits and of course it would be nice to have a preview of the symbol. Especially as there are quite a few.

Initially I wanted to have an emoji-picker-style menu with different tabs for different categories of symbols. Alas, I hardly managed to find any libraries/code snippets as I do not want to insert unicode smileys but png symbols. What I did find was the onesignal emoji-picker and the jquery.emojiarea plugin. But I failed to get them to work. Most likely because I'm a javascript beginner.

Then I tried to fall back to rveras image-picker for a simpler but hopefully easier to implement way, but also failed at getting it to work.

Now I think, maybe the is a simple, pure jquery way of doing just a preview of the png next to a dropdown?

So you see, my question is actually three-fold:

Does anyone know a tutorial for dummies on how to get a emoji-picker
style menu to work with png symbols? Or...

Can anyone show how to get the image-picker to work? Or ..

Can you tell me how I do this with vanilla jquery or javascript?

A problem might be that I'm operating within a leaflet popup that only allows html as content, so my code looks something like this:

```<code> map.on('draw:created', function (event) {
      layer = event.layer,
          feature = layer.feature = layer.feature || {};        // Intialize layer.feature
          feature.type = feature.type || "Feature";             // Intialize feature.type
      props = feature.properties = feature.properties || {};    // Intialize feature.properties
      props.name = "my name";
      props.description = "my content";
      props.icon = "my icon";
      //picker()              //execute image picker
      var editablePopup = L.popup();
      var content = //Textfield for the marker name
                    '<span><b>Enter the name</b></span><br/><input id="shapeName" type="text"/><br/><br/>' +
                    //Dropdown to choose the icon
                    '<span><b>Choose an icon</b></span></br>'+
                    '<select id="shapeIcon" class="image-picker">'+
                    '<optgroup label="Cats">'+
                      '<option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>'+
                      '<option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>'+
                      '<option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>'+
                      '<option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>'+
                    '</optgroup>'+
                    '<optgroup label="Animals">'+
                      '<option data-img-src="http://lorempixel.com/220/200/animals/" value="5">Animal 1</option>'+
                      '<option data-img-src="http://lorempixel.com/180/200/animals/" value="6">Animal 2</option>'+
                      '<option data-img-src="http://lorempixel.com/130/200/animals/" value="7">Animal 3</option>'+
                      '<option data-img-src="http://lorempixel.com/270/200/animals/" value="8">Animal 4</option>'+
                    '</optgroup></select></br>'+
                    //Textarea (flexible in size as opposed to textfield) for the general description
                    '<span><b>Enter a description<b/></span><br/><textarea id="shapeDesc" cols="25" rows="5"></textarea><br/><br/>'+
                    //Save Button that call the saveIdIW functions
                    '<input type="button" id="okBtn" value="Save" onclick="saveIdIW()"/>';
      editablePopup.setContent(content);
      editablePopup.setLatLng(layer.getLatLng());
      editablePopup.openOn(map);
      drawnItems.addLayer(layer);
    })
</code>```

If you want to see the whole code of the leaflet map, where I try this, see here. Warning! It's likely quite messy...

PS: if you want to see the problem in action, go to fictionalmaps.com, make a free account and hit "create map" in the user control center.

答:
You can do it like this using on():

$(document).ready( function() {
   $(document).on("change", "select", function() {
      let img = $(this).find("option:selected").attr("data-img-src");
      $("#preview").empty().append("<image src=" + img + "/>");
   });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#preview {
  display:inline-block;
  position:absolute;
  margin-left:20px;
}</code>```

<select id="shapeIcon" class="image-picker">
  <optgroup label="Cats">
    <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
    <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
    <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
    <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
  </optgroup>
  <optgroup label="Animals">
    <option data-img-src="http://lorempixel.com/220/200/animals/" value="5">Animal 1</option>
    <option data-img-src="http://lorempixel.com/180/200/animals/" value="6">Animal 2</option>
    <option data-img-src="http://lorempixel.com/130/200/animals/" value="7">Animal 3</option>
    <option data-img-src="http://lorempixel.com/270/200/animals/" value="8">Animal 4</option>
  </optgroup>
</select>

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

<p>Update: As mentioned in the comments, this lead to problems if there is another <code><select></code> on the same page. This issue can be solved by target the <code><select></code> by its <code>id</code> in the <code>change</code> event instead of binding the function to all selects. In addition, the preview should already display an image on pageload. This can be done by setting the first option as <code>selected</code> and call <code>change()</code>.</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>$(document).ready(function() {
  $(document).on("change", "#shapeIcon", function() {
    let img = $(this).find("option:selected").attr("data-img-src");
    $("#preview").empty().append("<image src=" + img + "/>");
  });

  $("#shapeIcon optgroup option:first").attr("selected", "selected");
  $("#shapeIcon").change();
});</code>```

#preview {
  display:inline-block;
  position:absolute;
  margin-left:20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="shapeIcon" class="image-picker">
  <optgroup label="Cats">
    <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
    <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
    <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
    <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
  </optgroup>
  <optgroup label="Animals">
    <option data-img-src="http://lorempixel.com/220/200/animals/" value="5">Animal 1</option>
    <option data-img-src="http://lorempixel.com/180/200/animals/" value="6">Animal 2</option>
    <option data-img-src="http://lorempixel.com/130/200/animals/" value="7">Animal 3</option>
    <option data-img-src="http://lorempixel.com/270/200/animals/" value="8">Animal 4</option>
  </optgroup>
</select>
<div id="preview">

</div></code>```

Body:
tl;dr

I have a dropdown list with the names of png symbols and would like to present a live preview of what the image looks like next to the dropdown before the user hits 'submit'.

More detailed information:

I have a leaflet.js map where the user can place markers. When the user does, a popup opens where a symbol for the marker can be choosen. This is where the dropdown menu sits and of course it would be nice to have a preview of the symbol. Especially as there are quite a few.

Initially I wanted to have an emoji-picker-style menu with different tabs for different categories of symbols. Alas, I hardly managed to find any libraries/code snippets as I do not want to insert unicode smileys but png symbols. What I did find was the onesignal emoji-picker and the jquery.emojiarea plugin. But I failed to get them to work. Most likely because I'm a javascript beginner.

Then I tried to fall back to rveras image-picker for a simpler but hopefully easier to implement way, but also failed at getting it to work.

Now I think, maybe the is a simple, pure jquery way of doing just a preview of the png next to a dropdown?

So you see, my question is actually three-fold:

Does anyone know a tutorial for dummies on how to get a emoji-picker
style menu to work with png symbols? Or...

Can anyone show how to get the image-picker to work? Or ..

Can you tell me how I do this with vanilla jquery or javascript?

A problem might be that I'm operating within a leaflet popup that only allows html as content, so my code looks something like this:

 map.on('draw:created', function (event) {
      layer = event.layer,
          feature = layer.feature = layer.feature || {};        // Intialize layer.feature
          feature.type = feature.type || "Feature";             // Intialize feature.type
      props = feature.properties = feature.properties || {};    // Intialize feature.properties
      props.name = "my name";
      props.description = "my content";
      props.icon = "my icon";
      //picker()              //execute image picker
      var editablePopup = L.popup();
      var content = //Textfield for the marker name
                    'Enter the name
<input id="shapeName" type="text"/>

' +
                    //Dropdown to choose the icon
                    'Choose an icon
'+
                    '<select id="shapeIcon" class="image-picker">'+
                    '<optgroup label="Cats">'+
                      '<option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>'+
                      '<option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>'+
                      '<option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>'+
                      '<option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>'+
                    '</optgroup>'+
                    '<optgroup label="Animals">'+
                      '<option data-img-src="http://lorempixel.com/220/200/animals/" value="5">Animal 1</option>'+
                      '<option data-img-src="http://lorempixel.com/180/200/animals/" value="6">Animal 2</option>'+
                      '<option data-img-src="http://lorempixel.com/130/200/animals/" value="7">Animal 3</option>'+
                      '<option data-img-src="http://lorempixel.com/270/200/animals/" value="8">Animal 4</option>'+
                    '</optgroup></select>
'+
                    //Textarea (flexible in size as opposed to textfield) for the general description
                    'Enter a description
<textarea id="shapeDesc" cols="25" rows="5"></textarea>

'+
                    //Save Button that call the saveIdIW functions
                    '<input type="button" id="okBtn" value="Save" onclick="saveIdIW()"/>';
      editablePopup.setContent(content);
      editablePopup.setLatLng(layer.getLatLng());
      editablePopup.openOn(map);
      drawnItems.addLayer(layer);
    })

If you want to see the whole code of the leaflet map, where I try this, see here. Warning! It's likely quite messy...

PS: if you want to see the problem in action, go to fictionalmaps.com, make a free account and hit "create map" in the user control center.

Body:
You can do it like this using on():

$(document).ready( function() {
   $(document).on("change", "select", function() {
      let img = $(this).find("option:selected").attr("data-img-src");
      $("#preview").empty().append("<image src=" + img + "/>");
   });
});

#preview {
  display:inline-block;
  position:absolute;
  margin-left:20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="shapeIcon" class="image-picker">
  <optgroup label="Cats">
    <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
    <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
    <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
    <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
  </optgroup>
  <optgroup label="Animals">
    <option data-img-src="http://lorempixel.com/220/200/animals/" value="5">Animal 1</option>
    <option data-img-src="http://lorempixel.com/180/200/animals/" value="6">Animal 2</option>
    <option data-img-src="http://lorempixel.com/130/200/animals/" value="7">Animal 3</option>
    <option data-img-src="http://lorempixel.com/270/200/animals/" value="8">Animal 4</option>
  </optgroup>
</select>
<div id="preview">

</div>

Update: As mentioned in the comments, this lead to problems if there is another <select> on the same page. This issue can be solved by target the <select> by its id in the change event instead of binding the function to all selects. In addition, the preview should already display an image on pageload. This can be done by setting the first option as selected and call change().

$(document).ready(function() {
  $(document).on("change", "#shapeIcon", function() {
    let img = $(this).find("option:selected").attr("data-img-src");
    $("#preview").empty().append("<image src=" + img + "/>");
  });

  $("#shapeIcon optgroup option:first").attr("selected", "selected");
  $("#shapeIcon").change();
});

#preview {
  display:inline-block;
  position:absolute;
  margin-left:20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="shapeIcon" class="image-picker">
  <optgroup label="Cats">
    <option data-img-src="http://placekitten.com/220/200" value="1">Cute Kitten 1</option>
    <option data-img-src="http://placekitten.com/180/200" value="2">Cute Kitten 2</option>
    <option data-img-src="http://placekitten.com/130/200" value="3">Cute Kitten 3</option>
    <option data-img-src="http://placekitten.com/270/200" value="4">Cute Kitten 4</option>
  </optgroup>
  <optgroup label="Animals">
    <option data-img-src="http://lorempixel.com/220/200/animals/" value="5">Animal 1</option>
    <option data-img-src="http://lorempixel.com/180/200/animals/" value="6">Animal 2</option>
    <option data-img-src="http://lorempixel.com/130/200/animals/" value="7">Animal 3</option>
    <option data-img-src="http://lorempixel.com/270/200/animals/" value="8">Animal 4</option>
  </optgroup>
</select>
<div id="preview">

</div>


问:
how to use for loop for multiple inputs
This is my code where I want to apply the for loop to check the best values result.   I want to apply the for loop for num_ants = 1000 , so I want to test the best values for the values 500,600, 700, 800,900  and like this for other inputs.</p>

```<code> num_ants = int(input("Please enter the number of ants (1000 recommended): "))
    if num_ants <= 0:
        quit("value entered for number of ants is non-positive")

min_cases_per_rule = int(input("Please enter the minimum number of cases per rule (10 recommended): "))
if min_cases_per_rule <= 0:
    quit("value entered for minimum number of cases per rule is non-positive")

max_uncovered_cases = int(input("Please enter the maximum number of uncovered cases in the training set (10 recommended): "))
if max_uncovered_cases < 0:
    quit("value entered for maximum number of uncovered cases is non-zero")

num_rules_converge = int(input("Please enter the number of rules used to test convergence of the ants (40 recommended): ")) #10
if num_rules_converge <= 0:
    quit("value entered for number of rules used to test convergence of the ants is non-positive")
</code>```

答:
```<code>while True:

        num_ants = int(input("Please enter the number of ants (1000 recommended): "))
        if num_ants <= 0:
            quit("value entered for number of ants is non-positive")

        min_cases_per_rule = int(input("Please enter the minimum number of cases per rule (10 recommended): "))
        if min_cases_per_rule <= 0:
            quit("value entered for minimum number of cases per rule is non-positive")

        max_uncovered_cases = int(input("Please enter the maximum number of uncovered cases in the training set (10 recommended): "))
        if max_uncovered_cases < 0:
            quit("value entered for maximum number of uncovered cases is non-zero")

        num_rules_converge = int(input("Please enter the number of rules used to test convergence of the ants (40 recommended): ")) #10
        if num_rules_converge <= 0:
            quit("value entered for number of rules used to test convergence of the ants is non-positive")

        # do your calculations and give results

        keep_going = input('Try another set of parameters? Type "no" to exit.')
        if keep_going == "no":
            break
</code>```

Title: how to use for loop for multiple inputs

Body:
This is my code where I want to apply the for loop to check the best values result.   I want to apply the for loop for num_ants = 1000 , so I want to test the best values for the values 500,600, 700, 800,900  and like this for other inputs.

 num_ants = int(input("Please enter the number of ants (1000 recommended): "))
    if num_ants <= 0:
        quit("value entered for number of ants is non-positive")

min_cases_per_rule = int(input("Please enter the minimum number of cases per rule (10 recommended): "))
if min_cases_per_rule <= 0:
    quit("value entered for minimum number of cases per rule is non-positive")

max_uncovered_cases = int(input("Please enter the maximum number of uncovered cases in the training set (10 recommended): "))
if max_uncovered_cases < 0:
    quit("value entered for maximum number of uncovered cases is non-zero")

num_rules_converge = int(input("Please enter the number of rules used to test convergence of the ants (40 recommended): ")) #10
if num_rules_converge <= 0:
    quit("value entered for number of rules used to test convergence of the ants is non-positive")


问:
Unable to get the first bar to show up in python matplotlib
For some reason my plot at 50 is not showing up and I can't figure out why. any help would be much appreciated.

```<code>import matplotlib.pyplot as plt
num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")
plt.show()
</code>```

答:
```<code>num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob, width=3)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")
plt.show()
</code>```

For some reason the width of the chart is problematic. Change it and it will be fine. Also it's will be more clear that way. It is an argument of the bar chart.

Body:
For some reason my plot at 50 is not showing up and I can't figure out why. any help would be much appreciated.

import matplotlib.pyplot as plt
num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")
plt.show()

Body:
num = [50, 100, 150, 300, 400]
prob = [0.08, .03, .013,.0033,0]
plt.bar(num,prob, width=3)
plt.xlabel("Number of Flaws")
plt.ylabel ("probability")
plt.show()

For some reason the width of the chart is problematic. Change it and it will be fine. Also it's will be more clear that way. It is an argument of the bar chart.


问:
Invalid signature when trying to upload to Cloudinary
Using the Node integration provided by cloudinary_npm, I'm getting the following message back when I try to upload:

```<code>{ error: { message: 'Invalid Signature t7233823748278473838erfndsjy8234. String to sign - \'timestamp=1439054775\'.', http_code: 401 } }
</code>```

I retrieve then pass my image to the backend like this:

```<code>$scope.previewFile = function() {
   var file  = document.querySelector('input[type=file]').files[0];
   var reader  = new FileReader();

   if (file) {
     reader.readAsDataURL(file);
   } else {
     preview.src = "";
   }

   reader.onloadend = function () {
     base64img = reader.result;
     preview.src = base64img;
     console.log(base64img);
   };
};

 $scope.submitPic = function() {
    $http.post('http://localhost:3000/story/pic', {img: base64img})
    .success(function(data){
      preview.src = "";
    })
    .error(function(err){
      console.log(err);
    });
  };
</code>```

Then in the back, I have the following configuration and routes, both straight from the docs:

```<code>var cloudinary = require("cloudinary");
var CLOUD_API_SECRET = require("../constants.js");

cloudinary.config({
  cloud_name: 'some_cloud',
  api_key: '63789865675995',
  api_secret: CLOUD_API_SECRET
});

router.post('/pic', function(req, res, next) {
  var img = req.body.img;
  cloudinary.uploader.upload(img, function(result) {
  });

  res.status(200).send('ok');
});
</code>```

Does anyone recognize what I might be doing wrong? I've been troubleshooting this for hours. I'm at a dead end.

答:
make sure you have placed your cloudinary secret inside a ''(quote/inverted comma).make sure the resulting statement should mean :

var CLOUD_API_SECRET ='some_cloudinary_secret_xxx';

check this value in the js file from where you are fetching this value.

Body:
Using the Node integration provided by cloudinary_npm, I'm getting the following message back when I try to upload:

{ error: { message: 'Invalid Signature t7233823748278473838erfndsjy8234. String to sign - \'timestamp=1439054775\'.', http_code: 401 } }

I retrieve then pass my image to the backend like this:

$scope.previewFile = function() {
   var file  = document.querySelector('input[type=file]').files[0];
   var reader  = new FileReader();

   if (file) {
     reader.readAsDataURL(file);
   } else {
     preview.src = "";
   }

   reader.onloadend = function () {
     base64img = reader.result;
     preview.src = base64img;
     console.log(base64img);
   };
};

 $scope.submitPic = function() {
    $http.post('http://localhost:3000/story/pic', {img: base64img})
    .success(function(data){
      preview.src = "";
    })
    .error(function(err){
      console.log(err);
    });
  };

Then in the back, I have the following configuration and routes, both straight from the docs:

var cloudinary = require("cloudinary");
var CLOUD_API_SECRET = require("../constants.js");

cloudinary.config({
  cloud_name: 'some_cloud',
  api_key: '63789865675995',
  api_secret: CLOUD_API_SECRET
});

router.post('/pic', function(req, res, next) {
  var img = req.body.img;
  cloudinary.uploader.upload(img, function(result) {
  });

  res.status(200).send('ok');
});

Does anyone recognize what I might be doing wrong? I've been troubleshooting this for hours. I'm at a dead end.


问:
How to generate large word count file in Spark?
I want to generate 10 million lines’ wordcount file for performance test(each line has the same sentence). But I have no idea about how to code it.

You can give me an example code, and save file in HDFS directly.

答:
You can try something like this.

Generate 1 column with values from 1 to 100k and one with values from 1 to 100 explode both of them with explode(column).
You can't generate one column with 10 Mil values because kryo buffer is gonna throw an error.

I don't know if this is the best performance way to do it, but it is the fastest way I can think right now.

```<code>val generateList = udf((s: Int) => {
    val buf = scala.collection.mutable.ArrayBuffer.empty[Int]
    for(i <- 1 to s) {
        buf += i
    }
    buf
})

val someDF = Seq(
  ("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
).toDF("sentence")

val someDfWithMilColumn = someDF.withColumn("genColumn1", generateList(lit(100000)))
   .withColumn("genColumn2", generateList(lit(100)))
val someDfWithMilColumn100k  = someDfWithMilColumn
   .withColumn("expl_val", explode($"mil")).drop("expl_val", "genColumn1")
val someDfWithMilColumn10mil = someDfWithMilColumn100k
   .withColumn("expl_val2", explode($"10")).drop("genColumn2", "expl_val2")

someDfWithMilColumn10mil.write.parquet(path)
</code>```

Body:
You can try something like this.

Generate 1 column with values from 1 to 100k and one with values from 1 to 100 explode both of them with explode(column).
You can't generate one column with 10 Mil values because kryo buffer is gonna throw an error.

I don't know if this is the best performance way to do it, but it is the fastest way I can think right now.

val generateList = udf((s: Int) => {
    val buf = scala.collection.mutable.ArrayBuffer.empty[Int]
    for(i <- 1 to s) {
        buf += i
    }
    buf
})

val someDF = Seq(
  ("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
).toDF("sentence")

val someDfWithMilColumn = someDF.withColumn("genColumn1", generateList(lit(100000)))
   .withColumn("genColumn2", generateList(lit(100)))
val someDfWithMilColumn100k  = someDfWithMilColumn
   .withColumn("expl_val", explode($"mil")).drop("expl_val", "genColumn1")
val someDfWithMilColumn10mil = someDfWithMilColumn100k
   .withColumn("expl_val2", explode($"10")).drop("genColumn2", "expl_val2")

someDfWithMilColumn10mil.write.parquet(path)


问:
Define a function that will take in a list of lengths from a shape and return the coordinates of each point
I am trying to define a function that will take in a list of lengths from a shape like this:

And return the coordinates of each point.

Here is what have so far:

```<code>def cord(lst):
    lst2 = [[0,0]]
    d = 'up'
    c = [0,0]
    for n in lst:
        if d == 'up': # if the direction is up, we add the value to the y cor
            c[1] += n
            lst2.append(c)
            d = 'right' # After up, we go right

        else: # if the direction is right, we add the value to the x cor
            c[0] += n
            lst2.append(c)
            d = 'up' # After right, we go up

    print(lst2)

cord([10,10,10])
</code>```

Output:

```<code>[[0, 0], [10, 20], [10, 20], [10, 20]]
</code>```

Desired output:

```<code>[[0, 0], [0, 10], [10, 10], [10, 20]]
</code>```

Can you tell me what's wrong?

答:
Since lists are mutable and your variable c is a list, you need to append a copy of c so that it will not affect others when you change it. Do:

```<code>lst2.append(c.copy())
</code>```

Body:
I am trying to define a function that will take in a list of lengths from a shape like this:

And return the coordinates of each point.

Here is what have so far:

def cord(lst):
    lst2 = [[0,0]]
    d = 'up'
    c = [0,0]
    for n in lst:
        if d == 'up': # if the direction is up, we add the value to the y cor
            c[1] += n
            lst2.append(c)
            d = 'right' # After up, we go right

        else: # if the direction is right, we add the value to the x cor
            c[0] += n
            lst2.append(c)
            d = 'up' # After right, we go up

    print(lst2)

cord([10,10,10])

Output:

[[0, 0], [10, 20], [10, 20], [10, 20]]

Desired output:

[[0, 0], [0, 10], [10, 10], [10, 20]]

Can you tell me what's wrong?

Body:
Since lists are mutable and your variable c is a list, you need to append a copy of c so that it will not affect others when you change it. Do:

lst2.append(c.copy())


问:
getSelection with multiple occurrence of text replaces first occurrence not the correct selection
I am having a hard time selecting text and replacing that selection when there are multiple occurrences. It always reverts to the first occurrence and replaces it.

Here is the scripting I am using and if the selection only appears once I am prefect. When it appears more than once it grabs the first.

```<code>var self=$('#textarea');
GetSelected={};
GetSelected=function(){
    var txt='';
    if(window.getSelection){
        txt=window.getSelection();
    }
    else if(document.getSelection){
        txt=document.getSelection();
    }
    else if(document.selection){
        txt=document.selection.createRange().text;
    }
    return txt;
}

self.html(self.html().replace(selection, '<b>' + selection + '</b>'));
</code>```

Is there something I am missing, that know which selection to replace?

答:
The main problem here is that treating HTML as a string and replacing parts of it as your are doing is a very fragile approach (think of a matching piece of text where part of it is already bold, or an attribute value that contains match the selected text, for example). Instead, you could use built-in browser behaviour to find matching text. Here is the function from that question adapted for your case:

```<code>function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);

        while (window.find(text)) {
            document.execCommand("Bold", false, null);
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("Bold", false, null);
            textRange.collapse(false);
        }
    }
}
</code>```

Also, the GetSelected function is incorrect (although it coincidentally does work in this case) in that it returns a string in IE < 9 and a Selection object in other browsers. You also haven't declared the GetSelected variable. Here's a simpler and better replacement:

```<code>function GetSelected() {
    var txt = ""
    if (window.getSelection) {
        txt = window.getSelection().toString();
    } else if (document.selection && document.selection.type == "Text") {
        txt = document.selection.createRange().text;
    }
    return txt;
}
</code>```

Note that you don't need this function at all if you use my suggested approach.

Body:
I am having a hard time selecting text and replacing that selection when there are multiple occurrences. It always reverts to the first occurrence and replaces it.

Here is the scripting I am using and if the selection only appears once I am prefect. When it appears more than once it grabs the first.

var self=$('#textarea');
GetSelected={};
GetSelected=function(){
    var txt='';
    if(window.getSelection){
        txt=window.getSelection();
    }
    else if(document.getSelection){
        txt=document.getSelection();
    }
    else if(document.selection){
        txt=document.selection.createRange().text;
    }
    return txt;
}

self.html(self.html().replace(selection, '' + selection + ''));

Is there something I am missing, that know which selection to replace?

Body:
The main problem here is that treating HTML as a string and replacing parts of it as your are doing is a very fragile approach (think of a matching piece of text where part of it is already bold, or an attribute value that contains match the selected text, for example). Instead, you could use built-in browser behaviour to find matching text. Here is the function from that question adapted for your case:

function doSearch(text) {
    if (window.find && window.getSelection) {
        document.designMode = "on";
        var sel = window.getSelection();
        sel.collapse(document.body, 0);

        while (window.find(text)) {
            document.execCommand("Bold", false, null);
            sel.collapseToEnd();
        }
        document.designMode = "off";
    } else if (document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        while (textRange.findText(text)) {
            textRange.execCommand("Bold", false, null);
            textRange.collapse(false);
        }
    }
}

Also, the GetSelected function is incorrect (although it coincidentally does work in this case) in that it returns a string in IE < 9 and a Selection object in other browsers. You also haven't declared the GetSelected variable. Here's a simpler and better replacement:

function GetSelected() {
    var txt = ""
    if (window.getSelection) {
        txt = window.getSelection().toString();
    } else if (document.selection && document.selection.type == "Text") {
        txt = document.selection.createRange().text;
    }
    return txt;
}

Note that you don't need this function at all if you use my suggested approach.


问:
Modifying list of related objects asynchronously yields unexpected results
I have a list of objects which can have one or more relationships to one another. I'd like to run through this list and compare each object to all other objects in the list, setting the relationships as I compare the objects. Because this comparison in real life is fairly complex and time consuming I'm trying to do this asynchronously.

I've quickly put together some sample code which illustrates the issue at hand in a fairly simple fashion.

```<code>class Program
    {
        private static readonly Word[] _words =
        {
            new Word("Beef"),
            new Word("Bull"),
            new Word("Space")
        };

        static void Main()
        {
            var tasks = new List<Task>();

            foreach (var word in _words)
            {
                tasks.Add(CheckRelationShipsAsnc(word));
            }

            Task.WhenAll(tasks);
        }

        static async Task CheckRelationShipsAsnc(Word leftWord)
        {
            await Task.Run(() =>
            {
                foreach (var rightWord in _words)
                {
                    if(leftWord.Text.First() == rightWord.Text.First())
                    {
                        leftWord.RelationShips.Add(rightWord);
                    }
                }
            });
        }
    }

    class Word
    {
        public string Text { get; }
        public List<Word> RelationShips { get; } = new List<Word>();

        public Word(string text)
        {
            if(string.IsNullOrEmpty(text)) throw new ArgumentException();
            Text = text;
        }

        public override string ToString()
        {
            return $"{Text} ({RelationShips.Count} relationships)";
        }
    }
</code>```

The expected result would be that "Space" has no relationships whereas the words "Bull" and "Beef" have one relationship to one another. What I get is all words have no relationsships at all. I'm having trouble understanding what exactly the problem is.

答:
Your algorithm has an O(n^2) time complexity. This is a problem if you have a great number of items to compare against each other. E.g., if you have 1000 items, this gives you 1000 * 1000 = 1000000 (one million) comparisons.

Consider using another approach. I don't know if this is applicable to your real problem, but for this example, assuming that each word starts with a capital letter A..Z, you could store the related words by first letter in an array of length 26 of word lists.

```<code>var a = new List<Word>[26];

// Initialize array with empty lists
for (int i = 0; i < a.Length; i++) {
    a[i] = new List<Word>();
}

// Fill array with related words
foreach (var word in _words) {
    a[word.Text[0] - 'A'].Add(word); // Subtracting 'A' yields a zero-based index.
}
</code>```

Note that your original solution has two nested loops (where one is hidden inside the call of CheckRelationShipsAsnc). This solution has only one level of loops and has a time complexity of O(n) up to here.

Now you find all related words in one list at the corresponding array positions. Taking this information, you can now wire up the words being in the same list. This part is still O(n^2); however, here n is much smaller, because is refers only to words being in the lists that are related, but not the length of the initial _words array.

Depending on how your real problem is formulated, it may be better to use a Dictionary<char, List<Word>> in place of the my array a. The array solution requires an index. In a real world problem, the relation condition may not be formulateable as an index. The dictionary requires a key and any kind of object can be used as key. See: Remarks section of Dictionary<TKey,TValue> Class.

An algorithm optimized in this way may be even faster than a multitaskting solution.

Body:
I have a list of objects which can have one or more relationships to one another. I'd like to run through this list and compare each object to all other objects in the list, setting the relationships as I compare the objects. Because this comparison in real life is fairly complex and time consuming I'm trying to do this asynchronously.

I've quickly put together some sample code which illustrates the issue at hand in a fairly simple fashion.

class Program
    {
        private static readonly Word[] _words =
        {
            new Word("Beef"),
            new Word("Bull"),
            new Word("Space")
        };

        static void Main()
        {
            var tasks = new List<Task>();

            foreach (var word in _words)
            {
                tasks.Add(CheckRelationShipsAsnc(word));
            }

            Task.WhenAll(tasks);
        }

        static async Task CheckRelationShipsAsnc(Word leftWord)
        {
            await Task.Run(() =>
            {
                foreach (var rightWord in _words)
                {
                    if(leftWord.Text.First() == rightWord.Text.First())
                    {
                        leftWord.RelationShips.Add(rightWord);
                    }
                }
            });
        }
    }

    class Word
    {
        public string Text { get; }
        public List<Word> RelationShips { get; } = new List<Word>();

        public Word(string text)
        {
            if(string.IsNullOrEmpty(text)) throw new ArgumentException();
            Text = text;
        }

        public override string ToString()
        {
            return $"{Text} ({RelationShips.Count} relationships)";
        }
    }

The expected result would be that "Space" has no relationships whereas the words "Bull" and "Beef" have one relationship to one another. What I get is all words have no relationsships at all. I'm having trouble understanding what exactly the problem is.

Body:
Your algorithm has an O(n^2) time complexity. This is a problem if you have a great number of items to compare against each other. E.g., if you have 1000 items, this gives you 1000 * 1000 = 1000000 (one million) comparisons.

Consider using another approach. I don't know if this is applicable to your real problem, but for this example, assuming that each word starts with a capital letter A..Z, you could store the related words by first letter in an array of length 26 of word lists.

var a = new List<Word>[26];

// Initialize array with empty lists
for (int i = 0; i < a.Length; i++) {
    a[i] = new List<Word>();
}

// Fill array with related words
foreach (var word in _words) {
    a[word.Text[0] - 'A'].Add(word); // Subtracting 'A' yields a zero-based index.
}

Note that your original solution has two nested loops (where one is hidden inside the call of CheckRelationShipsAsnc). This solution has only one level of loops and has a time complexity of O(n) up to here.

Now you find all related words in one list at the corresponding array positions. Taking this information, you can now wire up the words being in the same list. This part is still O(n^2); however, here n is much smaller, because is refers only to words being in the lists that are related, but not the length of the initial _words array.

Depending on how your real problem is formulated, it may be better to use a Dictionary<char, List<Word>> in place of the my array a. The array solution requires an index. In a real world problem, the relation condition may not be formulateable as an index. The dictionary requires a key and any kind of object can be used as key. See: Remarks section of Dictionary<TKey,TValue> Class.

An algorithm optimized in this way may be even faster than a multitaskting solution.


问:
Need suggestion for adding video conference (specially classroom / educational) in MERN stack app
I have created a web app using React, Node. I want to enable video conferencing in the app and have already integrated it with Agora and also tried others.
I have also tried using core WebRTC but nothing works so perfectly.
Agora is working fine but its UI is not customizable.
Can someone please suggest me the best option to do so.</p>

答:
A good solution for customization would be Mediasoup. This allows you to make an SFU and completely customize the framework to your needs. It is free and you only need to pay for your own server you deploy it on.

Here is an EXAMPLE PROJECT showing simple multi-user video conferencing with audio/video/screen sharing.

Another option would be the Janus Gateway. Haven't used it yet, but has a prebuilt backend for video/audio conferencing ready for deployment. You can then also customize the UI to your needs.


问:
How to Add a "Go Back" Toggle
I have a code where it allows me to go to new text if I press "next" but I also want to create another button where it would allow me to go back to the previous text I was reading.

I know I just write Previous but I don't know the javascript to go back.

$(function() {

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      1) Info here

       2) Info Here

       3) Info Here

       4) Info Here

       5) Info Here

Next```

答:
Use this, works like a charm.

// Next

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });

// Previous

$('#previous_button').click(function()  {

  if ($('.active').prev().hasClass('hidemsg')) {

     $('.active').prev('div').addClass('active').end().removeClass('active');

  } else {

    alert('Sorry, there is no previous entry');

  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      1) Info here

       2) Info Here

       3) Info Here

       4) Info Here

       5) Info Here

Next
Previous```

Title: How to Add a "Go Back" Toggle

Body:
I have a code where it allows me to go to new text if I press "next" but I also want to create another button where it would allow me to go back to the previous text I was reading.

I know I just write Previous but I don't know the javascript to go back.

$(function() {

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });
});

.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }

<!DOCTYPE html>

  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

      1) Info here

       2) Info Here

       3) Info Here

       4) Info Here

       5) Info Here

Next

Body:
Use this, works like a charm.

// Next

    $('.js-button').click(function() {
      if ($('div.active').next().hasClass('hidemsg')) {
        $('div.active').next('div').addClass('active').end().removeClass('active');
      }else{
        alert('Sorry, there is no next entry');
      }
    });

// Previous

$('#previous_button').click(function()  {

  if ($('.active').prev().hasClass('hidemsg')) {

     $('.active').prev('div').addClass('active').end().removeClass('active');

  } else {

    alert('Sorry, there is no previous entry');

  }

});

.hidemsg {
 display: none;
  }

  .hidemsg.active {
 display: block;
  }

<!DOCTYPE html>
<html lang="en" class="no-js.june">
 <head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>
<div id="msg1" class="hidemsg active">
   <p class="content__item-copy-text">
      1) Info here
      </p>
</div>

<div id="msg2" class="hidemsg">
      <p class="content__item-copy-text">
       2) Info Here </p>
</div>

<div id="msg3" class="hidemsg">
  <p class="content__item-copy-text">
       3) Info Here </p>
</div>

<div id="msg4" class="hidemsg">
  <p class="content__item-copy-text">
       4) Info Here </p>
</div>

    <div id="msg5" class="hidemsg">
   <p class="content__item-copy-text">
       5) Info Here </p>
</div>
<a href="#" type="button" class="btn btn-default js-button">Next</a>
<a href="#" type="button" class="btn btn-default" id="previous_button">Previous</a>


问:
Enable hover for touch/click on mobile
Everything works the way it should on desktop view but the DIV which shows on hover in desktop doesn't show in mobile view. I want to show that DIV on touch/click in mobile/tablet.

As per some suggestions, I tried with :active after :hover too but that doesn't work.

I don't mind JS or jQuery answers too.

DEMO: https://jsfiddle.net/ovg6xzhu/

HTML:

```<code><div class="hoverEffect hoverEffect-first">
  <img src="https://via.placeholder.com/150" />
  <div class="mask">
    <h2>Web Services!</h2>
    <p>We are going to build another sets of css hover image effects with CSS3 animations.<br /><a href="#">View All</a></p>
  </div>
</div>
</code>```

CSS:

```<code>.hoverEffect {
  width: 100%;
  float: left;
  overflow: hidden;
  position: relative;
  text-align: center;
  cursor: default;
  border-radius: 2px;
  margin-bottom: 30px;
}
.hoverEffect .mask {
  width: 100%;
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0
}
.hoverEffect img {
  display: block;
  position: relative
}
.hoverEffect h2 {
  text-transform: uppercase;
  color: #fff;
  text-align: center;
  position: relative;
  padding: 10px;
  margin: 20px 0 0 0
}
.hoverEffect p {
  position: relative;
  color: #fff;
  padding: 0px 20px 20px;
  text-align: center
}
.hoverEffect-first img {
  transition: all 0.2s linear;
  width:100%;
  height:auto;
}
.hoverEffect-first .mask {
  opacity: 0;
  background-color: rgba(61, 90, 128, 0.95);
  transition: all 0.4s ease-in-out;
  width: 100%;
  height: 100%;
}
.hoverEffect-first h2 {
  margin: 10px 40px;
  transform: translateY(-100px);
  opacity: 0;
  transition: all 0.2s ease-in-out;
}
.hoverEffect-first p {
  transform: translateY(100px);
  opacity: 0;
  transition: all 0.2s linear;
}
.hoverEffect-first:hover img, .hoverEffect-first:active img {
  transform: scale(1.1);
}
.hoverEffect-first:hover .mask, .hoverEffect-first:active .mask {
  opacity: 1;
}
.hoverEffect-first:hover h2,
.hoverEffect-first:hover p,
.hoverEffect-first:active h2,
.hoverEffect-first:active p {
  opacity: 1;
  transform: translateY(0px);
}
.hoverEffect-first:hover p, .hoverEffect-first:active p {
  transition-delay: 0.1s;
}
.hoverEffect-first:hover a.info, .hoverEffect-first:active a.info {
  transition-delay: 0.2s;
}
</code>```

答: You dont need js for this purpose: css should be enough, and active should do the job, The code you posted is working fine - maybe u had a cache problem. That being said its not the best experience for mobile users, you should not emulate hover effects on mobile, users wont expect they need to click ( and then they are expected to click on another element to make the effect go away).</p>

Title: Enable hover for touch/click on mobile

Body:
Everything works the way it should on desktop view but the DIV which shows on hover in desktop doesn't show in mobile view. I want to show that DIV on touch/click in mobile/tablet.

As per some suggestions, I tried with :active after :hover too but that doesn't work.

I don't mind JS or jQuery answers too.

DEMO: https://jsfiddle.net/ovg6xzhu/

HTML:

Web Services!

We are going to build another sets of css hover image effects with CSS3 animations.
View All

CSS:

.hoverEffect {
  width: 100%;
  float: left;
  overflow: hidden;
  position: relative;
  text-align: center;
  cursor: default;
  border-radius: 2px;
  margin-bottom: 30px;
}
.hoverEffect .mask {
  width: 100%;
  position: absolute;
  overflow: hidden;
  top: 0;
  left: 0
}
.hoverEffect img {
  display: block;
  position: relative
}
.hoverEffect h2 {
  text-transform: uppercase;
  color: #fff;
  text-align: center;
  position: relative;
  padding: 10px;
  margin: 20px 0 0 0
}
.hoverEffect p {
  position: relative;
  color: #fff;
  padding: 0px 20px 20px;
  text-align: center
}
.hoverEffect-first img {
  transition: all 0.2s linear;
  width:100%;
  height:auto;
}
.hoverEffect-first .mask {
  opacity: 0;
  background-color: rgba(61, 90, 128, 0.95);
  transition: all 0.4s ease-in-out;
  width: 100%;
  height: 100%;
}
.hoverEffect-first h2 {
  margin: 10px 40px;
  transform: translateY(-100px);
  opacity: 0;
  transition: all 0.2s ease-in-out;
}
.hoverEffect-first p {
  transform: translateY(100px);
  opacity: 0;
  transition: all 0.2s linear;
}
.hoverEffect-first:hover img, .hoverEffect-first:active img {
  transform: scale(1.1);
}
.hoverEffect-first:hover .mask, .hoverEffect-first:active .mask {
  opacity: 1;
}
.hoverEffect-first:hover h2,
.hoverEffect-first:hover p,
.hoverEffect-first:active h2,
.hoverEffect-first:active p {
  opacity: 1;
  transform: translateY(0px);
}
.hoverEffect-first:hover p, .hoverEffect-first:active p {
  transition-delay: 0.1s;
}
.hoverEffect-first:hover a.info, .hoverEffect-first:active a.info {
  transition-delay: 0.2s;
}


问:
Tips on designing a one-point-of-contact class
I am working on a software[runs on a public computer] which helps to create pdf files from word files. User have plethora of options for payment and specifying the properties of the final pdf output. Program now manages this situation using global variables.

I need to develop a user interaction object/class that will store information of every user activity in the program so that at the time of generation of output I’ve only one place to find all information. I will also record the path user selected to reach a particular point,errors happened,time spent,etc.  An interaction/recording  starts when user clicks on the  button by storing the name of the button clicked  and ends when the pdf is generated and money has debited from his account[Will store the amount debited,total pages converted,etc].  Eventually I may serialize this object.

I am contemplating about decorator pattern for implementing this module. Am I on the right path? Is there any better pattern/approach for this?

Thanks for the attention.

答: If the "user activity" is considered as set of methods he invokes so it looks like Command pattern here. Moveover you can add to the Command class a serialization mechanism and logging functionality.</p>


问:
Django template query for loop render taking too much time
I have a related query of limit 10 of an object. It's taking over 9s to load the whole page in development mode. When I'm not running the related query for loop on template, it only takes 1s to load. I'm quite confused what's going on in here! Please help me identify the problem/what I'm doing wrong here! Thanks in advance!

Here' my view file code -

```<code>related = News.objects.filter(
            is_active=True,
            status='public',
            language=request.LANGUAGE_CODE,
            category=news.category
        ).order_by('-published_at')[:10]
</code>```

And here's the loop on template file -

```<code>{% for r in related %}
    <li class="row mb-4">
        <a href="{% url 'single_news' r.id %}" class="col-5">
            <img src="{{ r.featured_image.url }}" alt="Image" class="rounded img-fluid">
        </a>
        <div class="col-7">
            <a href="{% url 'single_news' r.id %}" class="no-underline">
                <h6 class="mb-3 h5 text-charcoal">{{ r.heading }}</h6>
            </a>
            <div class="d-flex text-small">
                <span class="text-muted ml-1">{{ r.published_at }}</span>
            </div>
        </div>
    </li>
{% endfor %}
</code>```

Here's the django-debug-ttolbar image of the query time -

答:
How many News objects are there in the db? If you have many of them, and you don't have indexes on the columns you in your underlying where clause or order_by clause, it could take a long time to get those 10 News items. Do you have access to the database directly? I'd try the SQL of that query and see if the query takes a long time:

```<code>SELECT * FROM content_news WHERE is_active=1 AND status='public' AND language='bn' ORDER_BY published_at DESC
</code>```

I notice the query in the screenshot doesn't have the category=news.category clause. Is category a foreign key? If so you may want to use select_related to efficiently retrieve it.

Hope that helps, happy coding!

Body:
I have a related query of limit 10 of an object. It's taking over 9s to load the whole page in development mode. When I'm not running the related query for loop on template, it only takes 1s to load. I'm quite confused what's going on in here! Please help me identify the problem/what I'm doing wrong here! Thanks in advance!

Here' my view file code -

related = News.objects.filter(
            is_active=True,
            status='public',
            language=request.LANGUAGE_CODE,
            category=news.category
        ).order_by('-published_at')[:10]

And here's the loop on template file -

{% for r in related %}

{{ r.heading }}

                {{ r.published_at }}

{% endfor %}

Here's the django-debug-ttolbar image of the query time -

Body:
How many News objects are there in the db? If you have many of them, and you don't have indexes on the columns you in your underlying where clause or order_by clause, it could take a long time to get those 10 News items. Do you have access to the database directly? I'd try the SQL of that query and see if the query takes a long time:

SELECT * FROM content_news WHERE is_active=1 AND status='public' AND language='bn' ORDER_BY published_at DESC

I notice the query in the screenshot doesn't have the category=news.category clause. Is category a foreign key? If so you may want to use select_related to efficiently retrieve it.

Hope that helps, happy coding!