text:
Q: Maven3: replace transitive dependency of a direct dependency in dependency management I'm trying to fix the issue described here:
http://www.jayway.com/2013/04/12/solving-asm-conflicts-after-upgrading-to-groovy-2-1/
I have one dependency (Swagger->Jersey) that uses ASM 3.2 and one RestAssured that requires Groovy that requires ASM 4.0.
The idea is to replace the dependency to groovy to a dependency groovy-all which does not depend on ASM 4.0 (the class packages seems here but have been renamed using jarjar).
Is it possible to tell maven, in dependency management of a parent pom, that whenever a child depends on RestAssured, it will thus load transitively the groovy-all dependency instead of the normal groovy dependency?
Thanks

The aim is that all childs only need:
<dependency>
  <groupId>com.jayway.restassured</groupId>
  <artifactId>rest-assured</artifactId>
</dependency>

Which retrieve groovy-all instead of groovy
And not
<dependency>
  <groupId>com.jayway.restassured</groupId>
  <artifactId>rest-assured</artifactId>
</dependency>
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
</dependency>

A: No, it's not possible. However, you can use dependency <exclusions/>. Furthermore, as a top-level dependency, you can define groovy-all.
The article you linked to illustrates the following as a solution:
<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>1.8.0</version>
    <exclusions>
        <!-- Exclude Groovy because of classpath issue -->
        <exclusion>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
        </exclusion>
    </exclusions>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <!-- Needs to be the same version that
         REST Assured depends on -->
    <version>2.1.2</version>
    <scope>test</scope>
</dependency>


text:
Q: How to show that $\lim\limits_{x \to \infty} f'(x) = 0$ implies $\lim\limits_{x \to \infty} \frac{f(x)}{x} = 0$? I was trying to work out a problem I found online. Here is the problem statement:

Let $f(x)$ be continuously differentiable on $(0, \infty)$ and suppose $\lim\limits_{x \to \infty} f'(x) = 0$. Prove that $\lim\limits_{x \to \infty} \frac{f(x)}{x} = 0$.

(source: http://www.math.vt.edu/people/plinnell/Vtregional/E79/index.html)
The first idea that came to my mind was to show that for all $\epsilon > 0$, we have $|f(x)| < \epsilon|x|$ for sufficiently large $x$. (And I believe I could do this using the fact that $f'(x) \to 0$ as $x \to \infty$.)
However, I was wondering if there was a different (and nicer or cleverer) way. Here's an idea I had in mind:
If $f$ is bounded, then $\frac{f(x)}{x}$ clearly goes to zero. If $\lim\limits_{x \to \infty} f(x)$ is either $+\infty$ or $-\infty$, then we can apply l'Hôpital's rule (to get $\lim\limits_{x \to \infty} \frac{f(x)}{x} = \lim\limits_{x \to \infty} \frac{f'(x)}{1} = 0$).
However, I'm not sure what I could do in the remaining case (when $f$ is unbounded but oscillates like crazy). Is there a way to finish the proof from here?
Also, are there other ways of proving the given statement?

A: This is an immediate consequence of L'Hopital's rule. For example, below is said L'Hospital's rule, from Rudin's $ $ Principles of Mathematical Analysis, $ $  1976. Note that it requires only that the denominator $\to\infty,\:$ not also the numerator. For more see the Monthly papers cited here.
Remark $ $ L'Hospital's rule (LHR) is essentially a form of the Mean value Theorem (MVT) repacked into a form convenient for limit calculations. One can of course "unpackage" the MVT and apply it directly without any mention of LHR.  It's worth emphasizing that doing so does not really avoid L'Hopital's Rule (LHR) since it is precisely the proof of LHR, only specialized to a specfic function. Further, the proof of most special cases isn't much simpler than the proof of the general case of LHR. The raison d'être of the LHR abstraction is that it encapulates such applications of the Mean Value Theorem into a conveniently applicable form, so that one can easily reuse the proof by simply invoking the rule by name, not by value, i.e. not by repeating the whole proof ("inlining" it) every time one applies it!

A: You can do a proof by contradiction. If ${\displaystyle \lim_{x \rightarrow \infty} {f(x) \over x}}$ were not zero, then there is an $\epsilon > 0$ such that there are $x_1 < x_2 < ... \rightarrow \infty$ such that ${\displaystyle\bigg|{f(x_n) \over x_n}\bigg| > \epsilon}$. Then for $a \leq x_n$ one has
$$|f(x_n) - f(a)| \geq |f(x_n)| - |f(a)|$$
$$\geq \epsilon x_n - f(a)$$
By the mean value theorem, there is a $y_n$ between $a$ and $x_n$ such that
$$|f'(y_n)| = {|f(x_n) - f(a)| \over x_n - a}$$
$$\geq {\epsilon x_n - f(a) \over x_n - a}$$
Letting $n$ go to infinity this means for sufficiently large $n$ you have
$$|f'(y_n)| > {\epsilon \over 2}$$
Since each $y_n \geq a$ and $a$ is arbitrary, $f'(y)$ can't go to zero as $y$ goes to infinity.

A: let $f:\left[ a,+\infty \right[ \longrightarrow \mathbb{R}  $ differentiable suppose that  $\displaystyle \lim_{x\rightarrow +\infty} f'(x)=l \in \mathbb{R}$ prove that $\displaystyle \lim_{x\rightarrow +\infty} \dfrac{f(x)}{x}=l $
we will begin with the mean value theorem : for $ x > \max(0,a)  \ \exists c\in \left]a,x\right[ $ such that
    $$f(x)-f(a)=f'(c)(x-a)\implies \dfrac{\dfrac{f(x)}{x}-\dfrac{f(a)}{x}}{1-\dfrac{a}{x}}=f'(c)$$
    and because as $c\rightarrow +\infty$ , $x\rightarrow +\infty$ then we have:
    $$\lim_{c\rightarrow +\infty} f'(c)=\lim_{c\rightarrow +\infty }\dfrac{\dfrac{f(x)}{x}-\dfrac{f(a)}{x}}{1-\dfrac{a}{x}}\implies \lim_{c\rightarrow +\infty}\dfrac{\dfrac{f(x)}{x}-\dfrac{f(a)}{x}}{1-\dfrac{a}{x}}=l\implies \lim_{x\rightarrow +\infty}\dfrac{\dfrac{f(x)}{x}-\dfrac{f(a)}{x}}{1-\dfrac{a}{x}}=l$$
thus we have the desired result:
    $$\lim_{x\rightarrow +\infty} \dfrac{f(x)}{x}=l$$

A: Here's a proof that avoids L'Hôspital's rule (though you can certainly use it, as noted by Bill; basically, the condition on $f'(x)$ ensures that the function cannot oscillate like crazy).
Let $\epsilon\gt 0$. We want to show that there exists $N\gt 0$ such that if $x\gt N$, then
$$\left|\frac{f(x)}{x}\right| \lt\epsilon.$$
We know that there exists $M\gt 0$ such that $|f'(x)|\lt \frac{\epsilon}{2}$ for all $x\gt M$. By the Mean Value Theorem, if $x\gt M$, there exists $c\in (M,x)$ such that $f(x)-f(M)=f'(c)(x-M)$, so
$$|f(x)-f(M)| = |f'(c)|(x-M) \lt \left(\frac{\epsilon}{2}\right) x.$$
That is, for all $x\gt M$,
$$\left|\frac{f(x)}{x} - \frac{f(M)}{x}\right| \lt\frac{\epsilon}{2}.$$
As $x\to\infty$, we know $\frac{f(M)}{x}\to 0$ (since $f(M)$ is fixed). So there exists $N\gt M$ such that if $x\gt N$, then $\left|\frac{f(M)}{x}\right|\lt \frac{\epsilon}{2}$. Thus, if $x\gt N$, then
$$\left|\frac{f(x)}{x}\right| \leq \left|\frac{f(x)-f(M)}{x}\right| + \left|\frac{f(M)}{x}\right| \lt \frac{\epsilon}{2}+\frac{\epsilon}{2} = \epsilon,$$
which is what we needed to prove. QED

A: I'd start like this: for $x\geq 1$ we have
$${f(x)\over x}={f(1)\over x}+{1\over x}\int_1^x f^\prime(y)\, dy.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Subspace equipped with combinatorial structure? Given a vector space with tensor structure $V\otimes V\otimes V....\otimes V$, it is naturally (at least for us people doing many-body physics) to think that its subspaces are also equipped with some tenor structure.
Now could there be any possibility that vector space $V^{\otimes N^2}$ has a subspace equipped with a combinatorial structure instead of a tensor one, whose dimension is of order O(N!).
If there is, what shall be the proper mathematical structure between such two spaces? And how could that combinatorial structure naturally emerge from tensors?

A: Hint:
Let $V$ be an $n$-dim. vector space. Consider the tensor space $V^{\otimes k}$ and let $V_i$ be an $i$-dim. subspace of $V$ for $i=1,\ldots,n$. Put $V_n=V$.
If $k\geq n$, then $V_n\otimes V_{n-1}\otimes \ldots\otimes V_1$ has dimension $n!$.
If $k<n$, then $V_n\otimes V_{n-1}\otimes \ldots\otimes V_{n-k+1}$ has dimension $n\cdot (n-1)\cdot \ldots\cdot (n-k+1)$.


text:
Q: google drive api dont know where it saves the file but when fetched it shows the saved but not the others I used the google drive api to insert a text file...
Build Service
function buildService() {

$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = 'xxxx@developer.gserviceaccount.com';

if($_SERVER['HTTP_HOST'] == 'localhost')
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = 'xxxxxxxx-privatekey.p12';
else
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = $_SERVER['DOCUMENT_ROOT'].'/xxxxx-privatekey.p12';

  $key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
  $auth = new Google_AssertionCredentials(
      $SERVICE_ACCOUNT_EMAIL,
      array($DRIVE_SCOPE),
      $key);
  $client = new Google_Client();
  $client->setUseObjects(true);
  $client->setAssertionCredentials($auth);
  return new Google_DriveService($client);
}

Retrieve Files
function retrieveAllFiles($service) {
  $result = array();
  $pageToken = NULL;

  do {
    try {
      $parameters = array();
      if ($pageToken) {
        $parameters['pageToken'] = $pageToken;
      }
      $files = $service->files->listFiles($parameters);

      $result = array_merge($result, $files->getItems());
      $pageToken = $files->getNextPageToken();
    } catch (Exception $e) {
      print "An error occurred: " . $e->getMessage();
      $pageToken = NULL;
    }
  } while ($pageToken);
  return $result;
}

Creating an instance and inserting
$service = buildService();

$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');

$data = "contents";

$createdFile = $service->files->insert($file, array('data' => $data,'mimeType' =>'text/plain',));

print_r($createdFile);

echo '
------
';

Retrieving files
$ret = retrieveAllFiles($service);

echo '
';
print_r($ret);

*

*As in the fist call i insert a file...

*in the second call i am trying to list all files...

*when i try to list i could see only the inserted file but not the others which i could see in my drive by logging into docs.google.com. i am already having 6 files online

*as per the documentation i created service account with the private keys and the service account email.
so where will that file be store and how do i list all other files in the root of google drive?

A: You are inserting files in the application-owned account represented by the service account.
If you want to manage (insert/list/...) files in another domain user's Drive account, you'll have to perform Domain-wide delegation: https://developers.google.com/drive/delegation


text:
Q: scala: best wat to save csv coming from kafka to parquet format? I'm new to scala/java, so please bear with me.
I have a spark streaming and scala program that receives a csv file coming from kafka. I understand that what I get right now is a ReceiverInputDStream with plain lines (no schema yet).
I need to save the data I receive in parquet format in HDFS. I guess I could simply save the lines as they come in a parquet file (can I?).
But also I understand it's better to give some schema (columns and types) to the plain lines so parquet can convert the data to columnar format and achieve a better compression rate. Am I right?
So the question is, how do I convert my ReceiverInputDStream to something with a schema (column1 type1,... columnN typeN)? What object type is needed?
ANd then how do I save this new object to parquet?
Thank you.

A: If you happen to use Spark, you can do
spark.read.parquet(parquetPath).write.csv(newcsvPath)

Or you can use the same thing but Spark Streaming as a Kafka client

A: Answering myself, I was able to give format to the RDD and at the same time convert it to a dataframe with the following code
val viajesDF = splitRdd.map { case Array(s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18) =>
yellowSchema(s0, s1, s2, s3.toInt, s4.toDouble, s5.toFloat, s6.toFloat, s7.toString, s8.toString,
s9.toFloat, s10.toFloat, s11, s12.toDouble, s13.toDouble,
s14.toDouble, s15.toDouble, s16.toDouble, s17.toDouble, s18.toDouble)
}.toDF()

The schema is defined as a case class as follows in a different scala object
case class  yellowSchema (
                       vendor_id: String,
                       tpep_pickup_datetime: String,
                       tpep_dropoff_datetime: String,
                       passenger_count:  Long,
                       trip_distance: Double,
                       pickup_longitude: Float,
                       pickup_latitude: Float,
                       rate_code_id:  String,
                       store_and_fwd_flag:  String,
                       dropoff_longitude: Float,
                       dropoff_latitude: Float,
                       payment_type:  String,
                       fare_amount: Double,
                       extra: Double,
                       mta_tax: Double,
                       tip_amount: Double,
                       tolls_amount: Double,
                       improvement_surcharge: Double,
                       total_amount: Double
                     )

I finally write the DF to parquet this way:
viajesDateDF.write.mode(SaveMode.Append).parquet(parquetDest)


text:
Q: UI Testing with respect to a attribute value iOS/Swift I'm writing UI Tests for my application. I've an attribute named numberOfPhotos in PhotosViewController and it's value is set from another ViewController. Whenever numberOfPhotos is 2, only two photos should be displayed in my current PhotosViewController.
I was able to test if required number of images are visible or not but I'm not able to set numberOfPhotos from UITests class. Is there anyway I can set this value and proceed to tests.
Currents I'm editing the code to set value for numberOfPhotos and testing it. Is there anyway I can set this value from UITests class. Thanks.

A: They are different apps, that's why you can't set it directly. The UiTests use a test runner that runs your app. There is a way to do what you want using launchArguments.
From your tests:
let app = XCUIApplication()
app.launchArguments = XCUIApplication().launchArguments + ["UiTesting", "numberOfPhotos", "2"])
app.launch()

From your app:
var isUiTesting: Bool {
    return ProcessInfo.processInfo.arguments.contains("UiTesting")
}

Write some code in your controller to check the isUiTesting property and set the number of photos based on the next few launchArguments. You will have to do some parsing of the launch arguments.


text:
Q: Not serializable error for jenkins declarative pipeline I am trying to trigger my email promotion job from my pipeline which extracts the repo name from Jenkins messages. But not able to resolve the SerializableException error for this block. Any help is greatly appreciated.
post{
        success{
            script{
                @NonCPS
                //upstream_job_name = null
                def manager = manager.getLogMatcher('.*Obtained Jenkinsfile from git (.*)$')
                if(manager.matches()){
                    def gitMsg=manager.group(1)
                    gitrepo = "${gitMsg}"
                    echo gitrepo
                    def upstream_job_name = gitrepo.split("/")[4].replace(".git", "")
                    println upstream_job_name

                }
                build job: 'job-approval' , parameters: [[$class: 'StringParameterValue', name: 'upstream_job_name', value: upstream_job_name]]

            }
        }
    }

Below is the error messages i am receiving :
[Pipeline] // script
Error when executing success post condition:

java.io.NotSerializableException: java.util.regex.Matcher
      at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:926)
      at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
      at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
      at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
      at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)

A: You need to release manager immediately after using. More detail can find in this post
script{

    //upstream_job_name = null
    def manager = manager.getLogMatcher('.*Obtained Jenkinsfile from git (.*)$')
    if(manager.matches()){
        def gitMsg=manager.group(1)
        gitrepo = "${gitMsg}"
        echo gitrepo
        def upstream_job_name = gitrepo.split("/")[4].replace(".git", "")
        println upstream_job_name
    }
    manager = null

    build job: 'job-approval' ,
        parameters: [
            [$class: 'StringParameterValue', name: 'upstream_job_name', value: upstream_job_name]
        ]
}


text:
Q: Oracle.DataAccess.Client.OracleException ORA-01008: not all variables bound at Oracle.DataAccess.Client I've having this error and I can't explain it:

Oracle.DataAccess.Client.OracleException ORA-01008: not all variables
  bound at
  Oracle.DataAccess.Client.OracleException.HandleErrorHelper(Int32
  errCode, OracleConnection conn, IntPtr opsErrCtx, OpoSqlValCtx*
  pOpoSqlValCtx, Object src, String procedure, Boolean bCheck) at
  Oracle.DataAccess.Client.OracleCommand.ExecuteReader(Boolean requery,
  Boolean fillRequest, CommandBehavior behavior) at
  Oracle.DataAccess.Client.OracleCommand.ExecuteReader() at
  gestao.GestaoDefault.GeraSqlDataSourceDropDownDisciplinasSelectCommand(Int32
  selectValue) in
  c:\inetpub\MiniSites\inscricoes\gestao\Default.aspx.cs:line 501

My query:
SELECT DISTINCT
       cse.t_tbdiscip.cd_discip,
       cse.t_tbdiscip.ds_discip
  FROM cse.t_tbdiscip, cse.t_turma, cse.t_plandisc
 WHERE cse.t_plandisc.cd_curso = :CD_CURSO
   AND cse.t_turma.cd_curso = :CD_CURSO
   AND cse.t_plandisc.cd_activa = 'S'
   AND cse.t_turma.estado = 'S'
   AND cse.t_tbdiscip.cd_discip = cse.t_plandisc.cd_discip
   AND cse.t_tbdiscip.cd_discip = cse.t_turma.cd_discip
   AND cse.t_turma.cd_a_s_cur IS NOT NULL
   AND cse.t_turma.cd_lectivo = :CD_LECTIVO
 ORDER BY cse.t_tbdiscip.ds_discip

As you can see I have to vars to the query.
My code:
OracleConnection oracleSqlConnection = new OracleConnection(ConOracleString);
try
{
    // Just to see if any value is passed to the query
    LiteralMensagens.Text += String.Format("Curso : " + curso + "

");
    LiteralMensagens.Text += String.Format("Lectivo : " + lectivo + "

");
    LiteralMensagens.Text += String.Format("query : " + query + "

");

    oracleSqlConnection.Open();
    OracleCommand cmdOracle = new OracleCommand(query, oracleSqlConnection);
    cmdOracle.CommandType = CommandType.Text;

    cmdOracle.Parameters.Clear();
    cmdOracle.Parameters.Add(":CD_CURSO", OracleDbType.Decimal).Value = curso;
    cmdOracle.Parameters.Add(":CD_LECTIVO", OracleDbType.Varchar2).Value = lectivo;

    OracleDataReader oracleDataReader = cmdOracle.ExecuteReader();
    while (oracleDataReader.Read())
    {
        LiteralMensagens.Text += string.Format((String)oracleDataReader["DS_DISCIP"]);
    }
}
catch (Exception ex)
{

From my code I bound my vars.
From the Oracle DB:
CD_LECTIVO-  VARCHAR2(7)
CD_CURSO- NUMBER(4)
I've checked here and I think I'm using the correct types http://msdn.microsoft.com/en-us/library/yk72thhd.aspx
What can be wrong?

A: Problem solved...
Added this:
cmd.BindByName = true;

Found this reading this: similar issue on stackoverflow

A: You should change you code like this (omitting the ':' from the parameter name):
// ...
cmdOracle.Parameters.Add("CD_CURSO", OracleDbType.Decimal).Value = curso;
cmdOracle.Parameters.Add("CD_LECTIVO", OracleDbType.Varchar2).Value = lectivo;
//...

A: Still not working now something really strange... I'm bounding 2 vars, if I comment one of them and insert the value on the query (doesn't mather witch one) it works perfectly...
The cmdOracle.Parameters.Add is not accepting more than 1 value... Does this makes sense to anyone?
This works replacing ":CURSO" with a var on the query string:
String query = String.Format("SELECT DISTINCT CSE.T_TBDISCIP.CD_DISCIP, CSE.T_TBDISCIP.DS_DISCIP " +
"FROM CSE.T_TBDISCIP, CSE.T_TURMA, CSE.T_PLANDISC " +
"WHERE (CSE.T_PLANDISC.CD_CURSO = " + curso + ") " +
"AND (CSE.T_TURMA.CD_CURSO = " + curso + ") " +
"AND (CSE.T_PLANDISC.CD_ACTIVA='S') " +
"AND (CSE.T_TURMA.ESTADO='S') " +
"AND (CSE.T_TBDISCIP.CD_DISCIP=CSE.T_PLANDISC.CD_DISCIP) " +
"AND (CSE.T_TBDISCIP.CD_DISCIP=CSE.T_TURMA.CD_DISCIP) " +
"AND (CSE.T_TURMA.CD_A_S_CUR IS NOT NULL) " +
"AND (CSE.T_TURMA.CD_LECTIVO = :CD_LECTIVO) " +
"ORDER BY CSE.T_TBDISCIP.DS_DISCIP");


text:
Q: Why am I getting and "Image not found" error when converting pdf to html? I am using pdftohtml tool to convert pdfs to html using the following command:
pdftohtml -s -c SOURCE_FILE_NAME
which results in the following error:
dyld: Library not loaded: /usr/local/opt/openjpeg/lib/libopenjpeg.5.dylib
  Referenced from: /usr/local/bin/pdftohtml
  Reason: image not found
Trace/BPT trap: 5

I haven't managed to find outwhy this is happening thus far. Can anyone shed any light on this?


text:
Q: File path without domain name from wp_get_attachment_url() wp_get_attachment_url() process full file path like
http://example.com/wp-content/uploads/2014/12/aura.mp3

I want the url without http://example.com/
So, I want above example as wp-content/uploads/2014/12/aura.mp3 instead of http://example.com/wp-content/uploads/2014/12/aura.mp3. How to do it?

A: You can really easily explode it by / and then take the part with index 3. Example
$url = wp_get_attachment_url(id); //id is file's id
$urllocal = explode(site_url(), $url)[1]; //output local path

A: Here is the WordPress way using WordPress functions (avoid hacking):
$fullsize_path = get_attached_file( $attachment_id ); // Full path
$filename_only = basename( get_attached_file( $attachment_id ) ); // Just the file name

WordPress has tons of functions, so first try to find the function on the docs: https://developer.wordpress.org/reference/functions/get_attached_file/

A: You can use PHP's function explode.
Here is the code:
    <?php
         $image_url = wp_get_attachment_url( 9 ); //ID of your attachment
         $my_image_url = explode('/',$image_url,4);
         echo $my_image_url[3];
    ?>

A: You can implode your entire url on / and array_slice from the end, then implode it back in on /.
$url = wp_get_attachment_url($item->ID); //id is file's id
$url_relative = implode(array_slice(explode('/', $url),-3,3),'/');
//Returns: 2019/08/image.jpg

That way if your WordPress is on a subdomain or localhost or the images are on S3 it won't crash.


text:
Q: What is the Excel Formula to calculate based on consumption and rate I need help to come out with a solution for this:
Actually I want to calculate my electricity consumption. as the attached pic. the first consumption 0-200kwh, rate $0.218, for 201-300 consumption rate is $0.334, 301-600 rate is $0.516, 601-900 rate is $0.546.
I tried using :
=IF(F3<200, 0.218, IF(F3>200, 0.334, IF(F3>300, 0.516, IF(F3>600, 0.546, 0))))*F3

but get the wrong answer.
I also tried:
=VLOOKUP(F3, [Book2.xlsx]Sheet3!$A$2:$C$603, 3, 0)

but what I got are the total consumption(refer pic it sum up to 326kwhx0.516 =168.216).
I want to separate the kwh for the first 0-200, 201-300 and so on according to respective rate. How can I do that?

A: You're on the right track but you need to turn a few things around. Your formula:
=IF(F3<200,0.218,IF(F3>200,0.334,IF(F3>300,0.516,IF(F3>600,0.546,0))))*F3

Play it through for the value 350. You'll never get past the IF(F3>200 because 350 is greater than 200 and the rest of the formula won't be evaluated. So, change the comparison order from big number to small number.
=IF(F3<200,0.218,IF(F3>600,0.334,IF(F3>300,0.516,IF(F3>200,0.334,0))))*F3

As an alternative to nested IF() you may want to consider a lookup table sorted by the consumption threshold values. Use Vlookup with TRUE or 1 as the fourth parameter for an approximate lookup, which returns the result that is equal to or smaller than the lookup value.


text:
Q: Showing the hidden Winform I have two independent application. First application is called MSGAPP and other is called SCUForm.
I am controlling the the SCUForm through MSGAPP application by sending the Windows Messages. I can minimize, maximize the SCUForm application by sending the Windows Messages through MSGAPP. And I can also Hide the SCUForm. But when I hide the application, I am not able to show the form back.
what I should do to show it back.
I tried this.Show() but no use.
Am I missing some basics here?
Please guide me.
Thanks in advance.
-Harsha

A: If I remember well (I did it some year ago), you should try to use WM_SYSCOMMAND with SC_RESTORE.
Watch here.
You could find this and this useful, perhaps.


text:
Q: iCloud Drive takes forever to load I am trying to open open iCloud Drive from my browser and it is stuck at the loading stage:

Do you have any idea about how I can resolve this problem? I am using Google Chrome and my OS is Windows 10.


text:
Q: Why am I not getting the decrypted data when my input text size is less than 16 bytes using openssl EVP_OpenInit() api function? I am trying to encrypt and Decrypt file using EVP apis. I am getting correct result when size is greater or equal to 16 bytes only. Here is my codes for the above stated problem.
 #include <stdio.h>

    #include <stdlib.h>

    #include <openssl/evp.h>
    #include <openssl/pem.h>
    #include <openssl/rsa.h>
    #include <openssl/err.h>

    #include <arpa/inet.h>

    #if 1
    int do_evp_seal(FILE *rsa_pkey_file, FILE *in_file, FILE *out_file)
    {
        int retval = 0;
        RSA *rsa_pkey = NULL;
        EVP_PKEY *pkey = EVP_PKEY_new();
        EVP_CIPHER_CTX *ctx;
        ctx = EVP_CIPHER_CTX_new();
        unsigned char buffer[4096];
        unsigned char buffer_out[4096 + EVP_MAX_IV_LENGTH];
        //size_t len;
        int len_out;
        unsigned char *ek = NULL;
        int eklen=0;
        uint32_t eklen_n=0;
        unsigned char iv[EVP_MAX_IV_LENGTH];

        if (!PEM_read_RSA_PUBKEY(rsa_pkey_file, &rsa_pkey, NULL, NULL))
        {
            fprintf(stderr, "Error loading RSA Public Key File.\n");
            ERR_print_errors_fp(stderr);
            retval = 2;
            goto out;
        }

        if (!EVP_PKEY_assign_RSA(pkey, rsa_pkey))
        {
            fprintf(stderr, "EVP_PKEY_assign_RSA: failed.\n");
            retval = 3;
            goto out;
        }

        EVP_CIPHER_CTX_init(ctx);
        ek = malloc(EVP_PKEY_size(pkey));

        if (!EVP_SealInit(ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &pkey, 1))
        {
            fprintf(stderr, "EVP_SealInit: failed.\n");
            retval = 3;
            goto out_free;
        }

        /* First we write out the encrypted key length, then the encrypted key,
         * then the iv (the IV length is fixed by the cipher we have chosen).
         */

        eklen_n = htonl(eklen);
        if (fwrite(&eklen_n, sizeof eklen_n, 1, out_file) != 1)
        {
            perror("output file");
            retval = 5;
            goto out_free;
        }
        if (fwrite(ek, eklen, 1, out_file) != 1)
        {
            perror("output file");
            retval = 5;
            goto out_free;
        }
        if (fwrite(iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc()), 1, out_file) != 1)
        {
            perror("output file");
            retval = 5;
            goto out_free;
        }

        /* Now we process the input file and write the encrypted data to the
         * output file. */

        while (1)
        {
            int numlen = fread(buffer, 1, sizeof buffer, in_file);
            if (!EVP_SealUpdate(ctx, buffer_out, &len_out, buffer, numlen))
            {
                fprintf(stderr, "EVP_SealUpdate: failed.\n");
                retval = 3;
                goto out_free;
            }

            if (fwrite(buffer_out, len_out, 1, out_file) != 1)
            {
                perror("output file");
                retval = 5;
                goto out_free;
            }
            if (numlen < sizeof(buffer)) { // EOF
                break;
            }
        }

        if (ferror(in_file))
        {
            perror("input file");
            retval = 4;
            goto out_free;
        }

        if (!EVP_SealFinal(ctx, buffer_out, &len_out))
        {
            fprintf(stderr, "EVP_SealFinal: failed.\n");
            retval = 3;
            goto out_free;
        }

        if (fwrite(buffer_out, len_out, 1, out_file) != 1)
        {
            perror("output file");
            retval = 5;
            goto out_free;
        }

        out_free:
        EVP_PKEY_free(pkey);
        EVP_CIPHER_CTX_cleanup(ctx);
        free(ek);

        out:
        return retval;
    }
    #endif
    int main(int argc, char *argv[])
    {
        FILE *rsa_pkey_file,*ifp,*ofp;
        int rv;

        if (argc < 2)
        {
            fprintf(stderr, "Usage: %s <PEM RSA Public Key File>\n", argv[0]);
            exit(1);
        }

        rsa_pkey_file = fopen(argv[1], "rb");
        ifp = fopen(argv[2], "rb");
        ofp = fopen(argv[3], "wb");
        if (!rsa_pkey_file)
        {
            perror(argv[1]);
            fprintf(stderr, "Error loading PEM RSA Public Key File.\n");
            exit(2);
        }
        if (!ifp)
        {
            perror(argv[1]);
            fprintf(stderr, "Error loading input file.\n");
            exit(2);
        }
        if (!ofp)
        {
            perror(argv[1]);
            fprintf(stderr, "Error loading output file.\n");
            exit(2);
        }

        rv = do_evp_seal(rsa_pkey_file, ifp, ofp);

        fclose(rsa_pkey_file);
        fclose(ifp);
        fclose(ofp);
        return rv;
    }

Here is my code for decryption for the above stated problem. For size less than 16 bytes the decrypted file is empty. Although the code seems to be logically correct.
#include <stdio.h>
#include <stdlib.h>

#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/err.h>

#include <arpa/inet.h> /* For htonl() */

#if 1
int do_evp_unseal(FILE *rsa_pkey_file, FILE *in_file, FILE *out_file)
{
    int retval = 0;
    RSA *rsa_pkey = NULL;
    EVP_PKEY *pkey = EVP_PKEY_new();
    EVP_CIPHER_CTX *ctx;
    ctx = EVP_CIPHER_CTX_new();
    unsigned char buffer[4096];
    unsigned char buffer_out[4096 + EVP_MAX_IV_LENGTH];
    //size_t len;
    int len_out;
    unsigned char *ek;
    unsigned int eklen=0;
    uint32_t eklen_n=0;
    unsigned char iv[EVP_MAX_IV_LENGTH];

    if (!PEM_read_RSAPrivateKey(rsa_pkey_file, &rsa_pkey, NULL, NULL))
    {
        fprintf(stderr, "Error loading RSA Private Key File.\n");
        ERR_print_errors_fp(stderr);
        retval = 2;
        goto out;
    }

    if (!EVP_PKEY_assign_RSA(pkey, rsa_pkey))
    {
        fprintf(stderr, "EVP_PKEY_assign_RSA: failed.\n");
        retval = 3;
        goto out;
    }

    EVP_CIPHER_CTX_init(ctx);
    ek = malloc(EVP_PKEY_size(pkey));

    /* First need to fetch the encrypted key length, encrypted key and IV */

    if (fread(&eklen_n, sizeof eklen_n, 1, in_file) != 1)
    {
        perror("input file");
        retval = 4;
        goto out_free;
    }
    eklen = ntohl(eklen_n);
    if (eklen > EVP_PKEY_size(pkey))
    {
        fprintf(stderr, "Bad encrypted key length (%u > %d)\n", eklen,
            EVP_PKEY_size(pkey));
        retval = 4;
        goto out_free;
    }
    if (fread(ek, eklen, 1, in_file) != 1)
    {
        perror("input file");
        retval = 4;
        goto out_free;
    }
    if (fread(iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc()), 1, in_file) != 1)
    {
        perror("input file");
        retval = 4;
        goto out_free;
    }

    if (!EVP_OpenInit(ctx, EVP_aes_128_cbc(), ek, eklen, iv, pkey))
    {
        fprintf(stderr, "EVP_OpenInit: failed.\n");
        retval = 3;
        goto out_free;
    }

    while (1)
    {
        int numlen = fread(buffer, 1, sizeof buffer, in_file);
        if (!EVP_OpenUpdate(ctx, buffer_out, &len_out, buffer, numlen))
        {
            fprintf(stderr, "EVP_OpenUpdate: failed.\n");
            retval = 3;
            goto out_free;
        }

        if (fwrite(buffer_out, len_out, 1, out_file) != 1)
        {
            perror("output file");
            retval = 5;
            goto out_free;
        }
        if (numlen < sizeof(buffer)) { // EOF
            break;
        }
    }

    if (ferror(in_file))
    {
        perror("input file");
        retval = 4;
        goto out_free;
    }

    if (!EVP_OpenFinal(ctx, buffer_out, &len_out))
    {
        fprintf(stderr, "EVP_SealFinal: failed.\n");
        retval = 3;
        goto out_free;
    }

    if (fwrite(buffer_out, len_out, 1, out_file) != 1)
    {
        perror("output file");
        retval = 5;
        goto out_free;
    }

    out_free:
    EVP_PKEY_free(pkey);
    EVP_CIPHER_CTX_cleanup(ctx);
    free(ek);

    out:
    return retval;
}
#endif
int main(int argc, char *argv[])
{
    FILE *rsa_pkey_file,*ifp,*ofp;
    int rv;

    if (argc < 2)
    {
        fprintf(stderr, "Usage: %s <PEM RSA Private Key File>\n", argv[0]);
        exit(1);
    }

    rsa_pkey_file = fopen(argv[1], "rb");
    ifp = fopen(argv[2], "rb");
    ofp = fopen(argv[3], "wb");
    if (!rsa_pkey_file)
    {
        perror(argv[1]);
        fprintf(stderr, "Error loading PEM RSA Private Key File.\n");
        exit(2);
    }

    rv = do_evp_unseal(rsa_pkey_file, ifp, ofp);

    fclose(rsa_pkey_file);
    fclose(ifp);
    fclose(ofp);
    return rv;
}


text:
Q: Facing Error in positioning the Div on top of the screen Image
Hi,
I hope whoever reads this is in the best of health and spirit. I am facing some difficulties in positioning the divs. I want the suggestion box of highlighted div to be on top of the horizontal scroll.
I am working on React Js. I am adding my code down here. I really appreciate your help. Thanks

               <input class="provider-form" autocomplete="off" id="myAutocompleteID" type="text" name="searchValue" placeholder="" value="" style="margin-left: 0px;">

82232<input type="hidden" value="82232">

A: You may add z-index property to your element that you want to raise to top. In your screenshot I cannot tell whether it's in a frame or iframe. If it's in a frame, no matter what trick you do on CSS the element will not be rendered outside it's own frame. Another possible problem is that the element is cropped, in which case you may need to set overflow property.
Ref:

*

*https://developer.mozilla.org/en-US/docs/Web/CSS/z-index

*https://developer.mozilla.org/en-US/docs/Web/CSS/overflow


text:
Q: Using a username starting "##" at a bash prompt Some clown made me a sftp username that started with ##.  Now I don't know if the command is wrong or the ftp server isn't responding for certain.  Could someone please confirm for me that this should work using:
sftp "##Username@sftphostaddress"
Thank you

A: Yes, that should work... if your username really does start with ##. If it does, it would have to be the most bizarre username I've ever seen. In other words: are you sure this username is correct?


text:
Q: UITabBarControllerDelegate - Where to put the Code? I am writing an iPhone app with the following structure (created in storyboard)
UIView --> TabBarController --> 1.NavigationController --> UITableView --> UIView
                                2.NavigationController --> UITableView --> UIPageController --> UIView
                                3.NavigationController --> UIView
                                ...
                                7.NavigationController --> UIView

When a TabBarItem is clicked, I want the page to pop to the root view.
I know I need to implement a UITabBarControllerDelegate with the method:
- (void)tabController:(UITabBarController *)tabController didSelectViewController: (UIViewController *)viewController

I don't understand where to put this method and whether to make AppDelegate the UITabBarDelegate, or to make my customTabBarController class the delegate.
Also, where do I make the tabBarController.delegate = self call?
I'm a serious noob, please help :)

A: If your AppDelegate has the reference to the UITabBarController, then make that your delegate.


text:
Q: In Javascript, how can I perform a global replace on string with a variable inside '/' and '/g'? I want to perform a global replace of string using String.replace in Javascript.
In the documentation I read that I can do this with /g, i.e. for example;
var mystring = mystring.replace(/test/g, mystring);

and this will replace all occurrences inside mystring. No quotes for the expression.
But if I have a variable to find, how can I do this without quotes?
I've tried something like this:
var stringToFind = "test";

//first try
mystring = mystring.replace('/' + stringToFind + '/g', mystring);

//second try, not much sense at all
mystring = mystring.replace(/stringToFind/g, mystring);

but they don't work. Any ideas?

A: Regular expressions are much slower then string search. So, creating regex with escaped search string is not an optimal way. Even looping though the string would be faster, but I suggest using built-in pre-compiled methods.
Here is a fast and clean way of doing fast global string replace:
sMyString.split(sSearch).join(sReplace);

And that's it.

A: Thats a regular expression, not a string.  Use the constructor for a RegExp object to dynamically create a regex.
var r = new RegExp(stringToFind, 'g');
mystring.replace(r, 'some replacement text');

A: Try:
var stringToFind = "test";
mystring = mystring.replace(new RegExp(stringToFind, "g"), mystring);

A: var mystring = "hello world test world";
var find = "world";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "yay")); // alerts "hello yay test yay"

In case you need this into a function
  replaceGlobally(original, searchTxt, replaceTxt) {
    const regex = new RegExp(searchTxt, 'g');
    return original.replace(regex, replaceTxt) ;
  }

A: You can do using following method
see this function:
function SetValue()
{
    var txt1='This is a blacK table with BLack pen with bLack lady';
    alert(txt1);
    var txt2= txt1.replace(/black/gi,'green');
    alert(txt2);
}

syntax:

/search_string/{g|gi}

where

*

*g is global case-sensitive replacement

*gi is blobal case-insensitive replacement

You can check this JSBIN link
http://jsbin.com/nohuroboxa/edit?html,js,output

A: String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(RegExp.quote(replaceThis),"g");
   return this.replace(re, withThis);
};

RegExp.quote = function(str) {
     return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};

var aa = "qwerr.erer".replaceAll(".","A");
alert(aa);

silmiar post

A: You can use the following solution to perform a global replace on a string with a variable inside '/' and '/g':
myString.replace(new RegExp(strFind, 'g'), strReplace);

A: For regex, new RegExp(stringtofind, 'g');. BUT. If 'find' contains characters that are special in regex, they will have their regexy meaning. So if you tried to replace the '.' in 'abc.def' with 'x', you'd get 'xxxxxxx' — whoops.
If all you want is a simple string replacement, there is no need for regular expressions! Here is the plain string replace idiom:
mystring= mystring.split(stringtofind).join(replacementstring);

A: If you want variables interpolated, you need to use the RegExp object
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions
Example:
var str = "This is my name";
var replace = "i";
var re = new RegExp(replace, 'g')

str = str.replace(re, 'p');
alert(str);

A: Dynamic global replace
I came to this thread looking for a slightly more complex solution which isn't answered here. I've now found the answer so I'm going to post it in  case anyone else finds it useful.
I wanted to do a dynamic global replace, where the replacement strings are based on the original matches.
For example, to capitalise the first letter of all words (e.g. "cat sat mat" into "Cat Sat Mat") with a global find replace. Here's how to do that.
function capitaliseWords(aString) {
    // Global match for lowercase letters following a word boundary
    var letters = aString.match(/\b[a-z]/g), i, letterMatch;
    // Loop over all matched letters
    for( i = 0; i < letters.length; i++ ) {
        // Replace the matched letters with upper case versions
        letterMatch = new RegExp('\\b'+letters[i]); // EDIT - slight fix
        aString = aString.replace(letterMatch, letters[i].toUpperCase());
    }
    // Return our newly capitalised string
    return aString;
}

alert( capitaliseWords("cat sat mat") ); // Alerts "Cat Sat Mat"

A: WIth modern day linters, they prefer you to regEx literal, so rather than new RegExp it would just be `//
With an example:
'test'.replace(/ /gi, '_')

with the test you are looking to replace inside the regex or the /searchableText/ and then replace text in the second parameter. In my case I wanted to replace all spaces with underscores.

A: Can you use prototype.js? If so you could use String.gsub, like
var myStr = "a day in a life of a thing";
 var replace = "a";
 var resultString = myStr.gsub(replace, "g");
 // resultString will be "g day in g life of g thing"

It will also take regular expressions.  To me this is one of the more elegant ways to solve it. prototypejs gsub documentation


text:
Q: Why do pointer behave different in some cases when passed to a function? I have this code example and i can't figure out why sscanf works like intended in the example function but not in the main function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void example(char *seq){
    char wert;
    while(*seq){
        sscanf(seq,"%2x",&wert);
        fprintf(stdout,"%c",wert);
        seq+=2;
    }
}

int main() {
    char temp;
    char sentence []="1B2873313648";
    char *seq=sentence;
    example(seq);
    printf("\n");
    while(*seq){
        sscanf(seq,"%2x",&temp);
        fprintf(stdout,"%c",temp);
        seq+=2;
    }
}

A: The sscanf format specifier %x is expecting a pointer to unsigned int, not a pointer to char, so all bets are off due to undefined behaviour. Please take note of the compiler warnings. On my MSVC this code causes a crash.
This corrected code works.
#include <stdio.h>          // missing
#include <stdlib.h>
#include <string.h>

void example(char *seq){
    unsigned wert;
    while(*seq){
        sscanf(seq,"%2x",&wert);
        fprintf(stdout,"%02X ",wert);
        seq+=2;
        //fflush(stdin);
    }
}

int main() {
    unsigned temp;
    char sentence []="1B2873313648";
    char *seq=sentence;
    example(seq);
    printf("\n");
    while(*seq){
        sscanf(seq,"%2x",&temp);
        fprintf(stdout,"%02X ",temp);
        seq+=2;
        //fflush(stdin);
    }
}

Program output:

1B 28 73 31 36 48
1B 28 73 31 36 48


text:
Q: connecting to remote broker and consumer result with no messages I have the following flow:
1- producer running in a linux computer that supposed to write messages to a remote broker
2- remote broker and consumer (both of them in a windows 10 machine)
my problem is whenever I run the producer my consumer doesn't get any messages. the producer is connected to the broker but no messages is being received by the consumer however when I tested them (producer, consumer and broker) both in the same machine they worked fine.
All of the components are running in the same network, and the firewall is deactivated in the windows machine.
Producer.py
from kafka import KafkaProducer
producer = KafkaProducer(bootstrap_servers='windowIP:9092')
producer.send('testSite', b'Hello, World!')

consumer
kafka-console-consumer.bat --bootstrap-server windowIP:9092 --topic testSite --from-beginning

server.config
listeners=PLAINTEXT://windowsIP:9092
advertised.listeners=PLAINTEXT://windowsIP:9092
zookeeper.connect= windowsIP:2181

consumer.config
bootstrap.servers=windowsIP:9092,windowsIP:9093


text:
Q: How to blend two sound files in JYTHON? So, I am really new to programming, I am currently learning on JYTHON, I am required to blend two different sounds and turn them into one sound. I really tried my best to code this so far but whenever I try to play the result, the empty sound file does not play any sound :<
So could you please guys take a look at my code and tell me what did I do wrong?
def blendTwoSounds():
  sound1 = pickAFile()
  antelope = makeSound(sound1)
  sound2 = pickAFile()
  rabbit = makeSound(sound2)
  jackalope = makeEmptySoundBySeconds(9)
  for index in range(0,20000):
    rabbitSample = getSampleValueAt(sound2, index)
    setSampleValueAt(jackalope, index , sound2Sample)
  for index in range(0,20000):
    sound2Sample = getSampleValueAt(sound2,index+20000)
    sound1Sample = getSampleValueAt(sound1, 20000)
    newSample =10.0*sound2Sample + 10.9*sound2Sample
    setSampleValueAt(jackalope, index+20000, newSample)
  for index in range(20000,40000):
    sound1Sample = getSampleValueAt(sound1,index)
    setSampleValueAt(jackalope, index+20000,sound1Sample)
  play(jackalope)

I even tried this code, sounds work but the end result (jackalope) does not have any sound in it. Take a look at it too please and see which one is better to use
def blendTwoSounds():
  path1 = pickAFile()
  antelope = makeSound(path1)
  path2 = pickAFile()
  rabbit = makeSound(path2)
  jackalope = makeEmptySoundBySeconds(9)
  for index in range(0,20000):
    asample = getSampleValueAt(asample,index)
    rsample = getSampleValueAt(rsample,index)
    newSample = 9.5*asample+9.5*rsample
    setSampleValueAt(jackalope,index,newSample)
    for index in range(20000,40000):
      rsample = getSamleValueAt(rsample,index)
      setSampleValueAt(jackalope,index+20000,rsample)
  play(jackalope)
  return(jackalope)

So it seems like I got this code to work but can I make it better? Any suggestions would really help.
def blendTwoSounds():
  path1 = pickAFile()
  a = makeSound(path1)
  path2 = pickAFile()
  r = makeSound(path2)
  jackalope = makeEmptySoundBySeconds(3)
  for index in range(0,20000):
    rSample = getSampleValueAt(r,index)
    setSampleValueAt(jackalope,index,rSample)
  for index in range(0,20000):
      rSample = getSampleValueAt(r,index+20000)
      aSample = getSampleValueAt(a,index)
      newSample = 7.5*rSample + 7.5*aSample
      setSampleValueAt(jackalope,index+20000,newSample)
  for index in range(20000,40000):
      aSample = getSampleValueAt(a,index)
      setSampleValueAt(jackalope,index+20000,aSample)
  play(jackalope)
  folder=setMediaPath()
  writeSoundTo(jackalope,folder+'blending.wav')
  return jackalope
blendTwoSounds()


text:
Q: Uniformly Most Powerful test for normal distribution Let ${Y_1,...,Y_n}$ be independent random variables and $Y_i$~$N(\beta x_i, 1)$ where $x_1,...,x_n$ are fixed known constants, and $\beta$ is an unknown parameter.
I'm trying to find a uniformly most powerful level $\alpha$ test for
$$H_0: \beta=0 \quad \text{vs} \quad H_1:\beta>0$$
First I found the Likelihood Ratio statistic
$$\begin{align}\frac{L(0)}{L(\beta_1)}&=\frac{e^{-\frac{1}{2}\sum^n_{i=1}(y_i-0x_i)^2}}{e^{-\frac{1}{2}\sum^n_{i=1}(y_i-\beta_1x_i)^2}}
\\[15pt] & = \frac{e^{-\frac{1}{2}\sum^n y_i^2}}{e^{-\frac{1}{2}(y_i^2-2y_i\beta_1x_i+\beta_1^2x_i^2)}}
\\[15pt] & =e^{\beta_1\sum^n y_ix_i-\frac{1}{2}\beta_1^2\sum^nx_i^2}\end{align}$$
Then the rejection region of the LRT is
$$e^{\beta_1\sum^n y_ix_i-\frac{1}{2}\beta_1^2\sum^nx_i^2} \le k \\$$
Now moving the constants to the right side
$$\\[15pt]\Rightarrow\beta_1\sum^n y_ix_i-\frac{1}{2}\beta_1^2\sum^nx_i^2 \;\le\; \text{ln}(k)$$
$$\\[15pt]\Rightarrow\sum^ny_ix_i \;\le\; \frac{\text{ln}(k)+1/2\sum^n\beta_1^2x_i^2}{\beta_1}$$
Here is where I get confused because I'm not sure what to leave on the left side. From what I have read I'm supposed to move constants to the right. I'm thinking that only $y_i$'s should remain on the left. Since $x_i$'s are constants shouldn't I move it?
The steps that follow to find the rejection region by using the distribution of the left of the inequality, then equating to a quantile, puzzle me because of the $x_i$
I'm not even sure I'm going about this correctly or if there are more straight forward methods.

A: First of all, you lose a sign:
\begin{align}\frac{L(0)}{L(\beta_1)}&=\frac{e^{-\frac{1}{2}\sum^n y_i^2}}{e^{-\frac{1}{2}(y_i^2-2y_i\beta_1x_i+\beta_1^2x_i^2)}}
\\[15pt] & =e^{-\beta_1\sum^n y_ix_i+\frac{1}{2}\beta_1^2\sum^nx_i^2}\end{align}
The rejection region looks as
$$
-\beta_1\sum_{i=1}^n y_ix_i+\frac{1}{2}\beta_1^2\sum_{i=1}^nx_i^2 \leq k.
$$
Since only $y_i$ are random variables here, and $k$ should be found so that test has level $\alpha$, simplify rejection region:
$$
\sum_{i=1}^n y_ix_i \geq k_0.
$$
Let us find $k_0$ from type 1 error $\alpha_1=\alpha$. We need to know the distribution of l.h.s. under $H_0$:
$$
\sum_{i=1}^n y_ix_i \sim N\bigl(0, \sum_{i=1}^n x_i^2\bigr).
$$
Then
$$
\alpha_1=\mathbb P_{H_0}\left(\sum_{i=1}^n y_ix_i \geq k_0\right)=P_{H_0}\left(\frac{\sum_{i=1}^n y_ix_i}{\sqrt{\sum_{i=1}^n x_i^2}} \geq \frac{k_0}{\sqrt{\sum_{i=1}^n x_i^2}}\right)=1-\Phi\left(\frac{k_0}{\sqrt{\sum_{i=1}^n x_i^2}}\right)=\alpha
$$
if
$$
\frac{k_0}{\sqrt{\sum_{i=1}^n x_i^2}} = z_{1-\alpha},\ \quad k_0 = z_{1-\alpha}\cdot\sqrt{\sum_{i=1}^n x_i^2},
$$
where $z_{1-\alpha}$ is the $(1-\alpha)^{\text{th}}$ quantile of standard normal distribution.
Finally, we've got rejection region of level $\alpha$ test for testing $H_0$ under the simple alternative $H_1: \beta=\beta_1>0$:
$$
\sum_{i=1}^n y_ix_i \geq z_{1-\alpha}\cdot\sqrt{\sum_{i=1}^n x_i^2}.
$$
Since this test
1) is the most powerful test for any $\beta_1>0$,
2) does not depend on $\beta_1>0$ at all
is is the uniformly most powerful test for testing $H_0$ under the composite alternative $H_1: \beta>0$.


text:
Q: Why use flags+bitmasks rather than a series of booleans? Given a case where I have an object that may be in one or more true/false states, I've always been a little fuzzy on why programmers frequently use flags+bitmasks instead of just using several boolean values.
It's all over the .NET framework.  Not sure if this is the best example, but the .NET framework has the following:
public enum AnchorStyles
{
    None = 0,
    Top = 1,
    Bottom = 2,
    Left = 4,
    Right = 8
}

So given an anchor style, we can use bitmasks to figure out which of the states are selected.  However, it seems like you could accomplish the same thing with an AnchorStyle class/struct with bool properties defined for each possible value, or an array of individual enum values.
Of course the main reason for my question is that I'm wondering if I should follow a similar practice with my own code.
So, why use this approach?

*

*Less memory consumption?  (it doesn't seem like it would consume less than an array/struct of bools)

*Better stack/heap performance than a struct or array?

*Faster compare operations?  Faster value addition/removal?

*More convenient for the developer who wrote it?

A: Among other things, its easier to add new bit meanings to a bitfield than to add new boolean values to a class.  Its also easier to copy a bitfield from one instance to another than a series of booleans.

A: It can also make Methods clearer. Imagine a Method with 10 bools vs. 1 Bitmask.

A: Actually, it can have a better performance, mainly if your enum derives from an byte.
In that extreme case, each enum value would be represented by a byte, containing all the combinations, up to 256. Having so many possible combinations with booleans would lead to 256 bytes.
But, even then, I don't think that is the real reason. The reason I prefer those is the power C# gives me to handle those enums. I can add several values with a single expression. I can remove them also. I can even compare several values at once with a single expression using the enum. With booleans, code can become, let's say, more verbose.

A: From a domain Model perspective, it just models reality better in some situations.  If you have three booleans like AccountIsInDefault and IsPreferredCustomer and RequiresSalesTaxState, then it doesnn't make sense to add them to a single Flags decorated enumeration, cause they are not three distinct values for the same domain model element.
But if you have a set of booleans like:
 [Flags] enum AccountStatus {AccountIsInDefault=1,
         AccountOverdue=2 and AccountFrozen=4}

or
  [Flags] enum CargoState {ExceedsWeightLimit=1,
         ContainsDangerousCargo=2, IsFlammableCargo=4,
         ContainsRadioactive=8}

Then it is useful to be able to store the total state of the Account, (or the cargo) in ONE variable... that represents ONE Domain Element whose value can represent any possible combination of states.

A: It was traditionally a way of reducing memory usage. So, yes, its quite obsolete in C# :-)
As a programming technique, it may be obsolete in today's systems, and you'd be quite alright to use an array of bools, but...
It is fast to compare values stored as a bitmask. Use the AND and OR logic operators and compare the resulting 2 ints.
It uses considerably less memory. Putting all 4 of your example values in a bitmask would use half a byte. Using an array of bools, most likely would use a few bytes for the array object plus a long word for each bool. If you have to store a million values, you'll see exactly why a bitmask version is superior.
It is easier to manage, you only have to deal with a single integer value, whereas an array of bools would store quite differently in, say a database.
And, because of the memory layout, much faster in every aspect than an array. It's nearly  as fast as using a single 32-bit integer. We all know that is as fast as you can get for operations on data.

A: I would suggest never using enum flags unless you are dealing with some pretty serious memory limitations (not likely). You should always write code optimized for maintenance.
Having several boolean properties makes it easier to read and understand the code, change the values, and provide Intellisense comments not to mention reduce the likelihood of bugs. If necessary, you can always use an enum flag field internally, just make sure you expose the setting/getting of the values with boolean properties.

A: Raymond Chen has a blog post on this subject.

Sure, bitfields save data memory, but
  you have to balance it against the
  cost in code size, debuggability, and
  reduced multithreading.

As others have said, its time is largely past.  It's tempting to still do it, cause bit fiddling is fun and cool-looking, but it's no longer more efficient, it has serious drawbacks in terms of maintenance, it doesn't play nicely with databases, and unless you're working in an embedded world, you have enough memory.

A: *

*Easy setting multiple flags in any order.

*Easy to save and get a serie of 0101011 to the database.

A: *

*Space efficiency - 1 bit

*Time efficiency - bit comparisons are handled quickly by hardware.

*Language independence - where the data may be handled by a number of different programs you don't need to worry about the implementation of booleans across different languages/platforms.

Most of the time, these are not worth the tradeoff in terms of maintance. However, there are times when it is useful:

*

*Network protocols - there will be a big saving in reduced size of messages

*Legacy software - once I had to add some information for tracing into some legacy software.

Cost to modify the header: millions of dollars and years of effort.
Cost to shoehorn the information into 2 bytes in the header that weren't being used: 0.
Of course, there was the additional cost in the code that accessed and manipulated this information, but these were done by functions anyways so once you had the accessors defined it was no less maintainable than using Booleans.

A: I have seen answers like Time efficiency and compatibility. those are The Reasons, but I do not think it is explained why these are sometime necessary in times like ours. from all answers and experience of chatting with other engineers I have seen it pictured as some sort of quirky old time way of doing things that should just die because new way to do things are better.
Yes, in very rare case you may want to do it the "old way" for performance sake like if you have the classic million times loop. but I say that is the wrong perspective of putting things.
While it is true that you should NOT care at all and use whatever C# language throws at you as the new right-way™ to do things (enforced by some fancy AI code analysis slaping you whenever you do not meet their code style), you should understand deeply that low level strategies aren't there randomly and even more, it is in many cases the only way to solve things when you have no help from a fancy framework. your OS, drivers, and even more the .NET itself(especially the garbage collector) are built using bitfields and transactional instructions. your CPU instruction set itself is a very complex bitfield, so JIT compilers will encode their output using complex bit processing and few hardcoded bitfields so that the CPU can execute them correctly.
When we talk about performance things have a much larger impact than people imagine, today more then ever especially when you start considering multicores.
when multicore systems started to become more common all CPU manufacturer started to mitigate the issues of SMP with the addition of dedicated transactional memory access instructions  while these were made specifically to mitigate the near impossible task to make multiple CPUs to cooperate at kernel level without a huge drop in perfomrance it actually provides additional benefits like an OS independent way to boost low level part of most programs. basically your program can use CPU assisted instructions to perform memory changes to integers sized memory locations, that is, a read-modify-write where the "modify" part can be anything you want but most common patterns are a combination of set/clear/increment.
usually the CPU simply monitors if there is any other CPU accessing the same address location and if a contention happens it usually stops the operation to be committed to memory and signals the event to the application within the same instruction. this seems trivial task but superscaler CPU (each core has multiple ALUs allowing instruction parallelism), multi-level cache (some private to each core, some shared on a cluster of CPU) and Non-Uniform-Memory-Access systems (check threadripper CPU) makes things difficult to keep coherent, luckily the smartest people in the world work to boost performance and keep all these things happening correctly. todays CPU have a large amount of transistor dedicated to this task so that caches and our read-modify-write transactions work correctly.
C# allows you to use the most common transactional memory access patterns using Interlocked class (it is only a limited set for example a very useful clear mask and increment is missing, but you can always use CompareExchange instead which gets very close to the same performance).
To achieve the same result using a array of booleans you must use some sort of lock and in case of contention the lock is several orders of magnitude less permorming compared to the atomic instructions.
here are some examples of highly appreciated HW assisted transaction access using bitfields which would require a completely different strategy without them of course these are not part of C# scope:

*

*assume a DMA peripheral that has a set of DMA channels, let say 20 (but any number up to the maximum number of bits of the interlock integer will do). When any peripheral's interrupt that might execute at any time, including your beloved OS and from any core of your 32-core latest gen wants a DMA channel  you want to allocate a DMA channel (assign it to the peripheral) and use it. a bitfield will cover all those requirements and will use just a dozen of instructions to perform the allocation, which are inlineable within the requesting code. basically you cannot go faster then this and your code is just few functions, basically we delegate the hard part to the HW to solve the problem, constraints: bitfield only

*assume a peripheral that to perform its duty requires some working space in normal RAM memory. for example assume a high speed I/O peripheral that uses scatter-gather DMA, in short it uses a fixed-size block of RAM populated with the description (btw the descriptor is itself made of bitfields) of the next transfer and chained one to each other creating a FIFO queue of transfers in RAM. the application prepares the descriptors first and then it chains with the tail of the current transfers without ever pausing the controller (not even disabling the interrupts). the allocation/deallocation of such descriptors can be made using bitfield and transactional instructions so when it is shared between diffent CPUs and between the driver interrupt and the kernel all will still work without conflicts. one usage case would be the kernel allocates atomically descriptors without stopping or disabling interrupts and without additional locks (the bitfield itself is the lock), the interrupt deallocates when the transfer completes.
most old strategies were to preallocate the resources and force the application to free after usage.
If you ever need to use multitask on steriods C# allows you to use either Threads + Interlocked, but lately C# introduced lightweight Tasks, guess how it is made? transactional memory access using Interlocked class. So you likely do not need to reinvent the wheel any of the low level part is already covered and well engineered.
so the idea is, let smart people (not me, I am a common developer like you) solve the hard part for you and just enjoy general purpose computing platform like C#. if you still see some remnants of these parts is because someone may still need to interface with worlds outside .NET and access some driver or system calls for example requiring you to know how to build a descriptor and put each bit in the right place. do not being mad at those people, they made our jobs possible.
In short : Interlocked + bitfields. incredibly powerful, don't use it

A: It is for speed and efficiency. Essentially all you are working with is a single int.
if ((flags & AnchorStyles.Top) == AnchorStyles.Top)
{
    //Do stuff
}


text:
Q: how to check datetime in angularjs? posts = [{"content":"content1",
          "created":"2013-12-27T14: 15: 27.747Z"},
         {"content":"content2",
          "created":"2013-12-27T14: 15: 02.956Z"}]

How to check posts[0] and posts[1] was created in the same day or not with Angularjs?

A: javascript cannot parse ISODATE which contain spaces:
post[0].created.replace(/\s/g,'')

That's how you compare dates:
(new Date(post[0].created).toDateString) === (new Date(post[1].created).toDateString)

A: Angular doesn't really have a built in way to compare dates, but it can be done in conjunction with angular.
http://jsfiddle.net/TheSharpieOne/LxTGd/1/
This will compare if the day, month, and year are the same, determining if the 2 dates are on the same day (time is irrelevant).
$scope.sameDay = function(date1,date2){
    return date1.substring(0,10) === date2.substring(0,10);
}

This functionality would ideally be made into some sort of directive.  But this is just a basic example, a directive example can be made if required.


text:
Q: Juggle Producer and Consumer in Asyncio Python I have a producer and a consumer async function. The producer runs first and then three consumers consume the task concurrently. I want to continue this cadence indefinitely.

*

*What is the best way to stop the producer and send a signal to the consumer to start running?

*What is the best way to stop the consumer and send a signal to the producer to start running?

My current setup looks like this:
import asyncio
import time

async def producer(event):
    n = 0
    while True:
        print("Running producer...")
        await asyncio.sleep(0.5)
        n += 1
        if n == 2:
            event.set()
            break

async def consumer(event):
    await event.wait()
    print("Running consumer...")
    await asyncio.sleep(0.5)

async def main():
    event = asyncio.Event()

    tasks = [asyncio.create_task(producer(event))] + [
        asyncio.create_task(consumer(event)) for _ in range(3)
    ]

    await asyncio.gather(*tasks)

while True:
    asyncio.run(main())
    print("\nSleeping for 1 sec...\n")
    time.sleep(1)

This produces the following output:
Running producer...
Running producer...
Running consumer...
Running consumer...
Running consumer...

Sleeping for 1 sec...

Running producer...
Running producer...
Running consumer...
Running consumer...
Running consumer...

The snippet above will run the producer and the two consumers indefinitely. This works as expected:

*

*The producer and the two consumers run concurrently

*The while loop surrounding asyncio.run is running the system indefinitely

However, I was wondering if there is a better synchronization technique to achieve this long-running periodicity?

A: An alternative to using an event to wake up your consumers is to synchronize the producer and consumers using a queue. The code would look something like
import asyncio

async def producer(queue: asyncio.Queue):
    while True:
        print("Running producer...")
        message = await fetch_message_from_sqs()
        if message:
            await queue.put(message)
        await asyncio.sleep(0.5)

async def consumer(queue: asyncio.Queue):
    while True:
        print("Running consumer...")
        if queue.empty():
            await asyncio.sleep(1)
            continue
        message = await queue.get()
        print(message)
        await acknowledge_message(message)

async def main():
    # You can set a max size if you want to prevent pull too many messages from SQS.
    queue = asyncio.Queue()

    tasks = asyncio.gather(producer(queue), *[consumer(queue) for _ in range(3)])

if __name__ == "__main__":
    asyncio.run(main())


text:
Q: Mysql select * from a where doesnt exist in b Im having problems with constructing a query which filters out posts from table a, that already existing in table b.
Table A:
 `bok_id` int(6) NOT NULL AUTO_INCREMENT,
 `tid` time NOT NULL,
 `datum` date NOT NULL,
 `datum_end` date NOT NULL,
 `framtid` varchar(5) NOT NULL,
 `h_adress` varchar(100) NOT NULL,
 `l_adress` varchar(100) NOT NULL,
 `kund` varchar(100) NOT NULL,
 `typ` varchar(5) NOT NULL,
 `bil` varchar(99) NOT NULL,
 `sign` varchar(2) NOT NULL,
 `tilldelad` varchar(12) NOT NULL,
 `skapad` datetime NOT NULL,
 `endrad` datetime NOT NULL,
 `endrad_av` varchar(2) NOT NULL,
 `kommentar` text NOT NULL,
 `weektype` varchar(3) NOT NULL,
 `Monday` tinyint(1) NOT NULL,
 `Tuesday` tinyint(1) NOT NULL,
 `Wednesday` tinyint(1) NOT NULL,
 `Thursday` tinyint(1) NOT NULL,
 `Friday` tinyint(1) NOT NULL,
 `Saturday` tinyint(1) NOT NULL,
 `Sunday` tinyint(1) NOT NULL,
 `avbokad` varchar(2) NOT NULL,
 `unika_kommentarer` varchar(2) NOT NULL,
 UNIQUE KEY `bok_id` (`bok_id`)

Table B:
 `id` int(6) NOT NULL AUTO_INCREMENT,
 `bok_id` int(6) NOT NULL,
 `tid` time NOT NULL,
 `datum` date NOT NULL,
 `datum_end` date NOT NULL,
 `framtid` varchar(5) NOT NULL,
 `h_adress` varchar(100) NOT NULL,
 `l_adress` varchar(100) NOT NULL,
 `kund` varchar(100) NOT NULL,
 `typ` varchar(5) NOT NULL,
 `bil` varchar(99) NOT NULL,
 `sign` varchar(2) NOT NULL,
 `tilldelad` varchar(12) NOT NULL,
 `skapad` datetime NOT NULL,
 `endrad` datetime NOT NULL,
 `endrad_av` varchar(2) NOT NULL,
 `kommentar` text NOT NULL,
 `weektype` varchar(3) NOT NULL,
 `Monday` tinyint(1) NOT NULL,
 `Tuesday` tinyint(1) NOT NULL,
 `Wednesday` tinyint(1) NOT NULL,
 `Thursday` tinyint(1) NOT NULL,
 `Friday` tinyint(1) NOT NULL,
 `Saturday` tinyint(1) NOT NULL,
 `Sunday` tinyint(1) NOT NULL,
 `avbokad` varchar(2) NOT NULL,
 `unika_kommentarer` varchar(2) NOT NULL,
 UNIQUE KEY `id` (`id`)

What i want is a query which hides all rows in Table A which exists in table B IF Table B.tilldelad=Requested Date. (f.e 2013-09-30)
Im not sure this makes any sense?
What i want is to filter out period bookings as they have been executed and therefore exists in table b which indicates it has been.
Since its recurring events the same bok_id can exists SEVERAL times in table B, but only ONCE in table A...
SELECT * FROM bokningar
WHERE bokningar.datum <= '2013-09-30'
AND bokningar.datum_end >= '2013-09-30'
AND bokningar.typ >= '2'
AND bokningar.weektype = '1'
AND bokningar.Monday = '1' ## Monday this is dynamically changed to current date
AND bokningar.avbokad < '1'
AND NOT EXISTS ( SELECT 1 FROM tilldelade WHERE tilldelade.tilldelad = '2013-09-30' )

The above code does the trick regarding filtering out rows not in table B, however, if one row in table B has the current date, all results are filtered out.
Only rows with corresponding bok_id's is supposted to get filtered out.
Any thoughts on how to do that? Perhaps a Distinct select?

A: try something like
SELECT ...
FROM TABLEA
WHERE TABLEA.tilldelad=Requested Date
AND NOT EXISTS (SELECT 1 FROM TABLEB
                WHERE TABLEB.tilldelad=Requested Date
                  AND TABLEA.bok_id = TABLEB.bok_id
                  AND...)

A: Typically, NOT IN subselects are quite expensive in querying time.  This can normally be handled by doing a LEFT-JOIN and Keeping only those where the other table IS NULL like...
SELECT *
   FROM
      bokningar
         LEFT JOIN tilldelade
            on bokningar.bok_id = tilldelade.bok_id
           AND tilldelade.tilldelad = '2013-09-30'
   WHERE
          bokningar.datum <= '2013-09-30'
      AND bokningar.datum_end >= '2013-09-30'
      AND bokningar.typ >= '2'
      AND bokningar.weektype = '1'
      AND bokningar.Monday = '1' ## Monday this is dynamically changed to current date
      AND bokningar.avbokad < '1'
      AND tilldelade.bok_id IS NULL

A: You need to do set operations.
A simple minus Query would solve your problem here.
Select * from tableA
minus
Select * from tableB;

This would display all data in tableA which is not present in tableB.
You can read more about it over here. http://en.wikipedia.org/wiki/Set_operations_%28SQL%29
For your specific case, try this :
Select * from tableA A
minus
Select * from tableB B where B.tilldelad='3013-09-30';


text:
Q: Conditional Formatting for Calender Good day,
so I am trying to build a planning tool, where I am using a table with source data on one sheet, which I want to use to fill in cells with different colours in a calender sheet, depending on the job type for different dates.
I can get conditional formatting to display single tasks, but have problems applying the conditional formatting throughout, i.e. if I have two entries for the same person in the table, I want both of them displayed in the calender.
Anyone who can help?

Please see below example what I want the calender to show and what I want it to be based upon.


text:
Q: Answers in a line with `Answers` package I am typing a set of exercises with an 'answers' package. MWE:
\documentclass[12pt]{article}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[OT1]{fontenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{answers}

\Newassociation{sol}{Solution}{ans}
\renewcommand{\Solutionlabel}[1]{\textbf{#1.}}
\theoremstyle{plain}
\newtheorem{ex}{}

\begin{document}
\Opensolutionfile{ans}[ans1]
\section{Problems}
\begin{ex}
$2+2=?$
\begin{sol}
$4$.
\end{sol}
\end{ex}
\begin{ex}
$1+2=?$
\begin{sol}
$3$.
\end{sol}
\end{ex}
\Closesolutionfile{ans}
\section{Answers}
\input{ans1}
\end{document}

Everything is fine. But I want these short answers go in one paragraph like this:

How to achieve it? This should be simple, but the manual is very concise and is missing a lot of details.
Restriction: I cannot use exam package as I need to use these exercises in tufte-style book eventually, so I cannot do \documentclass{exam}.
Acceptable answer: The answer could be the suggestion of the package that allows doing the same stuff with a continuous enumeration of the problems through the entire book and the answers printed at the end of the document but by \section and with the continuous enumeration.

A: Just add one line:
\documentclass[12pt]{article}

\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[OT1]{fontenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{amsthm}
\usepackage{answers}

\Newassociation{sol}{Solution}{ans}
\renewcommand{\Solutionlabel}[1]{\textbf{#1.}}
\renewenvironment{Solution}[1]{\textbf{#1.} }{\quad}  % This line added
\theoremstyle{plain}
\newtheorem{ex}{}

\begin{document}
\Opensolutionfile{ans}[ans1]
\section{Problems}
\begin{ex}
$2+2=?$
\begin{sol}
$4$.
\end{sol}
\end{ex}
\begin{ex}
$1+2=?$
\begin{sol}
$3$.
\end{sol}
\end{ex}
\Closesolutionfile{ans}
\section{Answers}
\input{ans1}
\end{document}


text:
Q: Disabling Resume I am working with Cocoa, doing some tutorials. My question is how do I stop an application from picking up from where it left off after quitting? Like, how do I reset window size, position, etc?
And how do I set an initial position?

A: If you uncheck the "Restorable" box in IB, the window will always start with the size and position that you set in IB..


text:
Q: Async task in activiti not executed I have a problem with a simple workflow implemented with activiti engine and Java
I'm not able to execute a task asynchronously. The workflow is very simple

The upper part of the workflow start a process execute the "Start Service Task" emit a signal and execute the "Loop service Task" and repeat 10 times.
The bottom part is triggered by the signal emited in the upper part and must be execute asynchronously respect the loop part but in reality it block the "Loop service Task".
I try with set the async attribute in the bottom flow but in this case the bottom is not executed.
Follow the link to github project.
https://github.com/giane88/testActiviti
package configuration;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.asyncexecutor.AsyncExecutor;
import org.activiti.engine.impl.asyncexecutor.ManagedAsyncJobExecutor;
import org.activiti.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration;

public class WorkflowConfiguration {
  final ProcessEngine processEngine;

  public WorkflowConfiguration(final String workFlowName) {
    processEngine = setUpProcessEngine(workFlowName);
  }

  public ProcessEngine getProcessEngine() {
    return processEngine;
  }

  private ProcessEngine setUpProcessEngine(String workFlowName) {
    ProcessEngineConfiguration cfg = null;
    cfg = new StandaloneProcessEngineConfiguration()
        .setJdbcUrl("jdbc:h2:mem:activiti;DB_CLOSE_DELAY=1000")
        .setJdbcUsername("sa")
        .setJdbcPassword("")
        .setJdbcDriver("org.h2.Driver")
     .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
    final ProcessEngine processEngine = cfg.buildProcessEngine();
    RepositoryService repositoryService = processEngine.getRepositoryService();
    repositoryService.createDeployment().addClasspathResource("activiti/" + workFlowName)
        .deploy();
    return processEngine;
  }

}

package configuration;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.runtime.ProcessInstance;

import java.util.HashMap;
import java.util.Map;

public class WorkflowManipulator {
  private final Map<String, Object> nextDelegateVariables ;
  private final String wfName;
  private final ProcessEngine engine;

  public WorkflowManipulator(String wfName, ProcessEngine engine) {
    this.nextDelegateVariables = new HashMap<>();
    this.wfName = wfName;
    this.engine = engine;
  }

  public ProcessInstance startProcess() {
    if (nextDelegateVariables.size() > 0) {
      return engine.getRuntimeService().startProcessInstanceByKey(wfName, nextDelegateVariables);
    } else {
      return engine.getRuntimeService().startProcessInstanceByKey(wfName);
    }
  }
}

@Log4j2
public class TestWorkFlowMain {

  public static void main(String[] args) throws IOException {

    WorkflowConfiguration workflowConfiguration = new WorkflowConfiguration("test.bpmn");
    WorkflowManipulator workflowManipulator = new WorkflowManipulator("testProcess", workflowConfiguration.getProcessEngine());
    ProcessInstance processInstance = workflowManipulator.startProcess();
  }
}

package delegates;

import lombok.extern.log4j.Log4j2;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;

@Log4j2
public class AsyncServiceTask implements JavaDelegate {
  @Override
  public void execute(DelegateExecution execution) throws Exception {
    log.info("Sleeping for 3 second");
    Thread.sleep(3000);
    log.warn("AsyncCompleted");
  }
}

A: As usualy i found the solution some minutes after post the question.
The problems was in the process engine configuration you need to set up an asyncExecutor and enable and active it like in the example below.
    ProcessEngineConfiguration cfg;
    AsyncExecutor asyncExecutor = new ManagedAsyncJobExecutor();
    cfg = new StandaloneInMemProcessEngineConfiguration()
        .setAsyncExecutor(asyncExecutor)
        .setAsyncExecutorEnabled(true)
        .setAsyncExecutorActivate(true);
    final ProcessEngine processEngine = cfg.buildProcessEngine();


text:
Q: How can I know whether the logged in user is a prime user or not using LWA? I am working on a login with Amazon feature
How can I know weather the logged in user was a prime user or not
I have some documentation but it don't have any thing about this
https://developer.amazon.com/docs/login-with-amazon/android-docs.html
AuthorizationManager.authorize(new AuthorizeRequest
                    .Builder(requestContext)
                    .shouldReturnUserData(true)
                    .addScopes(ProfileScope.profile(), ProfileScope.postalCode(),ProfileScope.profile())
                    .build());


text:
Q: Count the number of metrics in Graphite that are currently between two values Help me with this otherwise very simple task... I have a series of metrics that represent a certain virtual machine state. I want to plot a graph with the count of all metrics that have been between a certain range (35-51). This is my query:
countSeries(filterSeries(filterSeries(opennebula-performance.zones.opennebula-innologica.vms.3DC.*.vm_lcm_state, 'min' , '>', 35 ), 'max', '<', 51))

This seems to be working well when there is at least one metric in the range. However when there are none (and it's the common case since there aren't usually faulty VMs), Graphite returns just [] instead of series with zeroes. Grafana doesn't like this and plots no data.
Why doesn't countSeries return 0 when there are no matches? This will indeed plot a straight line at 0 for the whole period, but this is exactly what is needed here.
My Graphite version is 1.2.0-dev, but on previous versions this didn't work too.


text:
Q: Booting from Live USB without typing "live" Can I set "live" as the default option so that I don't have to type it each time I boot the PC?
Can the config file below be changed somehow to achieve it? Currently it looks so. I've never changed it before.
$ cat syslinux/txt.cfg
default live
label live
menu label ^Start Kubuntu
kernel /casper/vmlinuz
append noprompt cdrom-detect/try-usb=true persistent file=/cdrom/preseed/kubuntu.seed boot=casper maybe-ubiquity initrd=/casper/initrd.lz quiet splash ---
label check
menu label ^Check disc for defects
kernel /casper/vmlinuz
append noprompt boot=casper integrity-check initrd=/casper/initrd.lz quiet splash ---
label memtest
menu label Test ^memory
kernel /install/mt86plus
label hd
menu label ^Boot from first hard disk
localboot 0x80

It's Ubuntu 16
Please, mark this question as duplicate of How to boot from ubuntu live usb with 'try ubuntu' directly?
The answer that worked for me was
https://askubuntu.com/a/865314/572615


text:
Q: window.onclick except if element is 'someElement' I am wondering if there is a way to exclude certain elements on a function.  For example:
window.onclick = doThis() except if the element clicked is a 'ul' element.

Something like that.  I know that it would probably have to be written like this:
function doThis() {
  if (this item clicked is NOT 'ul') {
     function xyz();
}}

window.onclick = doThis();

I am just not sure if there is an "exception" in javascript.  Can someone please help.  thanks.
ok so here is my full code because it is still not working:

i added the target.nodeName !== code that was suggested below but it is still not working.  When i click a ul it still closes my menu.  thank you.

A: window.onclick = function(ev){
    if( ev.target.nodeName !== 'UL' ){
        xyz();
    }
};

What we're doing here is making the event object a parameter. This way we can get the target of the click event. We're doing exactly that here—we check if the target is a ul element. If not, run the function.
Also, just for future reference, you have to assign the function to the onclick. So first assign the function to a variable, and then assign the variable to the onclick (without parentheses). I read this somewhere...I'll try to pull that up.

A: Events bubble up the DOM tree, so just set a "blocker" that prevents the bubbling from all
s: http://jsfiddle.net/6sqWh/.
$(window).on("click", doThis);

$("ul").click(false); // prevent bubbling to window from
s

Visually it will go like this:
execute the function
 ^                    (passed through)
window  <- click

--   blocks
ul

in contrast with:
execute the function
                      (not executed)
window
                      (won't arrive here)
--  blocks
ul  <- click

Note that without the blocker, it would go like:
execute the function
 ^
window
 ^
ul  <- click


text:
Q: WPF: Can I modify a TextBlock that is in a ControlTemplate? So I have a custom ControlTemplate that is used in several various sections throughout the same window to display a count.
However, this count is not relevant for one of the sections and I want to remove it, which would require removing a single textblock from this template.
The call when making the window is along the lines of:
<ContentControl>
    <filters:__________ DataContext="______" Template="{StaticResource FilterTemplate}" />
</ContentControl>

Where FilterTemplate is the template that I would like to override.
The filter is quite long, so having to recopy the entire filter for such a small change would not be ideal.


text:
Q: How to create % discount code for ENTIRE cart subtotal? How do I create a discount code for the ENTIRE value of a shopping cart, with multiple items in it?
By default, the "percentage of product price discount" function applies a % discount ONLY to the first line item in your basket. I need to offer the discount on the ENTIRE basket value, even if there are multiple items in it. This discount can be applied to ANY product, there are no category or price restrictions.

A: You have to make an pricerule for the basket and set the right conditions for it to target the whole basket.
it seams you have made it wrong if its only targeting one item.
this link explain the whole use of price rules - http://www.demacmedia.com/magento-commerce/shopping-cart-price-rules-in-magento-walk-through/

A: You will want to create a shopping cart price rule.
This rule should be setup to discount x% off any item.  This will then provide you the results you are asking about.  A discount off all items in the cart.
If you want to apply the discounts so that everyone see's them on the website in search results, product pages, categories, etc.. You'll want to use the Catalog price rules.
These sections can be found under:
Promotions > Shopping Cart Price Rules
and
Promotions > Catalog Price Rules
These two sections can be configured in a myriad of ways, and the interactions between both can get very, very complex.  If you need help drop me a line.


text:
Q: Equivalence relations, counting equivalence classes between sets Let $S=\{1,2,3..,9\}$ and $T=\{1,2,3,4,5\}$ . Let $R$ be the relation on the power set of S ie P(S) defined by
For all elements X, Y in P(S), X$R$Y iff |X ∩ T| = |Y ∩ T|.
I wanted to confirm my answers. Because this is an equivalence relation (I proved it via showing reflexivity, symmetry and transitivity), I rewrote it another way as X$R$Y iff |X| = |Y| to simplify the following.
(a) how many equivalence classes are there?
6 or 10, leaning more towards 10 (as there are 10 possible sizes of elements in P(S))
(b) how many elements does [∅] have?
1
(c) how many elements does [T] have?
9 choose 5 or 5 choose 5, leaning more towards 9 choose 5
(d) how many elements does [{1,2}] have?
9 choose 2 or 5 choose 2, leaning more towards 9 choose 2

A: (a) Note that each equivalence class has a $1\text{-}1$ mapping with the set $\{0,1,2,3,4,5\}$, via the mapping $f([A]) = \left| A\cup T\right|$. Thus, there is a total of 6 equivalence classes.
(b) A set $U$ belongs to $[\{\emptyset\}]$ if and only if $|U\cap T|=\emptyset$. That is, any subset of $\{6,7,8,9\}$ will do. There is a total of $2^4=16$ such sets.
(c) Using almost the same rationale as in (b), we see that There is a total of $2^4=16$ such sets, since the subsets are $T\cup U$, where $U\subseteq \{6,7,8,9\}.$
(d) As in (c), we select a subset of $\{6,7,8,9\}$, and take its union with some subset of $T$, of size $2$. So the answer is $16\cdot\binom{5}{2}=160$.

A: Indeed, this $\def\R{\mathscr R} \R$ is an equivalence relation on $P(S)$.
However, it is different from the one you replaced it with.
Hints:
(a) There are 6 equivalence classes, because $|X\cap T|$ can have 6 different values.
(b) $Y\R \emptyset\ \iff\ Y\cap T=\emptyset\ \iff\ Y\subseteq\{6,7,8,9\}$
(c) $Y\R T\ \iff\ Y\supseteq T$; in this case $Y$ can be written as any set $\subseteq\{6,7,8,9\}$ plus $T$.
(d) $Y\R\{1,2\}\ \iff\ |Y\cap T|=2$,  so the number of such sets $Y$ is $\,\binom52\cdot 2^4$.

A: "XRRY iff |X| = |Y|" is wrong.
(a) there are 6 equivalence classes since $|X|\cap T\in\{0,\dots,5 \}$ for any set $X \in P(S)$ and every case does occur.
(b) All elements in $[\emptyset]$ either contain 6,7,8,9 or not. So there are $2^4=16$ many.
(c) 16 (see (b) for reasoning)
(d) $16\cdot\binom{5}{2} =160$


text:
Q: Getting text/attributes from a script object function in html using Python I've been doing web scraping on a website where I need to get the javascript so I could extract data such as name, created date, and some randomly generated codes as will be shown below...
Is there an efficient/any way of getting text/attributes from a script object function in a <script type="text/javascript"> from a html webpage.
I was able to find the script section using BeautifulSoup, with the function embedded in it is as follows:
<script type="text/javascript">

//COMMENT// Some data already here

$(document).ready(function() {
    name.init("<website Link>")
    lang.init("en", "GB")
    data.init("hello", "", "AT3K21SDV", "YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5", "")
});
</script>

Specifically, I need to get the $(document).ready(function() section that will include AT3K21SDV and YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5.
I've been bugging my brains out trying to get it using index like so; `soup[3:40] but doesn't work

A: beautifulsoup doesn't parse JavaScript, so you need to use other tools. For example re to extract the information:
import re
from ast import literal_eval

txt = '''<script type="text/javascript">

//COMMENT// Some data already here

$(document).ready(function() {
    name.init("<website Link>")
    lang.init("en", "GB")
    data.init("hello", "", "AT3K21SDV", "YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5", "")
});
</script>'''

data = re.search(r'data\.init(\(.*?\))', txt).group(1)
data = literal_eval(data)

print(data[2], data[3])

Prints:
AT3K21SDV YIERE34ITEW832WCNG3VMASJKHO345JKRELRK5

EDIT: If inside data.init(...) are newlines, you must set flags=re.DOTALL in re.search():
import re
from ast import literal_eval

txt = '''<script type="text/javascript">

//COMMENT// Some data already here

$(document).ready(function() {
    ab.info.init("sv", "pp", "f", "NONE",
        "rw", "3r7u6565667",
        "3435345")
});
</script>'''

data = re.search(r'info\.init(\(.*?\))', txt, flags=re.DOTALL).group(1)
data = literal_eval(data)

print(data)

Prints:
('sv', 'pp', 'f', 'NONE', 'rw', '3r7u6565667', '3435345')


text:
Q: Create a new post from hybrid mobile App in WordPress using JSON API plugin So i am developing a hybrid app using cordova and jquery mobile. I need to login to a wordpress blog site and create a new post in my hybrid app. I am using JSON Api plugin(https://wordpress.org/plugins/json-api/) to perform AJAX post. The issue is when i try to create a new post using the create_post method,i get the following error:

POST http//some_localhost_ip/wordpress/api/create_post/? 403(Forbidden)

I have also used JSON Api user plugin (https://wordpress.org/plugins/json-api-user/) for user authentication where in i am using the generate_auth_cookie method.
authentication-controller.js
$.ajax({
    url: SERVER_URL + "/api/get_nonce/?controller=user&method=generate_auth_cookie",
    type: "POST",
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Accept',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
    },
    crossDomain: true,
    cache: true,
    success: function(result) {
        if (result.status == "ok") {
            var url = SERVER_URL + "/api/user/generate_auth_cookie/?"
            var dataString = {};
            dataString["nonce"] = result.nonce;
            dataString["username"] = username;
            dataString["password"] = password;
            if (!checkBox.is(':checked')) {
                dataString["seconds"] = SESSION_TIMEOUT;
            }
            dataString["insecure"] = "cool"; // remove this if SSL certificate is installed and the url is HTTPS
            $.ajax({
                url: url,
                type: "POST",
                headers: {
                    'Access-Control-Allow-Headers': 'Content-Type, Accept',
                    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
                },
                data: dataString,
                crossDomain: true,
                cache: false,
                success: function(result) {
                    if (result.status == "ok") {
                        window.localStorage.setItem("USERDATA", JSON.stringify(result.user));
                        window.localStorage.setItem("USERCOOKIE", result.cookie);
                        console
                        switch (result.user.role[0]) {
                            case "subscriber":
                                $.mobile.navigate("#page-subscriber-allposts");
                                break;
                            case "author":
                                $.mobile.navigate("#page-author-allposts");
                                break;
                            case "editor":
                                $.mobile.navigate("#page-editor-allposts");
                                break;
                            default:
                                $.mobile.navigate("#page-contributor-allposts");
                                break;
                        }
                    } else {
                        navigator.notification.alert(result.error, function doNothing() {}, "ERROR!", "OK");
                    }
                    return;
                },
                error: function(error) {
                    navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                    return;
                }
            });
        } else {
            navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
            return;
        }
    },
    error: function(error) {
        navigator.notification.alert("There is some issue in connecting to Authentication server", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
        return;
    }
});

workflow-controller.js
var url = SERVER_URL;
if (null != postId && typeof postId != "undefined") {
    url += "/api/get_nonce/?controller=posts&method=update_post";
} else {
    url += "/api/get_nonce/?controller=posts&method=create_post";
}
$.ajax({
    url: url,
    type: "POST",
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Accept',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
    },
    crossDomain: true,
    cache: false,
    success: function(result) {
        alert(JSON.stringify(result));
        if (result.status == "ok") {
            var dataString = {};
            if (null != postId && typeof postId != "undefined") {
                url = SERVER_URL + "/api/update_post/?";
            } else {
                url = SERVER_URL + "/api/create_post/?";
                dataString["post_id"] = postId;
            }
            dataString["nonce"] = result.nonce;
            dataString["cookie"] = window.localStorage.getItem("USERCOOKIE");
            dataString["author"] = author;
            dataString["title"] = title;
            dataString["content"] = news;
            $.ajax({
                url: url,
                type: "POST",
                headers: {
                    'Access-Control-Allow-Headers': 'Content-Type, Accept',
                    'Access-Control-Allow-Methods': 'GET, POST, OPTIONS'
                },
                data: dataString,
                crossDomain: true,
                cache: false,
                success: function(result) {
                    alert(JSON.stringify(result));
                    if (result.status == "ok") {
                        navigator.notification.alert("Your post was successfully submitted and is pending for review", function doNothing() {}, "Hurray!!", "Ok");
                        $.mobile.navigate("#page-author-allposts");
                        return;
                    }else {
                         navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                         return;
                     }
                },
                error: function(error) {
                    navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
                    return;
                }
            });
        }else {
             navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
             return;
         }
    },
    error: function(error) {
        navigator.notification.alert("There is some issue in submitting your post", function doNothing() {}, "Breath In! Breath Out!", "Try Again");
        return;
    }
});

A: you can use below plugin for authentication,
https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/
OR you need to implement auth by below methods,
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
When you send request with username and password, you can get token as a response. Then you need to send this token with each request with header like below for the Authentication purpose,
syntax :
Authorization : Bearer< space >token
Example:
Authorization : Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJINiJ9.eyJpiOiJodHRwOlwvXC9hcHBzLm9wZW50ZXN0ZHJpdmUuY29tOjgwODBcL21hZ25pZmljZW50IiwiF0IjoxNDMjk1LCJuYmYiOjE0OTgxOTYyOTUsImV4cCI6MTQ5ODIwMzQ5NSwiZGF0YSI6eyJ1c2VyIjp7ImliMSJ9fX0.ngBJaXmtKAaBULSUtQZ7eHhqB8YSPjeHuI

A: Well, i gave up on JSON Api and now using WP Rest API V2. Also, a slight change with the basic auth plugin i used before "WP Basic Auth". Its faulty. Try using the plugin https://github.com/WP-API/Basic-Auth.
I changed my ajax call as below:
$.ajax({
    url: SERVER_URL + "/wp-json/wp/v2/posts",
    type: "POST",
    headers: {
        'Access-Control-Allow-Headers': 'Content-Type, Accept',
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, DELETE',
        'Authorization': 'Basic ' + btoa(username + ":" + password)
    },
    data: dataString,
    crossDomain: true,
    cache: false,
    beforeSend: function() {
        SpinnerPlugin.activityStart("Please wait...", {dimBackground: true});
    },
    complete: function() {
        SpinnerPlugin.activityStop();
    },
    success: function(result) {
       navigator.notification.alert(successMsg, function doNothing() {}, "Success!!", "Ok");
       $.mobile.navigate("#page-author-allposts");
       return;
    },
    error: function(error) {
        console.log(error);
        navigator.notification.alert(errMsg, function doNothing() {}, "Error", "OK");
        return;
    }
});

However, this method of Basic Authenticating is only for development environment. I guess i need to implement the more complex oAuth authentication later on :/


text:
Q: Adding nodes to a line by interval in MapInfo I am a MapBasic beginner, and I just want a simple .mbx or tool that can add nodes to a line by interval (say every 50m). I don't really need it to have a start point or end point (or maybe it is necessary to have that for the code to work, not a problem). Just maybe a dialog box that lets me bring in the line table and specify my interval, that's it.

A: Have a look at the free tool ToolBox from Routeware.
You can find it on their download page.
And there's a description of the features on the Toolbox 1.07 page. Look for the Add Nodes feature.
And if you want to have a look at the sourcecode, you can download that from the same site, too


text:
Q: Numerical ways to find energy eigenvalues? I have to find energy eigenvalues of (time dependent) Schrödinger equation, but it was nonlinear so i cannot find a appropriate solutions about it.
I am not good at numerical analysis, so i don't know what kinds of methods are normally used in quantum mechanics. Also i cannot understand some methods which i can find in google scholar or arxiv (cause they are too difficult for me).
So, my question is that there is a computational method which is usually used in numerical researches in quantum mechanics and also simple as possible to applied by student?
Sorry for my english

A: You can use the variational method, especially numerical procedures based on the Ritz method, to find an approximation for the lowest energy eigenvalue of the time-independent Schrödinger equation.