text:
Q: Как правильно сделать обновляемый вывод в консоли? Как нужно сделать вывод в консоль так, чтобы она обновлялась правильно?
У меня есть код:
print(f'Warming up threads... [' + str(len(ips) - i) + ']', end="\r")

Вывод в консоли выглядит так:

Warming up threads... [1200]

Но если будет выведена строка, которая на 1 символ короче предыдущей, то выглядеть это будет так:

Warming up threads... [999]]

Соответственно, если останется запустить только 1 тред, то строка обретёт следующий вид:

Warming up threads... [1]]]]

A: При написании в новой строке консоли каретка уже в начале строки, после написания она будет стоять за последним символом.
Поэтому, добавляя \r мы возвращаем каретку в начало строки и все последующие символы заменяют те, что были в тех же позиция. Чтобы не было артефактов, очищаем строку сдвигая каретку, заполняя пробелами и снова сдвигая каретку
Пример артефакта:

*

*Если вывести сначала строку большей длины, а после меньшей:

*Current value [10254]

*Current value [999]4]
Пример:
import time
import sys

for ips in (10254, 1, 10, 1, 10254, 999):
    sys.stdout.write('\r' + ' ' * 50 + '\r')  # Очищение строки
    sys.stdout.write(f'Current value [{ips}]')
    sys.stdout.flush()

    time.sleep(0.5)

P.S.
В старой версии PyCharm мною был замечен баг, из-за которого не работал перевод каретки \r. Поэтому, лучше проверять и на терминалах в ОС (например cmd в windows)

A: Можно через os.system('cls'). Выйдет
import time
import os

x = 1200

while x:
    os.system('cls')
    print('Warming up threads... [' + str(x) + ']')`


text:
Q: R: Build second order transition matrix and score sequences Other questions
There is another question asking how to build a second order transition matrix, however the answer does not seem to produce a second order transition matrix.
Second order transition matrix & scoring a sequence
Let's use this dataset:
set.seed(1)
dat<-data.frame(replicate(20,sample(c("A", "B", "C","D"), size = 100, replace=TRUE)))

What would be the best way to build a second order transition matrix such that I can easily score a new sequence I encounter as discussed here. For example, such that I can calculate the probability of observing AAABCAD.

Reaction to Julius Vainora
set.seed(1)
mat <-data.frame(replicate(100,sample(c("AAA", "BBB", "CCC","DDD", "ABC", 'ABD'), size = 5, replace=TRUE)))

aux <- apply(mat, 2, function(col) rbind(paste0(head(col, -2), head(col[-1], -1)), col[-1:-2]))
aux <- data.frame(t(matrix(aux, nrow = 2)))
names(aux) <- c("From", "To")
head(aux, 3)
TM <- table(aux)
TM <- TM / rowSums(TM)

x <- as.character(unlist(mat[1,]))
transitions <- cbind(paste0(head(x, -2), head(x[-1], -1)), x[-1:-2])

prAA <- 1 / (4 * 4)
prAA * prod(TM[transitions])

When I ran this code it gave me  a probability of 0, however the sequence for which I calculated the probability was also used to build the transition matrix (namely the first row of the df, here mat). I suppose this should not happen since the sequence was used to build the transition matrix so none of the transitions can be zero right?
Moreover, when I change the mat creation to this line:
mat <-data.frame(replicate(10,sample(c("AAA", "BBB", "CCC","DDD", "ABC", 'ABD'), size = 5, replace=TRUE)))

It will give the error Error in [.default (TM, transitions) : subscript out of bounds

A: Let's start with the data coming in a matrix format:
set.seed(1)
dat <- replicate(20, sample(c("A", "B", "C", "D"), size = 100, replace = TRUE))

As to estimate the second order transition matrix, we extract the following observed transitions:
aux <- apply(dat, 2, function(col) rbind(paste0(head(col, -2), head(col[-1], -1)), col[-1:-2]))
aux <- data.frame(t(matrix(aux, nrow = 2)))
names(aux) <- c("From", "To")
head(aux, 3)
#   From To
# 1   DD  D
# 2   DD  B
# 3   DB  A

The transition matrix then can be estimated with
TM <- table(aux)
(TM <- TM / rowSums(TM)) # As expected, everything around 0.25
#     To
# From         A         B         C         D
#   AA 0.2459016 0.2950820 0.2049180 0.2540984
#   AB 0.2222222 0.3037037 0.1925926 0.2814815
#   AC 0.3162393 0.1794872 0.1709402 0.3333333
#   AD 0.3211679 0.2189781 0.1824818 0.2773723
#   BA 0.2066116 0.2066116 0.2727273 0.3140496
#   BB 0.2517483 0.2587413 0.2167832 0.2727273
#   BC 0.2647059 0.2745098 0.2254902 0.2352941
#   BD 0.3007519 0.2180451 0.2105263 0.2706767
#   CA 0.2500000 0.2931034 0.2068966 0.2500000
#   CB 0.2178218 0.3168317 0.2178218 0.2475248
#   CC 0.2584270 0.2247191 0.2359551 0.2808989
#   CD 0.3083333 0.2583333 0.2500000 0.1833333
#   DA 0.2402597 0.2727273 0.2272727 0.2597403
#   DB 0.2689076 0.2605042 0.2016807 0.2689076
#   DC 0.2416667 0.2750000 0.2166667 0.2666667
#   DD 0.2442748 0.2213740 0.2671756 0.2671756

In your example we have the sequence and transitions given by
x <- c("A", "A", "A", "B", "C", "A", "D")
(transitions <- cbind(paste0(head(x, -2), head(x[-1], -1)), x[-1:-2]))
#      [,1] [,2]
# [1,] "AA" "A"
# [2,] "AA" "B"
# [3,] "AB" "C"
# [4,] "BC" "A"
# [5,] "CA" "D"

Analogously as in my other answer then,
prAA <- 1 / (4 * 4)
prAA * prod(TM[transitions])
# [1] 6.223154e-05

is the probability to observe x, where prAA is the probability (specified by the user) of observing the first two elements of the sequence, AA.

Generalization: n-th order Markov chain.
n <- 3
aux <- apply(dat, 2, function(col) {
  from <- head(apply(embed(col, n)[, n:1], 1, paste, collapse = ""), -1)
  to <- col[-1:-n]
  rbind(from, to)
})
aux <- data.frame(t(matrix(aux, nrow = 2)))
names(aux) <- c("From", "To")
TM <- table(aux)
TM <- TM / rowSums(TM)
head(TM)
#      To
# From          A         B         C         D
#   AAA 0.3541667 0.2083333 0.2083333 0.2291667
#   AAB 0.3103448 0.3103448 0.1724138 0.2068966
#   AAC 0.2142857 0.2857143 0.2857143 0.2142857
#   AAD 0.1463415 0.3902439 0.2439024 0.2195122
#   ABA 0.1200000 0.4800000 0.2000000 0.2000000
#   ABB 0.2424242 0.2727273 0.1515152 0.3333333

x <- c("A", "A", "A", "B", "C", "A", "D")
(transitions <- cbind(head(apply(embed(x, n)[, n:1], 1, paste, collapse = ""), -1), x[-1:-n]))
#      [,1]  [,2]
# [1,] "AAA" "B"
# [2,] "AAB" "C"
# [3,] "ABC" "A"
# [4,] "BCA" "D"
prAAA <- 1 / 4^n
prAAA * prod(TM[transitions])
# [1] 3.048129e-05

redpajama_set_name: RedPajamaStackExchange


text: Q: Tobit or OLS question My dependent variable is mostly continuous and positive, but has a modest number of zeros (10% of the sample). The results from tobit and ols are very similar. How can I formally compare the tobit and ols results? I think that I should be using ols, because tobit doesn't change anything.


text:
Q: android Project add new activity error ? I am having trouble adding new activity to my android Project  because of this error
error MSG:
R cannot be resolved to a variable  testActivity.java
I really want to know what is correct way to add new activity to my project and how to solve this error?

A: You need to clean your project a few times. Save the code and clean the project and make sure you have not used import andorid.R;

A: How to add a new activity:

*

*Right click in your project

*New > Class

*Enter the name of your Activity.

*In super class field: android.app.Activity

Also, make sure you clean your project, close Eclipse and launch it again.
Finally, double check that you included your new activity in your manifest file.


text:
Q: html positioning difficulty
How do I get the About Me and Education sections to the right side of the web
Here is pencode link: https://codepen.io/Weng-Hong-the-selector/pen/GRGjVLy
Here is my HTML and CSS
`
<!DOCTYPE html>

TAN WENG HONG

STUDENT OF DIPLOMA IN IT

                Male

                Malaysian

                13A, Elitis Suria, Valencia, 47000, Sungai Buloh, Selangor

                012-352-5089

                wenghong.tan@sd.taylors.edu.my

Social

Facebook

Instagram

Youtube

LinkedIn

About me

My name is Tan Weng Hong and I am currently 19 years old

Education

2021 - present

Taylor's College

Diploma in Information Technology

Current CGPA: 3.01

Will Graduate August 2023

2016 - 2020

SMK Sri KDU

- Sijil Pelajaran Malaysia (SPM)

 &nbsp&nbspResults: 1A+ 1A 1C+ 1C 2D 3E 1G

`
`
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  list-style: none;
  font-family: 'Roboto Condensed', sans-serif;
}

body {
  background: #D3D3D3;
  font-size: 14px;
  line-height: 22px;
  color: #555555;
  width: 200vh;
  text-align: center;
}

img{
  border: solid;
  border_width: 5px;
}

.bold {
  font-weight: 700;
  font-size: 20px;
  text-transform: uppercase;
}

.semi-bold {
  font-weight: 500;
  font-size: 16px;
}

.regular{
  font-weight: 700;
  font-size: 12px;
  text-transform: uppercase;
}
.resume {
  width: 1200px;
  height: auto;
  display: flex;
  margin: 50px auto;
}

.resume .resume_left {
  width: 290px;
  height: 1050px;
  background: #0bb5f4;
  padding: 3px;
}

.resume .resume_left .resume_profile {
  width: 100%;
  height: 350px;
}

.resume .resume_left .resume_profile img {
  width: 100%;
  height: 100%;
}

.resume .resume_left .resume_content {
  padding: 0 25px;
}

.resume .title {
  margin-bottom: 20px;
}

.resume .resume_left .bold {
  color: #fff;
}

.resume .resume_left .regular {
  color: #b1eaff;
}

.resume .resume_item {
  padding: 25px 0;
  border-bottom: 2px solid #b1eaff;
}

.resume .resume_left ul li {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.resume .resume_left ul li:last-child {
  margin-bottom: 0;
}

.resume .resume_left ul li .icon {
  width: 35px;
  height: 35px;
  background: #fff;
  color: #0bb5f4;
  border-radius: 50%;
  margin-right: 15px;
  font-size: 16px;
  position: relative;
}

.resume .icon i,
.resume ul li i {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.resume .resume_left ul li .data {
  color: #b1eaff;
}

.resume .resume_left .resume_social .semi-bold {
  color: #fff;
  margin-bottom: 3px;
}

`
i want my about me section and education section to be on the right side of info section, any idea how to get that to work? thank you in advance

A: Not sure if you already figured this out, but a quick look at your code I saw that you had a html organization problem so the resume_right was inside the resume_left
this is your fixed code, hope it helps.
If after this you have any positioning problems, I suggest you read the CSS flex documentation.
https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox

TAN WENG HONG

STUDENT OF DIPLOMA IN IT

                Male

                Malaysian

                13A, Elitis Suria, Valencia, 47000, Sungai Buloh, Selangor

                012-352-5089

                wenghong.tan@sd.taylors.edu.my

Social

Facebook

Instagram

Youtube

LinkedIn

About me

My name is Tan Weng Hong and I am currently 19 years old

Education

2021 - present

Taylor's College

Diploma in Information Technology

Current CGPA: 3.01

Will Graduate August 2023

2016 - 2020

SMK Sri KDU

- Sijil Pelajaran Malaysia (SPM)

 &nbsp&nbspResults: 1A+ 1A 1C+ 1C 2D 3E 1G

A: You should use position to choose the place of your elements in the flow,
in your example, if you want to have your "About me" and "education" always displayed on the right of your screen you have to use
position : fixed;
right : 0;

If you want them to be scrolled like everything else, you can considere using
position : absolute;
right : 0;

In both case you'll have to be carefull of element stacking.
Here are informations about position :
https://developer.mozilla.org/fr/docs/Web/CSS/position

A: You can use either text-align: right, or display: flex together with justify-content: flex-end. In general, text-align works mostly on text elements, and justify-content will justify all elements and content.

A: I think using flex box it will help you:
    display: flex;
    justify-content: flex-end

or you can use positioning for this for example:

     This div has absolute positioning.


text:
Q: Accessing value returned by scala futures I am a newbie to scala futures and I have a doubt regarding the return value of scala futures.
So, generally syntax for a scala future is
 def downloadPage(url: URL) = Future[List[Int]] {

 }

I want to know how to access the List[Int] from some other method which calls this method.
In other words,
val result = downloadPage("localhost")

then what should be the approach to get List[Int] out of the future ?
I have tried using map method but not able to do this successfully.`

A: I hope you already solved this since it was asked in 2013 but maybe my answer can help someone else:
If you are using Play Framework, it support async Actions (actually all Actions are async inside). An easy way to create an async Action is using Action.async(). You need to provide a Future[Result]to this function.
Now you can just make transformations from your Future[List[Int]] to Future[Result] using Scala's map, flatMap, for-comprehension or async/await. Here an example from Play Framework documentation.
import play.api.libs.concurrent.Execution.Implicits.defaultContext

def index = Action.async {
  val futureInt = scala.concurrent.Future { intensiveComputation() }
  futureInt.map(i => Ok("Got result: " + i))
}

A: You can do something like that. If The wait time that is given in Await.result method is less than it takes the awaitable to execute, you will have a TimeoutException, and you need to handle the error (or any other error).
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.{Try, Success, Failure}
import scala.concurrent.duration._

object MyObject {
    def main(args: Array[String]) {

        val myVal: Future[String] = Future { silly() }

        // values less than 5 seconds will go to
        // Failure case, because silly() will not be done yet
        Try(Await.result(myVal, 10 seconds)) match {
            case Success(extractedVal) => { println("Success Happened: " + extractedVal) }
            case Failure(_) => { println("Failure Happened") }
            case _ => { println("Very Strange") }
        }
    }

    def silly(): String = {
        Thread.sleep(5000)
        "Hello from silly"
        }
}

A:
The case of Success(listInt) => I want to return the listInt and I am not able to figure out how to do that.

The best practice is that you don't return the value. Instead you just pass the future (or a version transformed with map, flatMap, etc.) to everyone who needs this value and they can add their own onComplete.
If you really need to return it (e.g. when implementing a legacy method), then the only thing you can do is to block (e.g. with Await.result) and you need to decide how long to await.

A: The best way I've found to think of a Future is a box that will, at some point, contain the thing that you want. The key thing with a Future is that you never open the box. Trying to force open the box will lead you to blocking and grief. Instead, you put the Future in another, larger box, typically using the map method.
Here's an example of a Future that contains a String. When the Future completes, then Console.println is called:
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object Main {

  def main(args:Array[String]) : Unit = {
    val stringFuture: Future[String] = Future.successful("hello world!")
    stringFuture.map {
      someString =>
        // if you use .foreach you avoid creating an extra Future, but we are proving
        // the concept here...
        Console.println(someString)
    }
  }
}

Note that in this case, we're calling the main method and then… finishing. The string's Future, provided by the global ExecutionContext, does the work of calling Console.println. This is great, because when we give up control over when someString is going to be there and when Console.println is going to be called, we let the system manage itself. In constrast, look what happens when we try to force the box open:
val stringFuture: Future[String] = Future.successful("hello world!")
val someString = Future.await(stringFuture)

In this case, we have to wait — keep a thread twiddling its thumbs — until we get someString back. We've opened the box, but we've had to commandeer the system's resources to get at it.

A: It wasn't yet mentioned, so I want to emphasize the point of using Future with for-comprehension and the difference of sequential and parallel execution.
For example, for sequential execution:
object FuturesSequential extends App {

  def job(n: Int) = Future {
    Thread.sleep(1000)
    println(s"Job $n")
  }

  val f = for {
    f1 <- job(1)
    f2 <- job(2)
    f3 <- job(3)
    f4 <- job(4)
    f5 <- job(5)
  } yield List(f1, f2, f3, f4, f5)
  f.map(res => println(s"Done. ${res.size} jobs run"))
  Thread.sleep(6000) // We need to prevent main thread from quitting too early
}

And for parallel execution (note that the Future are before the for-comprehension):
object FuturesParallel extends App {

  def job(n: Int) = Future {
    Thread.sleep(1000)
    println(s"Job $n")
  }

  val j1 = job(1)
  val j2 = job(2)
  val j3 = job(3)
  val j4 = job(4)
  val j5 = job(5)

  val f = for {
    f1 <- j1
    f2 <- j2
    f3 <- j3
    f4 <- j4
    f5 <- j5
  } yield List(f1, f2, f3, f4, f5)
  f.map(res => println(s"Done. ${res.size} jobs run"))
  Thread.sleep(6000) // We need to prevent main thread from quitting too early
}

A: You need to wait for the future to complete to get the result given some timespan, here's something that would work:
  import scala.concurrent.duration._

  def downloadPage(url: URL) = Future[List[Int]] {
    List(1,2,3)
  }

  val result = downloadPage("localhost")

  val myListInt = result.result(10 seconds)

Ideally, if you're using a Future, you don't want to block the executing thread, so you would move your logic that deals with the result of your Future into the onComplete method, something like this:
  result.onComplete({
    case Success(listInt) => {
      //Do something with my list
    }
    case Failure(exception) => {
      //Do something with my error
    }
  })


text:
Q: Precipitation plot, or mirrored histogram based on top axis I like to plot simple time series data and overplot precipitation data. The following code plots a line for the usual data and adds barplots (or histogram bars) for the precipitation data.
D # a simple (zoo) time series
P # a simple (zoo) time series of precipitation
plot(D, type="l")
lines(P, type="h", lwd=5)

But the bars are based on the y=0 axis and rise topwards. But usual in hydrology are precipitation bars that are based on the very top axis and "flow" downwards. D has arbitrary y-ranges, so I would prefer a solution that does fix a value for the baseline of P.
I googled a lot but did not manage to find how to do this in R without ggplot and without extra packages like hydrograph.

A: Not sure whether I understood it correctly so this is my interpretation.
Don't know whether this works with zoo objects as well.
# Create some mock data
x<-runif(20,0,100)
y<-runif(20,0,100)

# This is the normal topwards plot
plot(x,y,type="h")

# And this is the downwards plot
plot(x, y, ylim = rev(range(y)),type="h")

A: With the help of BlankUsername I found the following solution for zoo time series. I have not been aware of something like par(new=T) or the axis() command before:
# plot the usual data
plot(D)
# add half day to indicate that P is a sum of the whole day
index(P) <- index(P) + 0.5
# define an overlay plot without border
par(bty="n", new=T)
plot(P, type="h", ylim=rev(range(P)), # downward bars by BlankUsername
    yaxt="n", xaxt="n", ann=F, # do not plot x and y axis
    xlim=c(start(D),end(D)), # without xlim the two overlayed plots will not fit
    lwd=10, col=rgb(0,0,0,0.1) ) # suggested cosmetics
# add right axis (4) to describe P
axis(4, pretty(range(P)), col.axis="grey", col="grey", las=1, cex.axis=0.7 )
# reset border and overlay
par(bty="o", new=F)


text:
Q: Idempotent and Transactions I am exploring Transactions in Kafka, and I want to understand all the details.
I noticed in Spring-Kafka that idempotent is enabled when you provide a transactionsalId.
public void setTransactionIdPrefix(String transactionIdPrefix) {
    Assert.notNull(transactionIdPrefix, "'transactionIdPrefix' cannot be null");
    this.transactionIdPrefix = transactionIdPrefix;
    enableIdempotentBehaviour();
}

At first glance, I assume Spring-Kafka enabled idempotent in transactions because it is "good-to-have". I assumed it was to ensure to ensure exactly-once semantics in transactions.
I did a bit more digging and discovered that idempotent is required for transactions to work. This is mentioned in KIP-98

Note that enable.idempotence must be enabled if a TransactionalId is
  configured.

Kafka idempotent is a feature to avoid duplicated messages, such as network errors after the message has been sent.
My understanding is that, Kafka transactions basically writes to an internal topic and idempotent has to be enabled to avoid duplicates.
Idempotent enables exactly-once semantics for producers.
Transactions enables exactly-once semantics for transitivity; consume -> produce.
Is my understanding correct?
What enables exactly-once for only consumers? Committing offset, idempotent, or transactions.

A: The Idempotent producer enables exactly once for a producer against a single topic. Basically each single message send has stonger guarantees and will not be duplicated in case there's an error.
The Transactional producer on the other hand enables to group a number of send (that can be across many partitions) together and have all of them (or none) applied. Transactions can also contain offset commits (in the end commiting offsets is the same as writing to a topic).
Because Consumers fetch data from Kafka, it's sort of already exactly once. When the consumer asks Kafka messages from offset N, if it does not receives them, it will just retry, there can't be any duplication. The only exactly once need for COnsumers is for committing offsets and that can be done by the Transactional Producer (The consumer needs to pass its current offsets to the Producer).


text:
Q: A way to count amount of elements in-between another element and returning an array So, I am trying to scrape data off a page to analyze it with R. In order for a complete analysis I need to be able to account for the day of each infection. The page portrays it's content as so:

 5 of March

    x10

 4 of March

    x15

 3 of March

and so on until the 21 of Januray.
What I want to do is to count the amount of
 that are within a given
 that corresponds to its
 and for python to give me back a list that repeats the
 string the
 amount of times.
So for example, in
 5 of March
 case I would want a list that repeats "5 of March" 12 times, because there are 12
 that correspond to that
.
so far this is my code, but it doesn't even return something to me:
import re
from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd

driver = webdriver.Chrome(#purposefully left blank)

amount = []
cases = []
deaths = []
Country = []
Province = []

driver.get("https://bnonews.com/index.php/2020/01/timeline-coronavirus-epidemic/")

content = driver.page_source
soup = BeautifulSoup(content)

h4_tag = str(soup.findAll('h4'))
li_tag = str(soup.findAll('li'))

FLAGS = re.VERBOSE | re.DOTALL | re.IGNORECASE

At this point I was just trying to see if I could count the amount of
 elements but I can't even do that...
Any Ideas? I've checked stack and git for answers but to no avail...
UPDATE
the code findChildren doesn't work because the
 and
 elements are not children of the
 element. Removed "recursive"
ul_tag =  soup.find('div', attrs = {'class':'mvp-post-soc-in'})
children = ul_tag.find('li')
print(children)

This code returns a list with all
 elements and their content.
Trying to check if soup(content) is string
This is what I get when I print soup:
<meta content="60109657413" property="fb:pages"/>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" id="viewport" name="viewport"/>
<link href="https://bnonews.com/wp-content/uploads/2018/03/favicon2.ico" rel="shortcut icon"/><link href="https://bnonews.com/xmlrpc.php" rel="pingback"/>
<meta content="article" property="og:type"/>
<meta content="https://bnonews.com/wp-content/uploads/2019/04/2019EbolaWorker.jpg" property="og:image"/>
<meta content="https://bnonews.com/wp-content/uploads/2019/04/2019EbolaWorker.jpg" name="twitter:image"/>
<meta content="https://bnonews.com/index.php/2020/01/timeline-coronavirus-epidemic/" property="og:url"/>
<meta content="TIMELINE: Coronavirus epidemic" property="og:title"/>
<meta content="The following is a timeline of new cases in China and around the world. It is updated once a day. For the current day, click here. Timeline (GMT) 10 March 23:57: First 2 cases in Bolivia. (Source) 23:40: 21 new cases and 1 new death in Spain. (Source) 23:39: 1 new case in Nebraska, United […]" property="og:description"/>
<meta content="summary" name="twitter:card"/>
<meta content="https://bnonews.com/index.php/2020/01/timeline-coronavirus-epidemic/" name="twitter:url"/>
<meta content="TIMELINE: Coronavirus epidemic" name="twitter:title"/>
<meta content="The following is a timeline of new cases in China and around the world. It is updated once a day. For the current day, click here. Timeline (GMT) 10 March 23:57: First 2 cases in Bolivia. (Source) 23:40: 21 new cases and 1 new death in Spain. (Source) 23:39: 1 new case in Nebraska, United […]" name="twitter:description"/>
<title>TIMELINE: Coronavirus epidemic - BNO News</title>
<link href="https://bnonews.com/index.php/2020/01/timeline-coronavirus-epidemic/" rel="canonical"/>
<meta content="en_US" property="og:locale"/>
<meta content="article" property="og:type"/>
<meta content="TIMELINE: Coronavirus epidemic - BNO News" property="og:title"/>
<meta content="The following is a timeline of new cases in China and around the world. It is updated once a day. For the current day, click here. Timeline (GMT) 10 March 23:57: First 2 cases in Bolivia. (Source) 23:40: 21 new cases and 1 new death in Spain. (Source) 23:39: 1 new case in Nebraska, United …" property="og:description"/>
<meta content="https://bnonews.com/index.php/2020/01/timeline-coronavirus-epidemic/" property="og:url"/>
<meta content="BNO News" property="og:site_name"/>

A: Since ul is not contained within the parent container you want to print, you will probably have to walk the html elements and print as you go, checking for the different elements along the way.
from bs4 import BeautifulSoup

html = '
 5 of March

 4 of March

 3 of March

'
soup = BeautifulSoup(html, 'html.parser')

current_h4 = ''
for e in soup:
    if e.name == 'h4':
        current_h4 = e.text
    if e.name == 'ul':
        for li in e.find_all('li'):
            print(current_h4)

Result:
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 5 of March
 4 of March
 4 of March
 3 of March

Additional Update:
Here is a working example using your exact data source. It is easier to target the div that contains your data directly (id="mvp-content-main") instead of one of the parent divs. I believe the issues you were having was in navigating down the child elements to the one you actually wanted. The result below prints 2,596 lines.
from selenium import webdriver
from bs4 import BeautifulSoup

driver = webdriver.Chrome(executable_path=r'your/path/here/chromedriver.exe')

driver.get("https://bnonews.com/index.php/2020/01/timeline-coronavirus-epidemic/")

content = driver.page_source
soup = BeautifulSoup(content)
ul_tag = soup.find('div', attrs = {'id':'mvp-content-main'})

current_h4 = ''
for e in ul_tag:
    if e.name == 'h4':
        current_h4 = e.text
    if e.name == 'ul':
        for li in e.find_all('li'):
            print(current_h4)


text:
Q: how to write select tag with javascript? I have a website in which I am writing html code with javascript because I want to load everything into javascript code so that user won't feel any delay.But I am unable to implement "date of birth" part with javascript.Here is my code.
function getBasicProfileEditBody()
{
    var basicProfileEditBody = "
"+
                                    "
"+
                                        "gender:<input type='radio' name='gender' value='female' />female<input type='radio' name='gender' value='male' />male"+
                                    "
"+
                                    "
"+
                                        "date of birth:"+
                                        ""+
                                            "<select id='dateOfBirth'>"+

                                            +"</select>"+
                                        ""+
                                    "
"+
                                    "
"+
                                        "my strengths:"+
                                    "
"+
                                    "
"+
                                        "my weaknesses:"+
                                    "
"+
                                    "
"+
                                        "persons i like:"+
                                    "
"+
                                    "
"+
                                        "things i like in others:"+
                                    "
"+
                                    "
"+
                                        "things i don't like in others:"+
                                    "
"+
                                    "
"+
                                        "my friends:"+
                                    "
"+
                                    "
"+
                                        "<input type='button' value='edit' id='aboutProfileEdit' /><input type='button' value='cancel' id='aboutProfileCancel' />"+
                                    "
";
return basicProfileEditBody;
}

In this style if I have to write select tag for dates it is ok but how about select tag for years,it would be a burden to me?wouldn't it be?How to implement "date of birth" in this style?

A: To answer your question, try following way:
First step: Replace the source code "<select id='dateOfBirth'>"+</select>" by "div id='dateOfBirth'>"+
", because you need three select boxes.
Second step: Add some code to create each entries more or less automatically:
function getBasicProfileEditBody()
{
  ...

  var startBirthYearRange = 1970;
  var d = new Date();
  var endBirthYearRange = d.getFullYear();
  var yearEntries = endBirthYearRange - startbirthYear;
  var selectBoxYearOfBirth = "<select id='yearOfBirth'>";
  for (index = 0; index < yearEntries; index++)
  {
    selectBoxYearOfBirth += "<option>" + startBirthYearRange + index) + "</option>";
  }
  selectBoxYearOfBirth += "</select>";

  var birthMonth = new Array();
  birthMonth.push("1@January");
  birthMonth.push("2@February");
  birthMonth.push("3@March");
  ...
  birthMonth.push("12@December");
  var selectBoxMonthOfBirth = "<select id='monthOfBirth'>";
  for (index = 0; index < 12; index++)
  {
   var itemArry = birthMonth[index].split("@");
   selectBoxMonthOfBirth = += "<option value='" + itemArry[0] + "'>" +
                              itemArry[1] + "</option>";
  }
  selectBoxYearOfBirth += "</select>";

  var selectBoxDayOfBirth = = "<select id='dayOfBirth'>";
  for (index = 0; index < 31; index++)
  {
    selectBoxDayOfBirth = += "<option>" + (index + 1) + "</option>";
  )
  selectBoxDayOfBirth += "</select>";

  //Then apped the new three variables to var 'basicProfileEditBody'
  ...
}


text:
Q: Wordpress support I like to get a customer website to full cms website / blog / magazine / ecommerce
I will go with wordpress (joomla and drupal on the runner up list)
I will for sure need support for customizing template, code, php and plugins
I always found AMAZING support from stackoverflow, i like to have the same thing for wp... do you know where i should ask my Wordpress question and post my code...?
Thanks in advance

A: http://wordpress.org/support/


text:
Q: How to call Db view file in repository pattern? I am creating a view file in SQL Server as shown in the image below.

and I created a model to get results from this view:
public class FactALLCousumption : BaseEntity, IAggregateRoot
{

    public double sumActiveImportTotal { get;  set; }
    public DateTime hour { get;  set; }
    public int fullDateAlternateKey { get;  set; }
}

But I can't call this view in my repository. My repository code is bellow:
public class FactCousumptionRepository: GenericRepository<FactCousumption>, IFactCousumptionRepository
{
    public DbContext _dbContext;

    public FactCousumptionRepository(BaseDbContext context) : base(context)
    {
        _dbContext = context;
    }

    public async Task<FactALLCousumption> GetTotalAllCousumption()
    {

    }
}

A: In EF Core 2.2 or 2.1, you could use Query types.
According to the screenshot and the model to be used for the View you provided , I make a simple working demo like below , you could refer to and make the modification as per your demand:
1.Model
 public class FactCousumption
{
    public int Id { get; set; }
    public double SumActiveImportTotal { get; set; }
    public int DateKeyId { get; set; }
    [ForeignKey("DateKeyId")]
    public Dim_Date Dim_Date { get; set; }
    public int TimeAltKeyId { get; set; }
    [ForeignKey("TimeAltKeyId")]
    public Dim_Time Dim_Time { get; set; }
    public int TariffKeyId { get; set; }
    [ForeignKey("TariffKeyId")]
    public Dim_Tariff Dim_Tariff { get; set; }
}

public class Dim_Date
{
    [Key]
    public int DateKey { get; set; }
    public int FullDateAlternateKey { get; set; }
    public DateTime Date { get; set; }
    public ICollection<FactCousumption> FactCousumptions { get; set; }
}

public class Dim_Time
{
    [Key]
    public int TimeAltKey { get; set; }
    public DateTime Hour { get; set; }
    public ICollection<FactCousumption> FactCousumptions { get; set; }
}
 public class Dim_Tariff
{
    [Key]
    public int TariffType { get; set; }
    public string TariffName { get; set; }

    public ICollection<FactCousumption> FactCousumptions { get; set; }
}

2.Create SQL View
CREATE VIEW [dbo].[View1]
AS  SELECT SUM(FactCousumption.SumActiveImportTotal) AS consumption ,Dim_Time.HOUR,Dim_Date.FullDateAlternateKey,Dim_Tariff.TariffName
  FROM FactCousumption INNER JOIN
        Dim_Date ON FactCousumption.DateKeyId = Dim_Date.DateKey INNER JOIN
        Dim_Time ON FactCousumption.TimeAltKeyId=Dim_Time.TimeAltKey INNER JOIN
        Dim_Tariff ON FactCousumption.TariffKeyId=Dim_Tariff.TariffType
  GROUP BY Dim_Date.FullDateAlternateKey, Dim_Time.HOUR ,Dim_Tariff.TariffName

3.The model that is used for the view , note : the property name in model should be consistent with those in the view
public class FactALLCousumption
{
    public double consumption { get; set; }
    public DateTime hour { get; set; }
    public int fullDateAlternateKey { get; set; }
}

4.DbContext , create  a DbQuery property in my DbContext to consume the view results inside the Model and set up the View especially if you have different view name than your Class.
 public DbQuery<FactALLCousumption> FactALLCousumption { get; set; }

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Query<FactALLCousumption>().ToView("View1");
 }

5.Finally you can easily get the results of the View like this.
public async Task<FactALLCousumption> GetTotalAllCousumption()
{
        var result = await _context.FactALLCousumption.FirstOrDefaultAsync();

        return result;
}

Note: It's worth noting that DbQuery won't be/is not supported anymore in EF Core 3.0. See here


text:
Q: Null Check operator won't work on WebOperationContext.Current?.IncomingRequest It looked odd when I tried to add a null check operator on the following code
 WebOperationContext.Current?.IncomingRequest?.Headers[""];

This didn't catch the null and somehow Resharper recognized that question mark won't work and grayed it out.
But the following worked.
var httpIncomingRequest = WebOperationContext.Current?.IncomingRequest;
            var _ = httpIncomingRequest?.Headers[]

What is so special about IncomingRequest object that would stop us using null check operator?

A: You missed a check in Headers. This proves my hypothesis. There isn't an exception if there is a check  in Headers
https://dotnetfiddle.net/OqcL9U
WebOperationContext.Current?.IncomingRequest?.Headers?[""];

A: I decompiled the WebOperationContext class and found out that IncomingRequest property never returns null:
public IncomingWebRequestContext IncomingRequest
{
  get
  {
    return new IncomingWebRequestContext(this.operationContext);
  }
}

So it looks like R# is analyzing assembly bytecode and trying to check if question mark is redundant.


text:
Q: Selecting single expander within a list I have many expanders within a listbox and I have requirement where in I need only one to be expanded at any moment in time.
I use the below code from the msdn forums
<ListBox>
<ListBox.Resources>
  <Style TargetType="{x:Type Expander}">
    <Setter
       Property="IsExpanded"
       Value="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"/>
  </Style>
</ListBox.Resources>
<ListBox.Template>
  <ControlTemplate TargetType="{x:Type ListBox}">
    <ItemsPresenter/>
  </ControlTemplate>
</ListBox.Template>
<ListBox.ItemContainerStyle>
  <Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type ListBoxItem}">
          <ContentPresenter Content="{TemplateBinding Content}"/>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
</ListBox.ItemContainerStyle>
<Expander Background="Gray" Width="243" Header="Expander1">
  <StackPanel>
    <RadioButton Content="Eat Me" GroupName="Two"/>
    <RadioButton Content="Eat Pork" GroupName="Two"/>
    <RadioButton Content="Eat at Joe's" GroupName="Two"/>
  </StackPanel>
</Expander>
<Expander Background="Gray" Width="243" Header="Expander2">
  <StackPanel>
    <RadioButton Content="Pork" GroupName="Two"/>
    <RadioButton Content="Beef" GroupName="Two"/>
    <RadioButton Content="Chicken" GroupName="Two"/>
  </StackPanel>
</Expander>
<Expander Background="Gray" Width="243" Header="Expander3">
  <StackPanel>
    <RadioButton Content="Grill" GroupName="Two"/>
    <RadioButton Content="Bake" GroupName="Two"/>
    <RadioButton Content="Fry" GroupName="Two"/>
  </StackPanel>
</Expander>

When I paste this code in a sample app, everything works as usual.
But when I paste it into our projectcode, the single expander selection does not work.
I used an attached behavior to figure out whats really happening.
<Style x:Key="listBoxStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <ContentPresenter Content="{TemplateBinding Content}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="utilities:ListBoxItemBehavior.TemplatedListBoxItem" Value="True"/>
    </Style>

private static void Callback(object sender, DependencyPropertyChangedEventArgs args)
    {
        ListBoxItem listBoxItem = sender as ListBoxItem;

        if (listBoxItem != null)
        {
            listBoxItem.Selected += (s, a) =>
            {
                MessageBox.Show("ListBoxItem selected");
            };

            listBoxItem.Unselected += (s, a) =>
            {
                MessageBox.Show("ListBoxItem un-selected");
            };
        }
    }

to my surprise, the selected and unselected event never get called when I put it into my project code. Is there any reason why this is happening.
Can someone guide me?
thanks


text:
Q: Test is data is derived from mixture or just noisy normal Is there a way to quantify \ test \ describe how likely it is that high dimensional data come from a single Gaussian or a mixture of Gaussians (with different means \ SDs) or not?
What I am thinking of is similar to the idea of a t-test, but when the separation into groups is unknown.


text: Q: Wifi country (?) problem in ubuntu 18.04 and hotspot So I just bought a laptop from an italian company This with Ubuntu already installed. I am living in Mexico and when I tried to connect to the wifi it was either really slow or just did not work at all. I changed the country code to Mexico (MX) but I didn't see any changes. So I tried to use my smartphone to make hotspot, and connecting to this my laptop is perfect, fast and does not lose connection. What can it be? I specify that with the mexican wifi I never had a problem with my android smartphone and my old chromebook.


text:
Q: How to convert the Prices on my ProductCard to another Currency in React JS I am working on a Multi-Currency ecommerce app in React JS. I have been able to successfully convert the price on the Product Detail page to Buyer's local Currency.
I am having problem converting the prices on the Products Mapped on the home page to local currency using the same method I used for the Product detail page.
This is the function for converting:
this.myFX = (item) => {
      const userCurrency = localStorage.getItem("myCurrency");
      fx.base = "USD";
      fx.rates = {
        AED: 3.6729,
        AFN: 77.050006,
        ALL: 100.85,
        AMD: 481.616228,
      ...
      };
      const result = fx(item.unit_price).from(item.currency).to(userCurrency);
      this.setState({
        convertedPrice: result.toFixed(2),
      });
    };

This is the code for mapping my products:

    <div className="card-body row">
                  {this.state.featured.map((item, i) => (
                    <Card
                      className="col-xl-3 col-sm-6"
                      style={{ width: "18rem" }}
                      key={i}
                    >
                      <Link to={`/product/${item.id}`}>
                        {" "}
                        <Card.Img variant="top" src={item.img1} />{" "}
                      </Link>
                      <Card.Body>
                        <Card.Title>{item.name}</Card.Title>
                        <Card.Text className="text-uppercase text-primary">
                          {item.category}
                        </Card.Text>

                        <Card.Title style={{ fontWeight: "500" }}>
                          Price: {this.state.convertedPrice}

                        </Card.Title>
                      </Card.Body>
                    </Card>
                  ))}

Please how best can I do this?

A: To convert prices in a map you could extract the conversion logic into a function that returns the value. Then use the new function in the map of results as well as the original place where the state is being set.
this.getConvertedPrice = (item) => {
  const userCurrency = localStorage.getItem("myCurrency");
  fx.base = "USD";
  fx.rates = {
    AED: 3.6729,
    AFN: 77.050006,
    ALL: 100.85,
    AMD: 481.616228,
  ...
  };
  return fx(item.unit_price).from(item.currency).to(userCurrency);
};

...

this.myFX = (item) => {
  const result = this.getConvertedPrice(item)
  this.setState({
    convertedPrice: result.toFixed(2),
  });
};

...

<Card.Title style={{ fontWeight: "500" }}>
  Price: {this.getConvertedPrice(item).toFixed(2)}
</Card.Title>


text:
Q: Hide a specific cell in my table I'm trying to hide a specific cell in my table view?
private var yourDataSource = [AccountData.AllTasksDB] //A Json Array originally

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    var rowHeight:CGFloat = 72

    //AccountData.AllTasksDB[indexPath.row]["importantvariable"]
    if (self.yourDataSource[indexPath.row]["importantvarible"] == "0")
    {
        print("Cell is mine")
        rowHeight = 0
    }
    else
    {
        print("Cell is not mine")
        rowHeight = 72.0
    }

    return rowHeight
}

Can anyone tell me what I'm doing wrong? I thought it was looping through each cell and checking a value i've setup before hand. But it doesn't seem to want to access it.

A: You are accessing cell in the tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) method.
At this point the cell is not yet visible (or dequeued). If the cell is not visible, it will be nil, hence your error.
Try putting a break point at let cell = tableView.cellForRowAtIndexPath(indexPath) as! TableViewCellMyTasks and you'll see that it is nil.

A: I figured this would be more legible in an answer
fileprivate var yourDataSource = [YourObject]()

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {

  if self.yourDataSource[indexPath].isMine == true {

    return 0
  }
  else
  {
    return 72.0    //or whatever you like
  }
}


text:
Q: Hibernate and prepared statement As far as I could find from google, hibernate uses PreparedStatement for its queries.
I need to execute a query consisting of two parts, the first part of which could be written in hibernate criteria and the second one is a dblink query, therefore hibernate cannot be used.
So, I would like to extract the PreparedStatement object from the Criteria object.
Criteria criteria = getSession().createCriteria(Entity.class);
//adding restrictions
PreparedStatement stmt;
//initializing stmt with criteria's PreparedStatement

How can I do that?
Is it even possible?

A: This is not possible with the current Hibernate API. And it would be difficult to add support for it anyway. For example, to execute getSession().createCriteria(Entity.class) without any other restrictions, Hibernate may need to produce more than one PreparedStatement (to fetch Entity and all of its associations, based on defined fetch plan and strategy for Entity class).
Also, it would be difficult for you to implement and maintain such a solution event if something like that existed. You may need to parse the generated statements to be able to 'inject' your part of the query. Or the generated statements may change when you modify your entities or depending on the current state of persistence context (something that's already in the session is not fetched again, so the queries are different etc). You would also need to be careful when upgrading Hibernate to a new version because the exact structure of the generated queries may change.
There are probably many other obstacles that would make it hard to achieve this for the time being, but I think that your reasoning is good, and hopefully Hibernate will expose some kind of API in future which will allow us to have greater influence on the generated SQL.

A: Create a view that uses the dblink query in the same schema as your table.
Then create an entity that maps to your view.
You can then create a DetachedCriteria to use as a subselect in your criteria query.


text:
Q: Why doesn't this work for finding the PDF of $X_1 X_2$ where $X_1,X_2$ iid Unif(0,1) Let $X_1,X_2$ be iid Unif(0,1) random variables.
Find the PDF of $Y = X_1 X_2$.
This is my method and I'm unsure why it's wrong:
$$\mathbb{P}(Y\leq y) = \mathbb{P}(X_1 X_2 \leq y) \\ = \int_{\text{all} x} \mathbb{P}(X_2 \leq y/x | X_1 = x)f_{X_1}(x) \ dx \\ = \int_{\text{all} x} F_{X_2}(y/x) f_{X_1}(x) \ dx \\ = \int_{\text{all} x} \int_{0}^{y/x} I(0<y/x < 1)I(0<x<1) \ dx \\ = \int_{\text{all} \ x} y/x I(0<y/x < 1)I(0<x<1) \ dx \\ = \int_{y}^1 \frac{y}{x} \ dx \\ = -y\log y
$$
Hence, the PDF is the derivative which is $-(1+\log y)$
but the solution says that it's actually just $-\log y$. Where did I go wrong?

A: The problem is that$$\mathbb{P}(X_2 \leq y/x | X_1 = x)\not=\frac yx.$$
This is because if $y>x$ then $y/x>1$ and then $$F_{X_2}(y/x)=1.$$
So
$$\int_0^1\mathbb{P}(X_2 \leq y/x | X_1 = x)dx=\int_0^y1dx+y\int_y^1\frac 1x\ dx=y-y\ln(y)$$
the derivative of which is, indeed $-\ln(y)$.


text:
Q: Asp.NET Hiddenfield set $row as value I try to set my row in hiddenfield at get it back in another function.There is nothing wrong  at first $row value it is correct I use it in  A function
  <asp:HiddenField runat="server" ID="hdnSelectedFile" />

   // A function
   var $row = $(elem).closest("tr");
  $("[id*=hdnSelectedFile]").val($row);

     //another function
     // B function

      var $row = $("[id*=hdnSelectedFile]").val();
      if ($row != null && $row != "") {
        $($row).attr("data-showanswer", "0");
        $($row).attr("data-isdate", "0");
        $($row).attr("data-startdate", null);
        $($row).attr("data-finishdate", null);
        }

The error is  for my $row

Uncaught Error: Syntax error, unrecognized expression: [object Object]


text:
Q: Equation brackets after frac remain small My brackets in the equation remain small, between brackets I have a fraction, usually the brackets auto size and become the same size and enclose the fraction.
\documentclass[11pt,a4paper]{report}
\usepackage{graphicx}
\usepackage[a4paper]{geometry}
\usepackage[english]{babel}
\usepackage{fancyhdr}
\usepackage{float}
\usepackage{epstopdf}
\usepackage{enumerate}
\usepackage[utf8]{inputenc}
\usepackage{pdfpages}
\usepackage{tabularx}
\usepackage{array}
\usepackage{amsmath}
\begin{document}
\begin{equation}\label{eqn:arr}
k(T)=k^0\texttt{exp}(\frac{E}{R}(\frac{1}{T_{ref}})-\frac{1}{T})
\end{equation}
\end{document}

A: Brackets in equations only auto size if you ask them to. You can either set the size manually with \big, \Big, \bigg or \Bigg or let LaTeX compute it for you with \left(…\right). You need to use the former if the latter gives the wrong sizes or fails to compile, e.g. if you have brackets across several lines or some form of \underbrace. In your case,
\begin{equation}\label{eqn:arr}
k(T)=k^0\texttt{exp}\left(\frac{E}{R}\left(\frac{1}{T_{ref}}\right)-\frac{1}{T}\right)
\end{equation}

A: For your specific problem:

*

*use pairs of \left( and \right) to get brackets that automatically adapt their size to the contents. If you are not satisfied with the automatically assigned size (like here: both pairs of brackets will get the same size, although being nested), you can manually adjust the size by using \big(, \bigg(, \Big( or \Bigg(, respectively.

Other comments:

*

*use the \exp command instead of \texttt{exp}

*you probably want to have "ref" typed as text, not as math symbol. Use \mathrm for that

*it is better to post a Minimal Working Example, that doesn't include things not necessery to reproduce the problem. In your case, you can drop all the packages.

Your code:
\documentclass{report}

\begin{document}

\begin{equation}
k(T)=k^0\exp\Bigg(\frac{E}{R}\left(\frac{1}{T_{\mathrm{ref}}}\right)-\frac{1}{T}\Bigg)
\end{equation}

\end{document}

A: You have to size the parentheses yourself (maybe with \left and \right).
Here I present the formula in four different styles, comparing to the original one.
\documentclass[11pt,a4paper]{report}
\usepackage{amsmath}

\let\exp\relax % undefine it
\DeclareMathOperator{\exp}{\mathtt{exp}}

\begin{document}

\begin{align} % for several examples
k(T) &= k^0\exp(\frac{E}{R}(\frac{1}{T_{\mathrm{ref}}})-\frac{1}{T}) \\
k(T) &= k^0\exp\left(\frac{E}{R}\left(\frac{1}{T_{\mathrm{ref}}}\right)-\frac{1}{T}\right) \\
k(T) &= k^0\exp\Bigl(\frac{E}{R}\Bigl(\frac{1}{T_{\mathrm{ref}}}\Bigr)-\frac{1}{T}\Bigr) \\
k(T) &= k^0\exp\biggl(\frac{E}{R}\biggl(\frac{1}{T_{\mathrm{ref}}}\biggr)-\frac{1}{T}\biggr) \\
k(T) &= k^0\exp\biggl(\frac{E}{R}\Bigl(\,\frac{1}{T_{\mathrm{ref}}}\,\Bigr)-\frac{1}{T}\biggr)
\end{align}

\end{document}

The first is your input, clearly not acceptable. Number 2 shows \left and \right, which add unwanted spaces (compare with number 4, where the sizes are the same).
Number 3 and number 4 use the same size for all parentheses; choose one style and be consistent. The last one uses different size for the inner and the outer parentheses.
Note the redefinition of \exp: \texttt{exp} is wrong to begin with, because it would give italic in a theorem statement.
On the other hand, I'd use the standard \exp. Redefining it will ensure that when you change your mind you'll not need to chase the document for \mathttt{exp} or the like, but just remove or modify the redefinition.

On the other hand, the inner parentheses seem redundant, in this particular case. Again, I propose four different styles, in addition to the "non sized" style.
\documentclass[11pt,a4paper]{report}
\usepackage{amsmath}

\let\exp\relax % undefine it
\DeclareMathOperator{\exp}{\mathtt{exp}}

\begin{document}

\begin{align} % for several examples
k(T) &= k^0\exp(\frac{E}{R}\frac{1}{T_{\mathrm{ref}}}-\frac{1}{T}) \\
k(T) &= k^0\exp\left(\frac{E}{R}\frac{1}{T_{\mathrm{ref}}}-\frac{1}{T}\right) \\
k(T) &= k^0\exp\Bigl(\frac{E}{R}\frac{1}{T_{\mathrm{ref}}}-\frac{1}{T}\Bigr) \\
k(T) &= k^0\exp\biggl(\frac{E}{R}\frac{1}{T_{\mathrm{ref}}}-\frac{1}{T}\biggr) \\
k(T) &= k^0\exp\biggl(\frac{E}{R}\,\frac{1}{T_{\mathrm{ref}}}-\frac{1}{T}\biggr)
\end{align}

\end{document}


text:
Q: Excel VBA that searches by header name not column I need a VBA macro that does the below:
This part works fine, I want it to make a new column on sheet1 and name it header name then color it.
Columns("P:P").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("P1").Select
ActiveCell.FormulaR1C1 = "Header Name"
Range("P1").Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .Color = 15773696
    .TintAndShade = 0
    .PatternTintAndShade = 0
End With

This part however I would like to look for the header name on sheet2 not just the column C (since sometimes the column locations can change)
Range("P2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[8],Sheet2!C[-15]:C[-14],2,FALSE)"
Range("P2").Select
Selection.AutoFill Destination:=Range("P2:P" & Cells(Rows.Count, "X").End(xlUp).Row)

so basically this is what I want it to do:
on sheet 1 make a new column in P and name it "header name" then I want it to do a vlook up for column x (header 2) on sheet 1 (by name if able) and compare it to sheet2 column a (header 02) and give me the matching information in column B (header 3)
I have used this vlookup =VLOOKUP(X2,Sheet2!A:B,2,FALSE) but I want them to be header names not x,a,b and to search the entire sheet to find the header names.

*

*Column X name: Header 2

*Column A name: Header 02

*Column B name: Header 3

*Column P name: Header Name

A: Hmm, somehow feels hard to give this away, this is my precious baby for doing the job.
But all I can do is thank stack overflow and all of the community for all they have done, so here goes:
NOTE! I use Dictionaries. To make Dictionaries work, in VBA editor goto Tools > References. In the pop up scroll down to "Microsoft Scripting Runtime" and check the box and click OK.
Option Base 1

Sub TransferData()

    Dim Data()         As Variant
    Dim dataSheet      As String
    Dim resultSheet   As String
    Dim headingIndexes As New Dictionary

    dataSheet = "Data"
    dataStartCell = "A1"
    resultSheet = "Result"
    Data() = Sheets(dataSheet).Range(dataStartCell).CurrentRegion.Value

    Call GetHeadingIndexes(Data(), headingIndexes)
    Call Transfer(Data(), headingIndexes, resultSheet)

End Sub

Sub GetHeadingIndexes(ByRef Data() As Variant, ByRef headingIndexes As Dictionary)

    'Creates a dictionary with key-value pairs
    '
    'Creates a dictionary structure with key-value pairs resembling a table:
    '             [Column Heading] | [Column Index]
    '            "Actual/Forecast" | 1
    '                      "Brand" | 2
    ' "Division/ Line of Business" | 3
    '
    'Now it is easy and quick to find the column index based on column heading.

    Dim i As Integer

    For i = 1 To UBound(Data(), 2)
        headingIndexes.Add Data(1, i), i     'Make key-value pairs out of column heading and column index
    Next i

End Sub

Sub Transfer(ByRef Data() As Variant, ByRef headingIndexes As Dictionary, resultSheet As String)

    Application.ScreenUpdating = False

    Dim resultColumnHeading As String
    Dim resultSheetColumnNumber As Integer
    Dim dataColumnNumber As Integer
    Dim row As Integer

    'Loop through columns in result sheet. Assumes you have 16 columns
    For resultSheetColumnNumber = 1 To 16

        'Find the correct column in Data()
        resultColumnHeading = resultSheet.Cells(1, resultSheetColumnNumber)
        dataColumnNumber = headingIndexes(resultColumnHeading)

        For row = 2 To UBound(Data(), 1)

            'Transfer data from Data() array to the cell in resultSheet
            'Note, referencing each cell like this is really slow, it is better to create a resultArray similar to the data array (called Data() in this example). However, explaining all the nuances would take a one hour phone call, and gets far from the question at hand)
            resultSheet.Cells(row, resultSheetColumnNumber) = Data(row, dataColumnNumber)

        Next row

    Next resultSheetColumnNumber

    Application.ScreenUpdating = True

End Sub

A: It might work if you change this:
ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[8],Sheet2!C[-15]:C[-14],2,FALSE)"

to:
ActiveCell.Formula = "=vlookup(X" & ActiveCell.row & ",Sheet2!A:B,2,0)"

But that being said, be careful with ActiveCell and .Select.  You may want to check out How to Avoid Using Select in VBA Macros
EDIT:
I've amended/added to the code to take into consideration your need for flexibility with regards to where the columns of data are located.
Sub test3()
    'use the Header2sheet1column variable to hold the column number that "Header 2" is found in on sheet 1
    Dim Header2sheet1column As Long
        'search for "Header 2" across row 1 of sheet1 and remember the column number
        Header2sheet1column = Application.Match("Header 2", ThisWorkbook.Sheets("Sheet1").Range("$1:$1"), 0)
    'use the Header2sheet2column variable to hold the column number that "Header 2" is found in on sheet 2
    Dim Header2sheet2column As Long
        'search for "Header 2" across row 1 of sheet2 and remember the column number
        Header2sheet2column = Application.Match("Header 2", ThisWorkbook.Sheets("Sheet2").Range("$1:$1"), 0)
    'use the lookuprange variable to hold the range on sheet2 that will be used in the vlookup formula
    Dim lookuprange As Range

    'using With just so I don't have to type ThisWorkbook.Sheets("Sheet2") a bajillion times in the next couple lines
    With ThisWorkbook.Sheets("Sheet2")
        'set lookuprange variable - will start at column that "Header 2" is found on sheet 2 and will go to last row/column of the sheet
        'having extra columns at the end of your vlookup formula isn't going to hurt. the
        Set lookuprange = .Range(.Cells(1, Header2sheet2column), .Cells(.Rows.Count, .Columns.Count))
        'put formula into Cell P2 on sheet1
        ThisWorkbook.Sheets("Sheet1").Range("P2").Formula = "=vlookup(" & ThisWorkbook.Sheets("Sheet1").Cells(2, Header2sheet1column).Address(RowAbsolute:=False) & ",Sheet2!" _
                                                         & lookuprange.Address & "," _
                                                        & Header2sheet2column & ",0)"
    End With

    'using With again just so I don't have to type ThisWorkbook.Sheets("Sheet1") a bajillion times in the next couple lines
    With ThisWorkbook.Sheets("Sheet1")
    'fill formula in column P down to the row that the column
        .Range("P2").AutoFill Destination:=.Range("P2:P" & .Cells(.Rows.Count, Header2sheet1column).End(xlUp).Row)
    End With

End Sub

A: You'd be better off using named ranges that are created using the headers for each column.  Then your vlookup could just refer to the names rather than the cell references.
To get an idea how to do this start recording a macro then choose your columns and Insert - Names - Create.  You can adapt the macro to recreate the names every time your spreadsheet changes.  The vlookups won't need to be changed because they will point to the named ranges wherever they are.

A: I'm far from a VBA expert. Two things in VBA plagued me for a long time until recently.

*

*"Number Stored as Text" error

*Find column by first row 'Name' not 'Column Letter'

I use this in a macro to copy & reorder columns in a new sheet:
    Sub ColumnReorder()
    '**********************************************************
    'Paste this macro into the Workbook of each new "Employee_List_Weekly_Update"
    'Functionality:
    '1. Column order in the "Employee_List_Weekly_Update" worksheet changes fairly often.
    '   The macro will find each column by header name,
    '   select that column and copy it to the new sheet.
    '2. The macro also converts "Employee ID#" to a number,
    '   removing the "Number saved as Text" error.
    '**********************************************************
    'Create new sheet
        Sheets.Add.Name = "Roster_Columns_Reordered"

    'Repeat for each column or range - For each new section change Dim letter
    'Find Column in "Employee_List_Weekly_Update" - Copy it - Paste it in "Roster_Columns_Reordered" - Employee ID#
        Dim a As Integer
        Sheets("Employee_List_Weekly_Update").Select
        Set rngData = Range("A1").CurrentRegion
        a = Application.WorksheetFunction.Match("Employee ID#", Range("A1:BB1"), 0)
        Columns(a).Select
        Selection.Copy

        Sheets("Roster_Columns_Reordered").Select
        Range("A1").Select
        ActiveSheet.Paste
    'Use TextToColumns to convert "Number Stored as Text "
        Selection.TextToColumns _
          Destination:=Range("A:A"), _
          DataType:=xlDelimited

    'Find Column in "Employee_List_Weekly_Update" - Copy it - Paste it in "Roster_Columns_Reordered" - Name
        Dim b As Integer
        Sheets("Employee_List_Weekly_Update").Select
        Set rngData = Range("A1").CurrentRegion
        b = Application.WorksheetFunction.Match("Name", Range("A1:BB1"), 0)
        Columns(b).Select
        Selection.Copy

        Sheets("Roster_Columns_Reordered").Select
        Range("B1").Select
        ActiveSheet.Paste

    'Go to "Roster_Columns_Reordered" - Add AutoFilter - Freeze Top Row
        Rows("1:1").Select
        Selection.AutoFilter
        With ActiveWindow
          .SplitColumn = 2
          .SplitRow = 1
        End With
        Rows("2:2").Select
        ActiveWindow.FreezePanes = True
        Range("A1").Select

    End Sub


text:
Q: How to handle success and fail in redux How can I handle error when I am inserting in redux? My code es:
async newGroup(item: Item) {
    const newGroup = new GenericEntity(null, item.text, item.textMultiLanguage);
    this.store.dispatch(new RequestAddWorkstationGroup(newGroup));
    this.messageNotify.open(this.translate.instant('common.created_ok'), 'X', true, true, 3000, 'end', 'top', true, 'success');
  }

I want to show a notify message when element was inserted correctly, and show another message when element was error when user try to insert the element.
Is there a way to handle error using store-redux?

A: Finally I get it. We must set the handling error in effects, actions, reducers files.
In actions, I have to add:
export class CategoryFailed implements Action {

      static readonly TYPE = 'CATEGORY_FAILED';
      readonly type = CategoryFailed.TYPE;
      constructor(public category: GenericEntity) { }
    }

export class RequestCategoryFailed implements Action {

      static readonly TYPE = 'REQUEST_CATEGORY_FAILED';
      readonly type = RequestCategoryFailed.TYPE;
      constructor(public category: GenericEntity) { }
    }

In reducers:
case CategoryFailed.TYPE: {
      return { ...state, categories: state.categories.map(it => it.id === action.category.id ? it : it) };
    }

......TYPE:
    case RequestCategoryFailed.TYPE:
    default: { return { ...state }; }

In Effects:
@Effect() requestCategoryGroup: Observable<Action> = this.actions.pipe(
    ofType<RequestCategoryGroup>(RequestCategoryGroup.TYPE),
    mergeMap((category) =>
      from(this.Service.category(category.category)).pipe(
        map(() => new category(category.category)),
          catchError((error) => {
            const message = JSON.parse(error.response);
            this.dialogsService.alert(this.translate.instant('common.cannot_modify'), message.Title);
            return of(new CategoryFailed(category.category));
          }))));


text:
Q: Box2D + LibGDX pong, all bodies "stuck" I am probably missing something simple, not sure what. I am just practicing and re-creating Pong to see how it would go.
I have this:
package com.gibbo.pong;

enter code here
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.World;

public class GameScreen implements Screen {

    // Object instances
    Pong pong;
    Paddle paddle;
    Walls wall;
    Ball ball;
    OrthographicCamera cam;
    public static World world;
    Box2DDebugRenderer debug;

    // Booleans for paddles
    private boolean playerOne = false;
    private boolean playerTwo = false;

    // Booleans for walls
    private boolean wallTop = false;
    private boolean wallBottom = false;

    // Fields for the balls
    private boolean ballExists = false;
    private int ballTotal;

    //Array to hold ball objects
    Ball[] ballArray = new Ball[3];

    // GameScreen default constructor
    public GameScreen(Pong pong) {
        this.pong = pong;

        // Initiate the camera
        cam = new OrthographicCamera(20f, 14f);
        cam.position.set(10f, 7f, 0);

        // Initiate the world, no gravity
        world = new World(new Vector2(0, -10), true);

        // Initiate the renderer
        debug = new Box2DDebugRenderer();

        // Initiate the paddle
        paddle = new Paddle();

        //Initiate the walls
        wall = new Walls();

        //Initiate the ball
        ball = new Ball();

    }

    public void render(float delta) {
        // Clear the screen and fill it black
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

        // Update the camera
        cam.update();

        // Render the debug lines
        debug.render(world, cam.combined);

        // Check if paddles exist, if not create them
        if (!playerOne) {
            paddle.createPaddle(1, 7);
            playerOne = true;
            System.out.println("Creating player ones paddle");
        }
        if (!playerTwo) {
            paddle.createPaddle(19, 7);
            playerTwo = true;
            System.out.println("Creating player twos paddle");
        }

        //Check if walls exist, if not create them
        if(!wallBottom){
            wall.createWalls(0, 0.1f);
            wallBottom = true;
            System.out.println("Creating top wall");
        }
        if(!wallTop){
            wall.createWalls(0, 13f);
            wallTop = true;
            System.out.println("Creating bottom wall");
        }

        //Checks if ball exists
        if(!ballExists){
            ball.createBall(10f, 7f);
            ballExists = true;
            if(ballTotal == 0){
            System.out.println("Creating ball number 1");
            ballTotal += 1;
            }else{
                System.out.println("Creating ball number "+ballTotal + 1);
            }
        }
        if(ball.ballBody.getPosition().x < 0){
            System.out.println("Player twos point");
            ball.destroyBall();
        }

        boolean test = true;
        if(test){
        ball.ballBody.setLinearVelocity(-10, 0);
        System.out.println("Does this work?");
        }

        // Simulate the world with frame rate
        // Keep at bottom of render when possible
        world.step(1 / 60, 6, 2);
    }

I am using 3 other classes, one for balls, one for wall and one for paddles. Mainly to practice how to get them working together, passing arguments etc etc. Everything wrote here is a mix of tutorials from LibGDX site and the C++ box2d manual.
This is my ball class:
package com.gibbo.pong;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.World;

public class Ball {

    //Instance of the world
    World world;

    //Body for the ball
    Body ballBody;

    //Fixture for the ball
    Fixture ballFixture;

    public void createBall(float posX, float posY){
        //Define a body for the ball
        BodyDef ballBodyDef = new BodyDef();
        ballBodyDef.type = BodyType.DynamicBody;
        ballBodyDef.position.set(posX, posY);

        //Define a shape for the ball
        CircleShape ballShape = new CircleShape();
        ballShape.setRadius(0.50f);

        //Define a fixture for the ball
        FixtureDef ballFixtureDef = new FixtureDef();
        ballFixtureDef.shape = ballShape;
        ballFixtureDef.density = 1;

        //Create a ball
        ballBody = GameScreen.world.createBody(ballBodyDef);
        ballFixture = ballBody.createFixture(ballFixtureDef);

        ballShape.dispose();

        ballBody.setLinearVelocity(-10, 0.1f);

    }

Fairly straight forward, can easily be implemented inside the GameScreen class but for the sake of practice and tidyness, I went with this. I have tried setting the LinearVelocity here and in the GameScreen of the ball, I was trying to simulate what would happen if the ball hit the paddle, how it would react and if the method to destroy a ball off screen would work.
But for some reason, everything is just "stuck". As if everything is static. I even tried creating balls in an Object Array so I could do balls[0].setxxxx but that just went all funny.
Would I need to do create a constructor for my ball and other classes? Are my paddles, walls and ball just getting continuously rendered and forced to remain at the same position?
Regarding the random if statement with a print method in it, was just testing to see if that method was even being reached, so forced it to be run via the use of that.
Any spot my fail here?
Thanks in advance.

A: Shoot me, turns out that integer division is terrible.
I had to change:
world.step(1/60, 6, 2)

to:
world.step(1f/60f, 6, 2)

Wow that was annoying, yet so simple lol.


text:
Q: What does the Master Key in Parse Cloud? Could somebody explain me in brief that what does the master key within Parse Cloud Code?
Is it possible that a recently implemented CC function (which uses the master key) can change the behavior of other non Cloud Code functions?
As an instance, you have a properly working solution which lets to the current user to add other PFUser objects into a relation and delete them if needed. Until this point you don't need the master key because you writing the PFUser currentUser with the current user. Later you create another type of user relation where you want to write another PFUser object, now this time you need to use master key, because without this the currentUser won't be able to write another PFUser objects. Therefore you create a Cloud Code file to handle this issue and give legitimacy to the actual currentUser for writing other users. Now everything is working fine, we don't get an error when the actual user wants to write other user objects. However something happened. When currentUser tries to delete data from his first PFRelation (that was also worked before the new cc function) he gets the same error ..user must be authenticated via logIn or signUp that we got before we first tried to write an other user.
I guess since we using the master key it will override the existing/original security options
and we need to implement it for every other function. Am i right? If yes, how should i deal with this? Or is it possible to just set different restrictions inside the main.js cc file, and every "old" function will work in the same way plus the new one which using master key?
I would really appreciate any information about the topic, because it's a huge black hole for me.

A: The master key overrides all security, such as ACL or Class-based permissions.  It is like the "root" password.
You should invoke it only when needed, because all methods for the current request after it is enabled with Parse.Cloud.useMasterKey(); will use the master key.
You can selectively use it by passing options to the individual query/save/etc methods.
query.find({ useMasterKey: true }).then(function(results) { // ...

object.save(null, { useMasterKey: true }).then( // ...


text:
Q: How do I get the current editor from a QTableView? Is there a way of getting the editor (a QLineEdit instance) while the editing is in progress?

A: The delegate creates the editing widget, but does not store it and the view does not give access to it (presumably because it is not persistent).
So you will have to subclass QStyledItemDelegate and reimplement createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const to store a copy of the returned pointer.  Then you can provide access to the editor through the delegate.
AFAIK you cannot create multiple editors at once in a single view, and delegate sharing across views is discouraged, so holding the last created editor should be sufficient.  I would also create a private slot that nulls the pointer and connect it to the destroyed signal of the created editor - so you know it is always valid.


text:
Q: imagemagick converted images are grey in our current workflow we are using ImageMagick 6.7 to convert tif images to jp2000 and using bookviewer to display the jp2000 pictures, however the converted images always are more grey in color than the tif files, I have tried imageMagick's type option parameter TrueColor and colorspace sRGB together and seperately in the commandline and it still did not fix the issue. here's the command I'm using to convert in batch:
    mogrify -format jp2 -colorspace sRGB -type TrueColor -path {file}

here's the verbose information of the tif file info,
Format: TIFF (Tagged Image File Format)
  Class: DirectClass
  Geometry: 3416x4488+0+0
  Resolution: 400x400
  Print size: 8.54x11.22
  Units: PixelsPerInch
  Type: Bilevel
  Base type: Bilevel
  Endianess: LSB
  Colorspace: RGB
  Depth: 1-bit
  Channel depth:
    gray: 1-bit
  Channel statistics:
    Gray:
      min: 0 (0)
      max: 1 (1)
      mean: 0.762666 (0.762666)
      standard deviation: 0.425449 (0.425449)
      kurtosis: -0.475339
      skewness: -1.23477
  Colors: 2
  Histogram:
   3638570: (  0,  0,  0) #000000 black
  11692438: (255,255,255) #FFFFFF white
  Rendering intent: Undefined
  Interlace: None
  Background color: white
  Border color: rgb(223,223,223)
  Matte color: grey74
  Transparent color: black
  Compose: Over
  Page geometry: 3416x4488+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: None
  Orientation: TopLeft
  Properties:
    comment: 0030\0060\00001890.tif
    date:create: 2018-12-18T11:09:35-05:00
    date:modify: 2018-12-18T11:09:35-05:00
    signature: 2e4752f9eed1faeea038a7f33c562901502146ecdced65d2955751e549614fb2
    tiff:artist: The Crowley Company
    tiff:endian: lsb
    tiff:photometric: min-is-white
    tiff:rows-per-strip: 19
    tiff:software: Kofax standard Multi-Page TIFF Storage Filter v3.03.000
    tiff:timestamp: 2011:05:06 23:45:16
  Artifacts:
    verbose: true
  Tainted: False
  Filesize: 1.917MBB
  Number pixels: 15.33MB
  Pixels per second: 102.2MB
  User time: 0.070u
  Elapsed time: 0:01.150
  Version: ImageMagick 6.7.2-7 2017-03-22 Q16 http://www.imagemagick.org

and here's the converted jp2 file info
Image: 101083016_00009_00004_00119.jp2
  Format: JP2 (JPEG-2000 File Format Syntax)
  Class: DirectClass
  Geometry: 3379x4443+0+0
  Resolution: 72x72
  Print size: 46.9306x61.7083
  Units: Undefined
  Type: Bilevel
  Base type: Bilevel
  Endianess: Undefined
  Colorspace: RGB
  Depth: 2/1-bit
  Channel depth:
    gray: 1-bit
  Channel statistics:
    Gray:
      min: 0 (0)
      max: 3 (1)
      mean: 2.69697 (0.898989)
      standard deviation: 0.904028 (0.301343)
      kurtosis: 5.01231
      skewness: -2.64808
  Colors: 2
  Histogram:
   1516462: (  0,  0,  0) #000000 black
  13496435: (255,255,255) #FFFFFF white
  Rendering intent: Undefined
  Interlace: None
  Background color: white
  Border color: rgb(223,223,223)
  Matte color: grey74
  Transparent color: black
  Compose: Over
  Page geometry: 3379x4443+0+0
  Dispose: Undefined
  Iterations: 0
  Compression: JPEG2000
  Orientation: Undefined
  Properties:
    date:create: 2019-04-04T17:33:24-04:00
    date:modify: 2019-04-04T17:33:24-04:00
    signature: c5a16ea080389f3909f1ca87c4d0cc752b87af8c9fd24ad1a222b94904bf6950
  Profiles:
    Profile-icc: 394 bytes
      Restricted ICC profile describing sRGB-grey
  Artifacts:
    verbose: true
  Tainted: False
  Filesize: 364KBB
  Number pixels: 15.01MB
  Pixels per second: 7.082MB
  User time: 1.000u
  Elapsed time: 0:03.120
  Version: ImageMagick 6.7.2-7 2017-03-22 Q16 http://www.imagemagick.org

can anyone point out to me how I can keep the jp2 color white or which options I should use to prevent the converted jp2000 coming out grey? thanks!


text:
Q: Can we have more than one cfg file in hibernate? I am new to hibernate.I have a question please help me.
Can we have a more than one hibernate.cfg.xml file in one web-app?
If yes,then please explain.
Thanks in advance

A: Yes, you can.
Whenever you are creating the session factory, you can specify which configuration file you want to use and create as many SessionFactory objects as needed:
SessionFactory sessionFactory1 = new  Configuration().configure("ConfigFile_1.cfg.xml").buildSessionFactory();

See an example here


text:
Q: `collectstatic` error when deploying Django app to heroku While deploying my Django app to heroku, but colletstatic method seems to throw lots of errors. I've tried several solutions posted online but none worked. By the way, I'm using whitenoise for serving my static files.
Counting objects: 77, done.
Delta compression using up to 12 threads.
Compressing objects: 100% (74/74), done.
Writing objects: 100% (77/77), 351.57 KiB | 0 bytes/s, done.
Total 77 (delta 27), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.6.1
remote: -----> Installing pip
remote: -----> Installing requirements with pip
remote:        Collecting Django==1.11.1 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 1))
remote:          Downloading Django-1.11.1-py2.py3-none-any.whl (6.9MB)
remote:        Collecting gunicorn==19.7.1 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 2))
remote:          Downloading gunicorn-19.7.1-py2.py3-none-any.whl (111kB)
remote:        Collecting whitenoise==3.3.0 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 3))
remote:          Downloading whitenoise-3.3.0-py2.py3-none-any.whl
remote:        Collecting psycopg2==2.7.1 (from -r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 4))
remote:          Downloading psycopg2-2.7.1-cp36-cp36m-manylinux1_x86_64.whl (2.7MB)
remote:        Collecting pytz (from Django==1.11.1->-r /tmp/build_d86f80f6593040bde7f9cb90828051e6/requirements.txt (line 1))
remote:          Downloading pytz-2017.2-py2.py3-none-any.whl (484kB)
remote:        Installing collected packages: pytz, Django, gunicorn, whitenoise, psycopg2
remote:        Successfully installed Django-1.11.1 gunicorn-19.7.1 psycopg2-2.7.1 pytz-2017.2 whitenoise-3.3.0
remote:
remote: -----> $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 22, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
remote:            self.execute(*args, **cmd_options)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
remote:            output = self.handle(*args, **options)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle
remote:            collected = self.collect()
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect
remote:            for path, storage in finder.list(self.ignore_patterns):
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 112, in list
remote:            for path in utils.get_files(storage, ignore_patterns):
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files
remote:            directories, files = storage.listdir(location)
remote:          File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 397, in listdir
remote:            for entry in os.listdir(path):
remote:        FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_d86f80f6593040bde7f9cb90828051e6/Nostradamus/static'
remote:
remote:  !     Error while running '$ python manage.py collectstatic --noinput'.
remote:        See traceback above for details.
remote:
remote:        You may need to update application code to resolve this error.
remote:        Or, you can disable collectstatic for this application:
remote:
remote:           $ heroku config:set DISABLE_COLLECTSTATIC=1
remote:
remote:        https://devcenter.heroku.com/articles/django-assets
remote:
remote: ****** Collectstatic environment variables:
remote:
remote:        CPLUS_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include:
remote:        EXPORT_PATH=/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/bin/../export
remote:        SOURCE_VERSION=438c510c80b83b0d88b66ca02b9c8563e930b185
remote:        PROFILE_PATH=/tmp/build_d86f80f6593040bde7f9cb90828051e6/.profile.d/python.sh
remote:        DEBUG_COLLECTSTATIC=0
remote:        BUILDPACK_LOG_FILE=/dev/fd/3
remote:        LIBRARY_PATH=/app/.heroku/vendor/lib:/app/.heroku/python/lib:
remote:        CACHE_DIR=/app/tmp/cache
remote:        PYTHONUNBUFFERED=1
remote:        PYHONHOME=/tmp/build_d86f80f6593040bde7f9cb90828051e6/.heroku/python
remote:        LD_LIBRARY_PATH=/app/.heroku/vendor/lib:/app/.heroku/python/lib:
remote:        BIN_DIR=/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/bin
remote:        DYNO=run.7199
remote:        PATH=/app/.heroku/python/bin:/app/.heroku/vendor/bin::/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/tmp/codon/vendor/bin:/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/vendor/:/app/tmp/buildpacks/779a8bbfbbe7e1b715476c0b23fc63a2103b3e4131eda558669aba8fb5e6e05682419376144189b29beb5dee6d7626b4d3385edb0954bffea6c67d8cf622fd51/vendor/pip-pop
remote:        RECOMMENDED_PYTHON_VERSION=python-2.7.13
remote:        C_INCLUDE_PATH=/app/.heroku/vendor/include:/app/.heroku/python/include:
remote:        PWD=/tmp/build_d86f80f6593040bde7f9cb90828051e6
remote:        BPLOG_PREFIX=buildpack.python
remote:        LANG=en_US.UTF-8
remote:        STACK=heroku-16
remote:        SHLVL=3
remote:        REQUEST_ID=27f7a88e-8898-45ab-b6ef-d7792fdb0a7a
remote:        HOME=/app
remote:        PYTHONPATH=/tmp/build_d86f80f6593040bde7f9cb90828051e6/
remote:        BUILD_DIR=/tmp/build_d86f80f6593040bde7f9cb90828051e6
remote:        WARNINGS_LOG=/tmp/tmp.3UgKi9FCcP
remote:        PKG_CONFIG_PATH=/app/.heroku/vendor/lib/pkgconfig:/app/.heroku/vendor/lib/pkgconfig:/app/.heroku/vendor/lib/pkg-config:/app/.heroku/python/lib/pkg-config:
remote:        _=/usr/bin/env
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to habibam.
remote:
To https://git.heroku.com/habibam.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/habibam.git'

A: It's looking in the directory Nostradamus/static and throwing an error because that directory doesn't exist.
If that directory does exist locally then the problem might be that it's empty and so git doesn't track it. The simple solution to that is to create an empty file called .keep (or anything you like, it doesn't matter what it's called) in that directory which will cause git to "see" it.


text:
Q: java.lang.assertionError: expected "updated" but was "value" i am having three methods in my test case. 1.add 2.update
while i am updating i am using the following code in my test case
@Test
    @Rollback(true)
    public void testUpdateCoupon() {
        CouponDO couponDO = getCoupon();
        try {
            couponDAOImpl.addCoupon(couponDO);
            couponDO.setType(2);
            couponDAOImpl.addCoupon(couponDO);
            couponDAOImpl.getCoupon(couponDO.getDiscountId());
            couponDAOImpl.updateCoupon(couponDO);
            Assert.assertEquals("Coupon updated", couponDO.getType());
        } catch (CrafartDataException cdExp) {
            cdExp.printStackTrace();
            Assert.fail();
        }
    }

but it shows an error java.lang.assertionError: expected  but was<2>(

A: From code it seems that you are checking equality for Coupon updated and 2, as per the code you are setting type equal to 2. If you're using enum then you can use String value of enum for 2, else you will need to use 2 instead of Coupon updated.


text:
Q: Implement bootstrap pagination in webgrid I want to style my Webgrid pagination with bootstrap but cant find any good way.
I found this package https://www.nuget.org/packages/WebGridBootstrapPagination/
but I have no idea to use it after installing it.
Here is a part of my webgrid
@model IEnumerable<AnalyticConfig.Models.User>
@{
  var grid = new WebGrid(Model, ajaxUpdateContainerId: "ajaxgrid",    ajaxUpdateCallback: "webgrid", rowsPerPage: 5);
  grid.Pager(WebGridPagerModes.All);
}

    @grid.GetHtml(
    tableStyle: "table table-striped table-list table-hover",
    columns: grid.Columns(
                grid.Column(canSort: false, style: "col-md-2", format:
                @<text>

                </text>),
                grid.Column(null, null, style:"hidecol", format: @<input type="hidden" id="in_ID" value="@item.Id" />),
                grid.Column("SchoolUnit", "Skolenhet", style: "col-md-2", format:
                @<text>
                    @item.SchoolUnit
                    @Html.DropDownList("in_unit", new SelectList(ViewBag.schoolUnitList, "Text", "Value", @item.SchoolUnit), new { @class = "form-control modify" })
                </text>),
                grid.Column("Name", "Namn", style: "col-md-2", format:
                 @<text>
                    @item.Name
                    <input type="text" id="in_name" value="@item.Name" class="form-control modify" />
                </text>)

    )

If you know how to use the package or know any other ways please let me know.

A: My solution. No custom css or html added for webgrid pagination
$("tfoot a").addClass('btn btn-default'); // add bootstrap buttons

// add active bootstrap button
$("tfoot td")
  .contents()
  .filter(function () {
      if (this.nodeType === 3 && this.length > 1) {
          return this.nodeType
      }
  })
  .wrap('');

Result


text:
Q: ¿Cómo pausar un video al cerrar una modal y reproducirlo automáticamente con Bootstrap 4? espero me puedan ayudar!
Tengo el siguiente modal:

Maestría en Educación y
            Docencia online

          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            ×
          </button>

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

La linea que abre el modal dice #videoModal
Pero me doy cuenta que al abrir el modal no reproduce automáticamente el video, y al cerrar la modal lo sigue reproduciendo. Quiero que haga lo contrario, al abrir la modal reproduzca el video automáticamente y al cerrarlo que el video pare.

A: gracias por sus comentarios. Ya pude resolverlo!  quedo de la siguiente manera:


text:
Q: Ordering while Splitting and Appending the same column vertically in Spark I have a Dataframe like below,
+--------+--------+-------------+
|key     |colname1|column3      |
+--------+--------+-------------+
|   key1 |     2  |         23  |
|   key2 |     4  |         11  |
+--------+--------+-------------+

I want to split a column and do some operation on one of the dataframe and append the column
Before any operation on df1:
 df1                      df2
+--------+--------+      -------------+
|key     |colname1|      |column3      |
+--------+--------+      +-------------+
|   key1 |     2  |      |         23  |
|   key2 |     4  |      |         11  |
+--------+--------+      |-------------+

After an operation on df1 (Operation is colname1*2):
 df1                      df2
+--------+--------+      -------------+
|key     |colname1|      |column3      |
+--------+--------+      +-------------+
|   key1 |     4  |      |         23  |
|   key2 |     8  |      |         11  |
+--------+--------+      |-------------+

If I append the df2  back to df1 does Spark gaurentees that the sequence stays the same? if not, Is there any way I can achieve this?
Expected df:
+--------+--------+-------------+
|key     |colname1|column3      |
+--------+--------+-------------+
|   key1 |     4  |         23  |
|   key2 |     8  |         11  |
+--------+--------+-------------+

A: Spark does not guarantee that the sequence will stay the same, As data is partitioned across workers and depending on the transformation & action applied over the dataframe data could shuffle.
To perform above task splitting is not required.
//Input CSV
key,c1,c2
key1,2,23
key2,4,11

val df = spark.read.option("header", "true").csv("split_data.csv")
val mdf = df.withColumn("c1", col("c1") * 2)
mdf.show(10)
+----+---+---+
| key| c1| c2|
+----+---+---+
|key1|4.0| 23|
|key2|8.0| 11|
+----+---+---+

However, if still split is required then a join operation has to be performed using a key.
val df1 = df.select("key", "c1").withColumn("c1", col("c1") * 2)
val df2 = df.select("key", "c2")
val df3 = df1.join(df2 , "key")
df3.show(10)
+----+---+---+
| key| c1| c2|
+----+---+---+
|key1|4.0| 23|
|key2|8.0| 11|
+----+---+---+

Generally, Join operation is a little heavy, so the optimized way to do this would be the first approach.


text:
Q: Maximum allowed size of OpenReadStream What is the maximum allowed size of OpenReadStream? Right now, using 10MB. But I believe there has to be a certain cap. Can it take GB?

A: The maxAllowedSize parameter of OpenReadStream can be used to specify a larger size if required up to a maximum supported size of 2 GB
NOTE: The 2 GB framework file size limit only applies to ASP.NET Core 5.0. In ASP.NET Core 6.0 or later, the framework doesn't limit the maximum file size.
By default, files no larger than 512,000 bytes (500 KB) in size are allowed to be read before any further reads would result in an exception. This limit is present to prevent developers from accidentally reading large files in to memory.
await myFile.OpenReadStream().ReadAsync(buffers);

To specify your custom maximum file upload size, override the maxAllowedsize parameter as shown below:
// accept a file upto 307200 bytes (300kb) of size
await myFile.OpenReadStream(maxAllowedSize: 1024 * 300).ReadAsync(buffers);

EDIT:
I tested with a large file that was almost 2Gb of size and it was uploaded successfully.
Output:

Code example:
@page "/"
@using System.IO
@inject IWebHostEnvironment env

Blazor Server File Upload

@Message

<form @onsubmit="OnSubmit">
    <InputFile OnChange="OnInputFileChange"/>

    <button type="submit">Upload Selected File</button>
</form>

@code
{
    string Message = "No file selected";
    IBrowserFile selectedFile;

    private void OnInputFileChange(InputFileChangeEventArgs e)
    {
        selectedFile = e.GetMultipleFiles()[0];
        Message = $"{selectedFile.Name} ({selectedFile.Size} bytes) file selected";
        this.StateHasChanged();
    }

    private async void OnSubmit()
    {
        if (selectedFile != null)
        {
            Stream stream = selectedFile.OpenReadStream(maxAllowedSize: 1024 * 1024 * 1024 * 2);
            var path = $"{env.WebRootPath}\\{selectedFile.Name}";
            FileStream fs = File.Create(path);
            await stream.CopyToAsync(fs);
            stream.Close();
            fs.Close();
        }
        Message = $"{selectedFile.Name} ({selectedFile.Size} bytes) file uploaded on server";
        this.StateHasChanged();
    }
}


text:
Q: Spring Web Service SOAP is not working after integration with struts 2.3? Till now in my project the spring 3.0.1 and struts 2.0 was getting integrated and SOAP web service was working perfectly fine. But for some security reason I have migrated to struts 2.3 and for SOAP, I am using jars like spring-ws-all-1.5.9 and wsld4j-1.6.2.jar.
Still when I am calling my web service method I am getting exception like this:
HTTP Status 404 - There is no Action mapped for namespace [/] and action name [someServices] associated with context path [/someproject].
I tried to search the solution for this problem but I didn't get any. I finally migrated my jar to spring-ws-2.0.2.RELEASE-all.jar . Still I am getting the same problem. Please help me if anyone have any idea.


text:
Q: Showing the infinite product space of $[0, 1]^\omega$ is not compact with respect to the box topology using the notion of open covers I wish to show that the space $[0,1]^\omega$ in the box topology is not compact using the notion of open covers. The box topology has been a topic where I have struggled in my studies of topology, and I am having trouble trying to come up with an open cover that has no finite sub-cover for this space (I understand that there are other ways to prove that this space is not compact, but my goal is to use the notion of open covers and finite sub-covers in the proof). Any help would be greatly appreciated

A: HINT: For $n\in\omega$ let $x_n$ be the point
$$x_n(k)=\begin{cases}
1,&\text{if }k=n\\
0,&\text{otherwise}
\end{cases}$$
in $X=\square[0,1]^\omega$. For $n\in\omega$ let $F_n=\{x_k:k\ge n\}$, and let $U_n=X\setminus F_n$.

*

*Show that each $F_n$ is closed. You may find it helpful to begin by shoing that $F_0$ is a closed, discrete subset of $X$.

*Let $\mathscr{U}=\{U_n:n\in\omega\}$; show that $\mathscr{U}$ is an open cover of $X$ with no finite subcover.

A: Show that the product topology on $[0,1]^\omega$ is strictly coarser than the box topology. Since a compact topology is minimal among T2 topologies, the box topology is therefore not compact.


text:
Q: Make a newer version of the LDF-file work with an older version of the MDF-file Is it possible to combine a "newer version" of the LDF file with an older version of the MDF file and keep changes logged in the LDF? Lets assume there has been no log-backups in the time between as I guess that would make this truly impossible.
Steps:

*

*Database in full recovery mode

*Take a full backup

*Make some changes

*Detach database

*Make a filecopy of the LDF-file

*Restore from full backup in step 2

*Detach database

*Make a filecopy of the MDF-file

*Throw away the backup (important step)

*Delete the database

*Somehow make the MDF and LDF play together with the change made in
 step 3 still in place.

Just attaching the MDF and LDF gives an error:

The log scan number (38:195:41) passed to log scan database 'mic' is
  not valid.

I also tried a sequence of

*

*Create database

*Take database offline

*Replace the MDF and LDF files

*Bring online

*Do a log backup

*Drop database

*Create database with attach MDF-file only

*Make full backup

*Restore full backup (norecovery)

*Restore log-backup from Step 5

I have a vivid memory that this worked just fine for a while but then it did not any more.

The log in this backup set terminates at LSN 38000000021300001, which
  is too early to apply to the database. A more recent log backup that
  includes LSN 39000000006500001 can be restored.

A:
Is it possible to combine a "newer version" of the LDF file with an older version of the MDF file and keep changes logged in the LDF?

Assuming you want the database to be transactionally consistent, no.

Just attaching the MDF and LDF gives an error

In this case it's because the log number is no valid, for whatever reason given the database file's metadata. This is a symptom of the exact process you've described. In this case it'd just be better to use the create database to regenerate the log (or DBCC commands) because either way the database isn't going to be consistent which it already wouldn't be with the above steps you've outlined. Six of one, half dozen the other.