text:
Q: Column height of widow on resize I am stuck, I want to make the height of my left column equal to the height of the right column . Seems the problem is the width of my video but I know how to fix this issue
I put in code this :

@font-face {
  font-family: "poppins-bold";
  src: url('../css/fonts/Poppins-Bold.ttf');
}

@font-face {
  font-family: "poppins-light";
  src: url('../css/fonts/Poppins-Light.ttf');
}

@font-face {
  font-family: "poppins-medium";
  src: url('../css/fonts/Poppins-Medium.ttf');
}

@font-face {
  font-family: "poppins-regular";
  src: url('../css/fonts/Poppins-Regular.ttf');
}

@font-face {
  font-family: "poppins-semibold";
  src: url('../css/fonts/Poppins-SemiBold.ttf');
}

body {
  margin: 0;
  background-color: #0080b9;
}

.conteneur {
  min-width: 1050px;
}

.light {
  font-family: "poppins-light";
}

.video-cover {
  width: 100%;
  height: 175px;
  background-color: gray;
  margin-top: 10px;
  margin-bottom: 50px;
}

#bloc-gauche {
  background-color: white;
  width: 25%;
  float: left;
  /*height: 900px;*/
  height: 100vh;
  color: #0080b9;
  font-family: "poppins-semibold";
  overflow: scroll;
  /*
        padding-left:20px;
        padding-right:20px;
        padding-top:20px;
        */
}

.wrapper-bloc-gauche {
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 30px;
}

#intro {
  width: 185px;
  margin-bottom: 50px;
}

#content-bloc-droite {
  padding-top: 25px;
}

#bloc-droite {
  background-color: #0080b9;
  width: 75%;
  float: right;
  font-family: "poppins-semibold";
  color: white;
  background-repeat: repeat-x;
}

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

#description {
  font-size: 15px;
  text-align: center;
  width: 45%;
  margin-top: 25px;
}

.video-player-container {
  /*width:40%;*/
  display: block;
  margin-right: auto;
  margin-left: auto;
  margin-top: 50px;
  margin-bottom: 40px;
}

.video-player {
  width: 100%;
  border: 5px solid #ECECEC;
  box-sizing: border-box;
}

.footer-bloc-droite {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  overflow: hidden;
}

#logo-joon {
  float: left;
  width: 200px;
}

#btn-xp {
  display: inline-block;
  margin: 0 auto;
  background-color: white;
  padding-right: 15px;
  padding-left: 15px;
  padding-top: 10px;
  padding-bottom: 10px;
  color: #0080b9;
}

#joon-p {
  float: right;
  width: 200px;
}

#joon-p-img {
  /*transform: rotate(-20deg);
        padding-bottom: 0px;
        -webkit-transform-origin-x: -55px;
        overflow: hidden;
        */
  -webkit-transform-origin-x: -55px;
  width: 95%;
}

#left-block {
  float: left;
}

#right-block {
  float: right;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

          Vivez l'intégralité d'un voyage JOON avec Maxime Gasteuil

Ep 1 Lorem Ipsum dolores sit amet

Ep 2 Lorem Ipsum dolores sit amet

Ep 3 Lorem Ipsum dolores sit amet

Ep 4 Lorem Ipsum dolores sit amet

          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis veritatis, fugit quia repudiandae est dignissimos modi expedita ullam totam, aliquid odit voluptas omnis dolores nemo nam

          <video controls class='video-player center-block' style='min-width:475px;max-width:40%;'>
                                <source src='http://web1.fr-hmd.com/adpulse/videos-adpulse/joon-1.mp4' type="video/mp4">
                            </video>

            Démarrer l'expérience de voyage

I have a another little problem: I wanted to put the plane little up.
I tried to use position:absolute but all other element is not centered.

A: You provided so much code, that is useless and as you can no one cared to fix your issue, anyway all i'm going to say is that i tried to add certain height:100% and height:100vh on some wrapper elements and it should work now.

@font-face {
  font-family: "poppins-bold";
  src: url('../css/fonts/Poppins-Bold.ttf');
}

@font-face {
  font-family: "poppins-light";
  src: url('../css/fonts/Poppins-Light.ttf');
}

@font-face {
  font-family: "poppins-medium";
  src: url('../css/fonts/Poppins-Medium.ttf');
}

@font-face {
  font-family: "poppins-regular";
  src: url('../css/fonts/Poppins-Regular.ttf');
}

@font-face {
  font-family: "poppins-semibold";
  src: url('../css/fonts/Poppins-SemiBold.ttf');
}

body {
  margin: 0;
  background-color: #0080b9;
}

.conteneur {
  min-width: 1050px;
  height: 100vh;
}

.light {
  font-family: "poppins-light";
}

.video-cover {
  width: 100%;
  height: 175px;
  background-color: gray;
  margin-top: 10px;
  margin-bottom: 50px;
}

#bloc-gauche {
  background-color: white;
  width: 25%;
  float: left;
  /* height: 900px; */
  height: 100vh;
  color: #0080b9;
  font-family: "poppins-semibold";
  overflow: scroll;
  /*
        padding-left:20px;
        padding-right:20px;
        padding-top:20px;
        */
}

.wrapper-bloc-gauche {
  padding-left: 30px;
  padding-right: 30px;
  padding-top: 30px;
  max-height: 100%;
}

#intro {
  width: 185px;
  margin-bottom: 50px;
}

#content-bloc-droite {
  padding-top: 25px;
  max-height: 100%;
  overflow: auto;
}

#bloc-droite {
  background-color: #0080b9;
  width: 75%;
  float: right;
  font-family: "poppins-semibold";
  color: white;
  background-repeat: repeat-x;
  height: 100%;
}

.center-block {
  display: block;
  margin-right: auto;
  margin-left: auto;
}

#description {
  font-size: 15px;
  text-align: center;
  width: 45%;
  margin-top: 25px;
}

.video-player-container {
  /*width:40%;*/
  display: block;
  margin-right: auto;
  margin-left: auto;
  margin-top: 50px;
  margin-bottom: 40px;
}

.video-player {
  width: 100%;
  border: 5px solid #ECECEC;
  box-sizing: border-box;
}

.footer-bloc-droite {
  text-align: center;
  padding-left: 30px;
  padding-right: 30px;
  overflow: hidden;
}

#logo-joon {
  float: left;
  width: 200px;
}

#btn-xp {
  display: inline-block;
  margin: 0 auto;
  background-color: white;
  padding-right: 15px;
  padding-left: 15px;
  padding-top: 10px;
  padding-bottom: 10px;
  color: #0080b9;
}

#joon-p {
  float: right;
  width: 200px;
}

#joon-p-img {
  /*transform: rotate(-20deg);
        padding-bottom: 0px;
        -webkit-transform-origin-x: -55px;
        overflow: hidden;
        */
  -webkit-transform-origin-x: -55px;
  width: 95%;
}

#left-block {
  float: left;
}

#right-block {
  float: right;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">

          Vivez l'intégralité d'un voyage JOON avec Maxime Gasteuil

Ep 1 Lorem Ipsum dolores sit amet

Ep 2 Lorem Ipsum dolores sit amet

Ep 3 Lorem Ipsum dolores sit amet

Ep 4 Lorem Ipsum dolores sit amet

          Lorem ipsum dolor sit amet consectetur adipisicing elit. Quis veritatis, fugit quia repudiandae est dignissimos modi expedita ullam totam, aliquid odit voluptas omnis dolores nemo nam

          <video controls class='video-player center-block' style='min-width:475px;max-width:40%;'>
                                <source src='http://web1.fr-hmd.com/adpulse/videos-adpulse/joon-1.mp4' type="video/mp4">
                            </video>

            Démarrer l'expérience de voyage


text:
Q: Scaling content in UIWebView I am displaying some content in a UIWebView on both an iPhone and an iPad (same content, two different apps). On the iPhone, the content fills the entire 320px in width, but on the iPad, it does not - it seems to only be about 240px across.
I don't have control of the content, but I did find this in the source:
<meta name="viewport" content="width = 320" /><meta name="viewport" content="initial-scale=1, user-scalable=no" /></head>

Can anyone suggest why this wouldn't be working on an iPad app, and if there's anything I can do about it without being able to change the HTML? I'd rather not manipulate it through javascript either, if possible.

A: I'm not sure exactly what is going wrong, or what effect you are trying to achieve, but I usually use a tag like this in my UIWebView-based views:
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plone 4.3 migration - AttributeError: type object 'IIntIds' has no attribute '__iro__' After migrating Plone 4.1 + Dexterity site to Plone 4.3 site's /manage_workspace becomes inaccessible. Database migration cannot be performed.
The ZMI root can be still accessed.
Traceback (innermost last):

    Module ZPublisher.Publish, line 237, in publish_module_standard
    Module ZPublisher.Publish, line 179, in publish
    Module zope.event, line 31, in notify
    Module zope.component.event, line 24, in dispatch
    Module zope.component._api, line 136, in subscribers
    Module zope.component.registry, line 321, in subscribers
    Module zope.interface.adapter, line 585, in subscribers
    Module plone.transformchain.zpublisher, line 119, in applyTransformOnFailure
    Module plone.transformchain.zpublisher, line 79, in applyTransformOnSuccess
    Module plone.transformchain.zpublisher, line 55, in applyTransform
    Module zope.component._api, line 172, in queryUtility
    Module zope.component.registry, line 163, in queryUtility
    Module ZODB.Connection, line 860, in setstate
    Module ZODB.Connection, line 914, in _setstate
    Module ZODB.serialize, line 613, in setGhostState
    Module zope.component.persistentregistry, line 40, in __setstate__
    Module zope.interface.adapter, line 91, in _createLookup
    Module zope.interface.adapter, line 439, in __init__
    Module zope.interface.adapter, line 476, in init_extendors
    Module zope.interface.adapter, line 480, in add_extendor

AttributeError: type object 'IIntIds' has no attribute '__iro__'

Also @@plone-upgrade is inaccessible.
Any ideas or special migrations needed?

A: In Dexterity 2, relation field support (which includes installing the intids catalog) is no longer installed by default. To get it you need to install Dexterity with the [relations] extra:
[instance]
eggs =
    plone.app.dexterity [relations]

This is documented at http://plone.org/documentation/manual/upgrade-guide/version/upgrading-plone-4.2-to-4.3/dexterity-optional-extras and in the Dexterity release notes.


text:
Q: How to pass dynamic queue name in jmeter Am having a CSV file with a list of active mq queue name.  Am trying to push messages to dynamic queue by reading the queue name from csv and setting it to my variable and passing that variable in jms point to point sampler as ${queueName}. The messages are not getting poster todynamic queue, instead it's getting posted to ${queueName

A: As per your reply, Its clear your queue variable name doesn't get evaluated properly.
I hope you can find the root cause for the issue by following below steps.

*

*Check whether CSV file in a readable location, It should be on bin folder

*Check for variable name spellings

*Add a debug sampler in middle and check whether variable getting evaluated correctly

*Install step-by-step plugin and debug the jmeter flow

A: Just make sure the variable spelling is correct in both CSV Data config and the request where you are using the variable. This happens when there is no data available in the sheet or if there is a spell mistake in the variable.


text:
Q: yarn stderr no logger appender and no stdout I'm running a simple mapreduce program wordcount agian Apache Hadoop 2.6.0. The hadoop is running distributedly (several nodes). However, I'm not able to see any stderr and stdout from yarn job history. (but I can see the syslog)
The wordcount program is really simple, just for demo purpose.
import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class WordCount {
  public static final Log LOG = LogFactory.getLog(WordCount.class);

  public static class TokenizerMapper
       extends Mapper<Object, Text, Text, IntWritable>{

    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      LOG.info("LOG - map function invoked");
      System.out.println("stdout - map function invoded");
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  public static class IntSumReducer
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values,
                       Context context
              ) throws IOException, InterruptedException {
        int sum = 0;
        for (IntWritable val : values) {
          sum += val.get();
        }
        result.set(sum);
        context.write(key, result);
      }
    }

    public static void main(String[] args) throws Exception {
      Configuration conf = new Configuration();
      conf.set("mapreduce.job.jar","/space/tmp/jar/wordCount.jar");
      Job job = Job.getInstance(conf, "word count");
      job.setJarByClass(WordCount.class);
      job.setMapperClass(TokenizerMapper.class);
      job.setCombinerClass(IntSumReducer.class);
      job.setReducerClass(IntSumReducer.class);
      job.setOutputKeyClass(Text.class);
      job.setOutputValueClass(IntWritable.class);
      FileInputFormat.addInputPath(job, new Path("hdfs://localhost:9000/user/jsun/input"));
      FileOutputFormat.setOutputPath(job, new Path("hdfs://localhost:9000/user/jsun/output"));

      System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
  }

Note in the map function of Mapper class, I added two statements:
LOG.info("LOG - map function invoked");
System.out.println("stdout - map function invoded");

These two statements are to test whether I can see logging from hadoop server. I can successfully run the program. But if I go to localhost:8088 to see the application history and then "logs", I see nothing in "stdout", and in "stderr":
log4j:WARN No appenders could be found for logger (org.apache.hadoop.ipc.Server).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

I think there is some configuration needed to get those output, but not sure which piece of information is missing. I searched online as well as in stackoverflow. Some people mentioned container-log4j.properties but they are not specific about how to configure that file and where to put.
One thing to note is I also tried the job with Hortonworks Data Platform 2.2 and Cloudera 5.4. The result is the same. I remember when I dealt with some previous version of hadoop (hadoop 1.x), I can easily see the loggings from same place. So I guess this is something new in hadoop 2.x
=======
As a comparison, if I make the apache hadoop run in local mode (meaning LocalJobRunner), I can see some loggings in console like this:
[2015-09-08 15:57:25,992]org.apache.hadoop.mapred.MapTask$MapOutputBuffer.init(MapTask.java:998) INFO:kvstart = 26214396; length = 6553600
[2015-09-08 15:57:25,996]org.apache.hadoop.mapred.MapTask.createSortingCollector(MapTask.java:402) INFO:Map output collector class = org.apache.hadoop.mapred.MapTask$MapOutputBuffer
[2015-09-08 15:57:26,064]WordCount$TokenizerMapper.map(WordCount.java:28) INFO:LOG - map function invoked
stdout - map function invoded
[2015-09-08 15:57:26,075]org.apache.hadoop.mapred.LocalJobRunner$Job.statusUpdate(LocalJobRunner.java:591) INFO:
[2015-09-08 15:57:26,077]org.apache.hadoop.mapred.MapTask$MapOutputBuffer.flush(MapTask.java:1457) INFO:Starting flush of map output
[2015-09-08 15:57:26,077]org.apache.hadoop.mapred.MapTask$MapOutputBuffer.flush(MapTask.java:1475) INFO:Spilling map output

These kind of loggings ("map function is invoked") is what I expected in hadoop server logging.

A: All the sysout written in Map-Reduce program can not be seen on console. It is because map-reduce run in multiple parallel copies across the cluster, so there is no concept of a single console with output.
However, The System.out.println() for map and reduce phases can be seen in the job logs. Easy way to access the logs is
open the jobtracker web console - http://localhost:50030/jobtracker.jsp
click on the completed job
click on map or reduce task
click on tasknumber
Go to task logs
Check stdout logs.

Please note that if you are not able to locate URL, just look into the console log for jobtracker URL.


text:
Q: Weird output of merge sort for no. of entries not being a power of 2. - c I have written a code for mergesort to sort an array of structures in c it works fine when i give no. of entries as a power of 2 but does not even sort the records for other no. of entries. I Would like to learn where is my logic going wrong??
Here is my code:
void Mergesort(struct record r[],int n)
{
    int k;
    if(n>1)
    {
        int i,j;
        struct record r1[n/2];
        struct record r2[n-n/2];
        for(i=0,j=n/2;i<n/2 && j<n;i++,j++)
        {
            r1[i]=r[i];
            r2[i]=r[j];
        }
        Mergesort(r1,n/2);
        Mergesort(r2,n/2);
        r=Merge(r1,r2,r,n);
    }

}

struct record * Merge(struct record r1[],struct record r2[],struct record r[],int n)
{
    int i=0,j=0,k=0;
    while(i<n/2 && j<n/2)
    {
        if (strcmp(r1[i].a,r2[j].a)<=0)
        {
            r[k]=r1[i];
            i=i+1;
        }
        else
        {
            r[k]=r2[j];
            j=j+1;
        }
        k=k+1;
    }
    if(i==n/2)
    {
        for(j;j<n/2 && k<n;j++,k++)
        {
            r[k]=r2[j];
        }

    }
    else
    {
        for(i;i<n/2 && k<n;i++,k++)
        {
            r[k]=r1[i];
        }
    }
    return r;
}

Any Help would be greatly appreciated.!!
Sample Input for 8 entries:

CS003 Vinay 10
CS005 Mouli 9.94
CS010 Gautham 9.94
CS020 Sneha 9.94
CS200 Mohit 9.93
CS012 Aarti 9.9
CS002 Adithya 9.78
CS001 Adithya 9.58

Getting correct output as follows:

CS012 Aarti 9.90
CS002 Adithya 9.78
CS001 Adithya 9.58
CS010 Gautham 9.94
CS200 Mohit 9.93
CS005 Mouli 9.94
CS020 Sneha 9.94
CS003 Vinay 10.00
**[Sorted according to the Names in the record]**

Sample input for 7 entries:

CS003 Vinay 10
CS005 Mouli 9.94
CS010 Gautham 9.94
CS020 Sneha 9.94
CS200 Mohit 9.93
CS012 Aarti 9.9
CS002 Adithya 9.78

Output(Weird):

CS200 Mohit 9.93
CS005 Mouli 9.94
CS020 Sneha 9.94
CS012 Aarti 9.90
CS003 Vinay 10.00
CS010 Gautham 9.94
CS002 Adithya 9.78

[Not at all sorted according to the names]

A: I would make the below changes:
void Mergesort(struct record r[],int n)
{
    int k;
    if(n>1)
    {
        int i,j;
        struct record r1[n/2];
        struct record r2[n-n/2];
        for(i=0; i<n/2; i++)
        {
            r1[i]=r[i];
        }
        for(i=0,j=n/2; j < n; i++,j++) // This is required because your previous logic used to skip the last element of j when n is odd.
        {
            r2[i]=r[j];
        }
        Mergesort(r1,n/2);
        Mergesort(r2,n-n/2);//this is 'n - n/2'
        r=Merge(r1,r2,r,n/2, n-n/2); //The sizes are different so pass both
    }

}

struct record * Merge(struct record r1[],struct record r2[],struct record r[],int r1N, int r2N)
{
    int i=0,j=0,k=0;
    while(i<r1N && j<r2N)
    {
        if (strcmp(r1[i].a, r2[j].a)<=0)
        {
            r[k]=r1[i];
            i=i+1;
        }
        else
        {
            r[k]=r2[j];
            j=j+1;
        }
        k=k+1;
    }
    if(i==r1N)
    {
        for(j;j< r2N && k < (r1N + r2N);j++,k++)
        {
            r[k]=r2[j];
        }

    }
    else
    {
        for(i;i < r1N && k < (r1N+r2N); i++,k++)
        {
            r[k] = r1[i];
        }
    }
    return r;
}

A: The problem is with this loop:
for(i=0,j=n/2;i<n/2 && j<n;i++,j++) { ... }

Since you are filling r1[] and r2[] in the same loop, you are filling each array with the same number of items. However, if n is an odd number, you will need to put the last remaining element of r[] into one of these arrays. The easiest solution would be to have two separate loops.

A: Your main mistake is

*

*not considering unequal 'halves' of n in case of odd value, which means your code works only if all divisions of n-s by halves produce even numbers (until it went down to 2=1+1); that implies the starting value of n must be a power of 2.
That is reflected in following errors:

*

*a single for() loop to fill both r1[] and r2[] despite the fact they are different lengths;

*the recursive call to Mergesort with r2 passing wrong length (n/2 while it should be n-n/2);

*passing the n parameter alone to Merge and not calculating n-n/2 for r2[] inside Merge.

In addition, unused variable k declared in Mergesort and useless r assignment at the end of the function.
Please see the code below.
void Mergesort(struct record r[], int n)
{
    if (n > 1)
    {
        int n1 = n/2;
        int n2 = n - n1;
        int i;
        struct record r1[n1];
        struct record r2[n2];

        for (i = 0; i < n1; i++)    // fill r1[] with n1 items from r[]
            r1[i] = r[i];
        for (i = 0; i < n2; i++)    // fill r2[] with n2 items from r[]
            r2[i] = r[n1+i];        // skipping n1 already copied to r1[]

        Mergesort(r1, n1);          // pass appropriate lengths
        Mergesort(r2, n2);
        Merge(r1, r2, r, n1, n2);   // pass arrays with lengths
    }
}

void Merge(struct record r1[], struct record r2[], struct record r[], int n1, int n2)
{
    int i=0, j=0, k=0;
    while (i < n1 && j < n2)        // any items left in both sub-arrays?
    {
        if (strcmp(r1[i].a, r2[j].a) <= 0)  // append the smaller one
            r[k++] = r1[i++];               // or earlier if they're equal
        else
            r[k++] = r2[j++];
    }

    while (i < n1)                  // append the remaining part, if any
        r[k++] = r1[i++];
    while (j < n2)
        r[k++] = r2[j++];
}

You might also simplify the code a bit by dropping indices and operating directly on pointers and decrementing lengths of remaining parts:
void Merge(struct record r1[], struct record r2[], struct record r[], int n1, int n2)
{
    while (n1 && n2)        // any items left in both sub-arrays?
    {
        if (strcmp(r1->a, r2->a) <= 0)  // append the smaller one
            *r++ = *r1++, n1--;         // or earlier if they're equal
        else
            *r++ = *r2++, n2--;
    }

    while (n1--)                  // append the remaining part, if any
        *r++ = *r1++;
    while (n2--)
        *r++ = *r2++;
}


text:
Q: Which is the right formula to evaluate the diameter of a divergent gaussian beam at a distance r? Good morning,
I have to evaluate the diameter of a gaussian beam at a distance $r$ which has a divergence $\theta$ and a starting diameter $d_0$.
I found these three ways:
1)
$
d_f=d_0+r\tan(\theta)
$
2)$d_f=d_0+2r\tan(\theta/2)$
3)$d_f=d_0+r\theta$
I was wondering which is the right one between these three formulas and if they are different approximations of the same formula.
Many thanks.

A: I think this can be seen as a matter of how you define the divergence angle $\theta$. Different authors seem to define it slightly differently, however in practice this is rarely an issue since $\theta$ is typically small enough that $2\tan(\theta/2) \approx \tan(\theta) \approx \theta$.
The Gaussian beam as a solution to the paraxial Helmholtz equation has the intensity
$$I(\rho, z) = I_0 \left[\frac{W_0}{W(z)}\right]^2 \exp \left[-\frac{2\rho^2}{W^2(z)}\right],$$
$$W(z) = W_0 \sqrt{1 + (z/z_0)^2},$$
$$W_0 = \sqrt{\frac{\lambda z_0}{\pi}},$$
where $\rho$ is the distance from the beam axis, $z$ is the position along the beam axis, $W_0$ is called the waist radius and $z_0$ the Rayleigh range (from Saleh & Teich). The fraction of the power of the beam contained by a circle of radius $\rho$ about the beam that is a distance $z$ away from the beam waist is
$$1 - \exp \left[-\frac{2\rho^2}{W^2(z)}\right].$$
If you define the beam diameter (as is usually done) as the diameter containing $1 - e^{-2}$ of the power, then the beam diameter is
$$D(z) = 2W(z) = 2W_0 \sqrt{1 + (z/z_0)^2} = D_0 \sqrt{1 + (z/z_0)^2}$$
with $D_0 = 2W_0$. Far away from the beam waist ($z \gg z_0$), we have
$$D(z) \approx D_0 \frac{z}{z_0}.$$
This diameter is defined by a cone along the beam axis with the vertex at the center of the beam. The half-angle of this cone is
$$ \theta_0 = \tan^{-1}\left(\frac{W_0}{z_0}\right) $$
Now, if we define the divergence to be the full vertex angle of this cone, i.e. $\theta = 2\theta_0$,
$$ D(z) = \sqrt{D_0^2 + \left(2\frac{W_0}{z_0}z\right)^2} = \sqrt{D_0^2 + \left(2z\tan\theta_0\right)^2} = \sqrt{D_0^2 + \left[2z\tan(\theta/2)\right]^2} $$
If we define the divergence as $\theta = \tan^{-1}(D_0/z_0)$ (although I don't see an obvious reason for doing so),
$$ D(z) = \sqrt{D_0^2 + \left(\frac{D_0}{z_0}z\right)^2} = \sqrt{D_0^2 + \left(z\tan\theta\right)^2} $$
If we define the divergence as $\theta = D_0/z_0$ so that $D(z) \approx \theta z$ for $z\gg z_0$ (this is twice the definition in Saleh & Teich),
$$ D(z) = \sqrt{D_0^2 + \left(\frac{D_0}{z_0}z\right)^2} = \sqrt{D_0^2 + \left(\theta z\right)^2}. $$
I believe the formulas you gave are approximations for these expressions that are valid for $z \approx 0$ and $z \gg z_0$.


text:
Q: When trying to connect to Queue Manager Using IBM MQ Explorer, I'm getting error as "Could not establish connection to the queue manager -reason 2538" could not establish a connection to the queue manager - reason 2538. (amq4059) severity: 10 (warning)
explanation: the attempt to connect to the queue manager failed. this could be because the queue manager is incorrectly configured to allow a connection from this system, or the connection has been broken. response: try the operation again. if the error persists, examine the problem determination information to see if any information has been recorded.
Please tell how do I resolve this.


text:
Q: Como fazer upload de aquivos para o servidor? Tenho o seguinte código html e php a rodar no meu servidor, no entanto, sempre que tento fazer o upload de um arquivo, é-me retornada a mensagem "There was an error uploading the file, please try again!" e não consigo perceber porquê...

<!DOCTYPE html>

  <title>Upload your files</title>

  <form enctype="multipart/form-data" action="upload.php" method="POST">

Upload your file

    <input type="file" name="uploaded_file"></input>

    <input type="submit" value="Upload"></input>
  </form>

<?PHP
  if(!empty($_FILES['uploaded_file']))
  {
    $path = "uploads/";
    $path = $path . basename( $_FILES['uploaded_file']['name']);

    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
      echo "The file ".  basename( $_FILES['uploaded_file']['name']).
      " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";
    }
  }
?>

O meu servidor é Apache/2.4.25 (Debian).
Será que me conseguem ajudar?

A: FAÇA UM TESTE, uso este código. (obviamente muda para a sua estrutura)
 <?php

        $foto = $_FILES['uploaded_file']['tmp_name'];

   //FOTO
    $tamanho_permitido = "1024000"; //1 MB
    $pasta = 'uploads';

    if (!empty($foto)){
    $file = getimagesize($foto);

    //TESTA O TAMANHO DO ARQUIVO
    if($_FILES['image']['size'] > $tamanho_permitido){
        echo "Erro - Arquivo muito grande";
        exit();
    }

    //TESTA A EXTENSÃO DO ARQUIVO
    if(!preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $file['mime'])){
        echo "Erro - extensão não permitida";
        exit();
    }

    //CAPTURA A EXTENSÃO DO ARQUIVO
    $extensao = str_ireplace("/", "", strchr($file['mime'], "/"));

    //MONTA O CAMINHO DO NOVO DESTINO
    $novoDestino = "{$pasta}/imagem_".uniqid('', true) . '.' . $extensao;
    move_uploaded_file ($foto , $novoDestino );

}

        include('conexaobd.php');

        $sqlinsert = "INSERT INTO pacientes (uploaded_file) VALUES ('$novoDestino')";

        mysqli_query($link, $sqlinsert) or die("Não foi possível armazenar no banco");

        $resultado = "Dados Cadastrados com Sucesso!!";

        ?>

Salva o caminho da imagem no banco de dados, e a imagem em si no diretório.


text:
Q: An inquiry on memory pools in C++ Is it possible to create a memory pool implementation that follows the simple logic:
1 - Allocate n bytes worth of memory pool.
2 - Use modified new(); function/operator that does not allocate memory only gets a pointer to the beginning of the memory pool. This way objects are created dynamically without overhead.
3 - When the memory pool runs low, it deallocates what is left of it and allocates a new memory pool
4 - the objects created in the first memory pool are left to pick up the memory based on their sizes. The difference of what was allocated in the first pool and what was given back when it ran low is restored by the objects upon their deletion.
My worries are mainly about the fact that I have no idea how to delete the memory pool smaller than it was allocated, KEEPING IN MIND that besides what is left in the end of the memory pool object there is also a OS header for the memory pool that is before the first object, allocated in the pool. What approach do I need to make sure no memory is leaked, that deleting the excess memory pool won't delete objects that are allocated in it and that the header for the memory pool fragment is safely removed.
Thanks!
EDIT: Note that the intent is for memory to be allocated by the memory pool and released by the objects, which may have different lifetime. If this is possible at all...

A: Firstly, this sounds like an arena allocator (as mentioned in the comments), if you want to know what you should be searching for.
Note that arenas are only really useful if you plan to tear down the whole thing at once; if you expect to reclaim memory from deleted objects for re-use, you end up writing your own heap sitting on top of the arena.  If you just want to keep the arena-chunk alive until the last object is deallocated, you can manage with a refcount.
Secondly, the only common way I know to allocate memory which you can later shrink without possibly moving (like realloc), is using memory maps: this is platform-specific.


text:
Q: The fundamental group of the Möbius strip What is the fundamental group of the Möbius strip?
Is it given by $\{-1,1\}$ as the lemma of Synge supposes, or am I wrong and it does not apply there?

A: The moebius strip is homotopy-equivalent to the circle, so has the same fundamental group which is $\mathbb Z$.

A: It is $\mathbb{Z}$. You can prove it via seeing the Möbius strip as a quotient of a square , with sides identified properly. Draw a diagonal dividing this square, and show that the Möbius strip deformation retracts onto this circle .

A: The fundamental group of the moebius strip is $\{a,b|a^2=b^2\}$.
Cf. http://www2.math.ou.edu/~forester/5863S14/fsol.pdf


text:
Q: Replace/Add string in textarea in js I have a textarea and some buttons. Onclick of each button I have to do following:

*

*Check if textarea contains some text XXX.

*If contains then remove it.

*If not then add it.

How can I do this in javascript? I have tried following but it does not work:
function addRecip(con){
    var myvalue = document.getElementById("textarea1").value;
    if(myvalue.indexof(con+",")==-1){
        document.getElementById("textarea1").value = myvalue + con + ",";
    } else {
        document.getElementById("textarea1").value = myvalue.replace(con + ",","");
    }
}

A: indexof is actually meant to be spelled indexOf, and JavaScript is case-sensitive.
This works:
function addRecip(con){
    var myvalue = document.getElementById("textarea1").value;
    if(myvalue.indexOf(con+",")==-1){
        document.getElementById("textarea1").value = myvalue + con + ",";
    } else {
        document.getElementById("textarea1").value = myvalue.replace(con + ",","");
    }
}


text:
Q: Typeclass method which returns another typeclass in Haskell I have this task in which I have to define 2 typeclasses in Haskell. One is simple - it implements Ord and has one method which converts given type to an int. Something like this:
class (Ord a) => Id a where
  toInt :: a -> Int

But then I have another typeclass HasId which has a method getId. This method should return Id typeclass. So I wrote something like this:
class HasId a where
  getId :: a -> Id a

And I get an error I don't know how to solve.
• Expected kind '* -> Constraint', but 'Int' has kind '*'
• In the class declaration for 'HasId'
 |
 | class (Int a) => HasId a where     |        ^^^^^

• Expected a type, but 'Id a' has kind 'Constraint'
• In the type signature: getId :: a -> Id a
  In the class declaration for 'HasId'
 |
 |  getId :: a -> Id a     |

Can somebody tell me how can I return typeclass in another's typeclass method?
Should I implement some instance of Id typeclass at first?

A: It's important to understand that a Haskell class is very different from a class in OO languages. It's a type class, i.e. it "groups together a collection of types", whereas an OO class groups together a collection of values. IOW, an OO class is a type (containing values), but a Haskell class is rather something like a type of types, as it were.
Now, a function/method always takes values as argument and gives back values as results. But it can't give you back a type, nor a "value of a typeclass" because there's no such thing.
Instead, the way to use type classes is this: you write a polymorphic function, i.e. a function that accepts or yields some value of unspecified type. That's what type variables are there for. Normally, a polymorphic signature means that the function can deal with values of any type, like with
length :: [a] -> Int

which takes a list and doesn't care what type its elements have. But then you say that you do care a bit what types are used, namely, you require that they are in the class. That's a constraint, and it's written with the => notation. toInt actually has the signature (automatically generated by the class declaration)
toInt :: Id a => a -> Int

Frankly, I doubt that this is really what you want. If all you can do with an Id a is converting it to an Int, then the result effectively is an Int (just with a type-annotation which indicates what kind of object this Id belongs to), regardless of the a parameter. So instead of the Id class, you should consider having an Id type
newtype Id' a = Id {toInt :: Int}  -- The prime ' symbol has no particular meaning,
                                   -- I just use it for disambiguation.

Then, you have the more sensible type
toInt :: Id' a -> Int

without needing any constraints.
newtype is much more similar to a OO class, in that it actually defines a concrete type which has values you can pass around.
The getId method is also a constrained-polymorphic function, that can take something which "has an Id" and gives you back that Id. In this case, a class makes sense (because you can have different data structure that may store their Ids in different ways). This would now actually be
class HasId a where
  getId :: a -> Id' a

As per Welperooni's answer, it is indeed also conveivable to define HasId using your original Id class, just it doesn't really make much sense. Id is the class of all types which can be used as identifyers. You could express that getId can yield an Id of  any such type:
class HasId a where
  getId :: Id b => a -> b

Note that the result-Id type is now completely independent of the type of object whose Id you want to calculate. b can always be any Id-type. As I said this doesn't make sense: why would you need a whole lot of different types that represent Ids, but require all the HasId types to support all of them?
In fact this cannot be implemented as it stands, because there's no mechanism that allows you to generate an Id of arbitrary Id type. This would require an additional method
class Id a where
  toInt :: a -> Int
  fromInt :: Int -> a

and now you could do
class HasId a where
  getId :: Id b => a -> b

data SomeObj { objName :: String
             , objId :: Int }

instance HasId SomeObj where
  getId (SomeObj _ i) = fromInt i

However, if you require that any Id type is convertible both from and to Int, then these types must be isomorphic to Int itself. Therefore, the newtype Id' a approach is almost certainly better.

A: You declared the return value to be a HKT Id a, but what you wanted is another type, constrained by the typeclass Id.
What you need is not getId :: a -> Id a, but getId :: Id b => a -> b


text:
Q: Find the remainder when $11^{12}$ is divided by $13$. I am looking for an easier way than mine to solve the problem.

Problem: Find the remainder when $11^{12}$ is divided by $13$.

Here is what I did. I simplify $11^{12}$ mod $13$ = $(–2)^{12}$ mod $13$. Then I don't know how to simply further.

A: Use Euler's theorem. Let's notice that since $13$ is prime then $\varphi(13)=12$, when $\varphi(13)$ is the number of natural numbers $k$ smaller than $13$ such that $gcd(13,k)=1$. According to Euler's theorem, $11^{12} \equiv 1 (\mod 13)$ since $gcd(11,13)=1$.

A: Working modulo 13:
$$ 11^{12} \equiv (-2)^{12} \equiv \left((-2)^2\right)^6 \equiv 4^6 \equiv 16^3 \equiv 3^3 \equiv 27 \equiv 1 \mod 13$$

A: Since $2^6 = 64 = 65 - 1 = 5 \cdot 13 -1$, we have
$$
11^{12}
\equiv (-2)^{12} = 2^{12} = 64^2 \equiv (-1)^2 = 1 \bmod 13
$$


text:
Q: How to return result in last line by pipe operator? Can I return time_stamp in last line without extracting it in curly brackets?
{:ok, time_stamp} = Myapp.Repo.insert(changeset) # |> Map.get time_stamp
time_stamp

# {:ok, %Myapp.TimeStamp{__meta__: #Ecto.Schema.Metadata<:loaded>, active: true...}

A: You can use Kernel.elem/2 to get an item from a tuple by index (starting from 0).
Myapp.Repo.insert(changeset) |> elem(1)

However if your changeset is not valid then this will return the changeset, as an invalid changeset will return {error, changeset}
If you could explain a little bit about why you want to do this then we may be able to help further.


text:
Q: Hibernate @OneToMany how to persist the relationship without updating the (many) elements? I have
public class Stale {

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "stale", cascade = CascadeType.ALL)
    private List<Poney> poneys;
}

and
public class Poney {

    @ManyToOne()
    @JoinColumn(name = "stale_id")
    private Stale stale;

    private String name;
}

When I try to save a stale with an updated poney list, the persisting of a stale doesn't behave like I would it to do.

*

*[GOOD] added poneys (existing in te db) are well persisted as stale members

*[BAD] poneys removed from the stable are still in the stable after save(). Caution : I want them removed from the stable but I don't want to kill any pony from the db !

*[BAD] if the poney's name is edited before persisting the stale, the name modification is persisted. But I would like to persist only the relationship, not poney modifications.

Can someone help me ?

A: The problem is that this is a bi-directional relationship. When updating the state of a bidirectional relationship it is applications duty to update the state on both sides (so not only remove Ponies from Stable, but also remove the Stable reference in Ponies). That can be accomplished for example by @BeforePersist or @BeforeUpdate method in the Stable entity. Since Pony is the owner of the relationship JPA sees the state of Pony as more important than state of Stable, and removing ponies in Stable does nothing.
As for your last point - again, since this is bidirectional and Pony is the owner it's impossible to change the state of the relationship without saving new state of Pony (including any changes like name).
They way you want this to behave makes me think what you actually want is a uni-directional relationship on the Stable side:
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="stale_id", referencedColumnName="id")
private List<Poney> poneys;

And removing the @ManyToOne mapping in Pony.


text:
Q: How to only allow certain words in .htaccess regex? For example, I can write the following .htaccess rule at the base directory of my domain (/):
RewriteRule ^something/[bd]on$ foo.php [L]

Which would match the following URLs, providing my domain is www.example.com:
http://www.example.com/something/bon
http://www.example.com/something/don

right? But how would I put words in there to match? For example, apple and cheese, so that it only matches:
http://www.example.com/something/apple
http://www.example.com/something/cheese

Note that I have around 40 different possibilities after something/, so please provide me with an .htaccess rule which can accommodate that.

A: 40 words sounds long but AFAIK, the only way to make a Regex pattern match a set of options is to explicitly write them in parantheses, separated by the pipe | character.
So I think RewriteRule ^something/(word1|word2|word3)$ foo.php [L] should work for you.
EDIT:
I forgot to mention. To shorten the list you can use character groups/ranges and conditions for the words (such as colou?r or gr[ae]y) but that will make it look confusing later when you need to edit it.


text:
Q: How to multiply two 8 bit numbers using shift and add operations in 8085 microprocessor? We are supposed to multiply two 8 bit numbers using shift and add operations of 8085 microprocessor. Answer should be a 16 bit number. Use of shift and add operation is compulsory

A: To understand the solution you must be familiar with Rotate instructions in 8085,particularly for this solution you need to understand two things

*

*RRC instruction rotates bits to the right and LSB can be checked from carry flag

*multiplying number by 2(10 in binary) results in left shif by one bit (verify yourself)

*adding number with itself is equivaent to multiplying number by 2(10 in binary) and hence also shift bits by 1 bit
 #ORG 8000
  //initializing operands
         LXI H,7000H   //data is stored in 7000H
         MOV E,M
         MVI D,00H
         INX H
         MOV A,M
         MVI C,08H
         LXI H, 0000H

 //multiplication algorithm starts here
 LOOP :  RRC
         JNC SKIP
         DAD D

 //left shift is performed by adding number with itself
 //three lines just below this comment is shifting DE pair to left by 1 bit
 SKIP:   XCHG          //exchange HL and DE pair
         DAD H         //Add HL with itself and store in HL
         XCHG          //exchange HL and DE
         DCR C
         JNZ LOOP
         SHLD 7050H
         HLT
 #ORG7000
 #DB 25,2A

A: Suppose we want to multiply two integers 27 and 23. Since 23 (10111 in binary) can be written as
2*11 + 1 = 2*(2*5 + 1) + 1 = ... = 2*(2*(2*(2*(2*0 + 1) + 0) + 1) + 1) + 1. Thus, x * 23 can be expressed as: 2*(2*(2*(2*(2*0 + x) + 0) + x) + x) + x. Observe that the addend terms in each step follows the binary representation of 23 (1, 0, 1, 1, 1). With this observation, we can write the following pseudocode to perform the multiplication x * y using shift and add operations.
let x be the first operand and y be the second one
set sum = 0
repeat
    set sum = sum * 2
    left shift y by one place
    if the overflow bit after the shift is set then
        set sum = sum + x
until y ≠ 0
output the sum as the result of x*y

Let x=27 (0x1B) and y=23 (0x17) be two 8-bit intergers, the follwing microprogram performs the required multiplication. As the multiplication may require 16 bits to store the result we use the HL register pair for the calculation.
      LXI D,001BH ; DE <- 27(x)
      MVI A,17H   ; A <- 23(y)
      LXI H,0000H ; HL <- 0(sum)

LOOP: DAD H       ; sum <- sum*2

      STC
      CMC         ; clear the carry flag before rotate
      RAL         ; y <- y<<1

      JNC SKIP    ; if overflow bit from y was not set
      DAD D       ; sum <- sum + x
SKIP: ORA A       ; to update the zero flag
      JNZ LOOP
      HLT

The result, 27*23 = 621 (0x026D), is available in the HL register pair.


text:
Q: Aftershock (Radiant) quest - how does the Staff of Magnus fit in? Does it have a special function in this quest? Once you've finished the College of Winterhold main quest, Tolfdir will give you the 'Aftershock' Radiant quest.
Before giving the quest for the first time, Tolfdir will say something along the lines of "I hope you still have the Staff of Magnus, you may (or will) need it."
However, I have tried completing this  Radiant quest multiple times without using the Staff of Magnus at all (I just used a sword to kill the Magic Anomalies - they are tough and hard to hit).
My question is: Will the Staff of Magnus make completion of the 'Aftershock' Radiant  quests easier or faster? Does it have a special function similar to its function in the last College of Winterhold main quest?
Related question: Do you need the Staff of Magnus after killing Arcano?

A: The odds are pointing towards no. On the Quest Stages page, it doesn't mention anything about the Staff of Magnus being used for anything (besides his recommendation,) just the Eye. If it really was crucial, it would have been listed on the Quest Stages page. Also, if you can drop it, it's not a Quest Item. And that it has monetary value will only further confirm this.
Granted, because he recommended it, it would probably make the quest go faster. But because you already finished the quest, I'm not sure how this would benefit anymore.


text:
Q: DEBUG|Insert failed. First exception on row 0; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, bad value for restricted picklist field I have a record type picklist on Case object.
When I create case via email-to-case that works fine without any issue(I have some APEX code related to that)
Issue:
The problem is when I write test cases for that and run the test that says on insert and update.

DEBUG|Insert failed. First exception on row 0; first error: INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST, bad value for restricted picklist field

What is the issue? Even though that works fine when I create case via email-to-case.
Code:
Case newCase = new Case();
newCase.Origin = 'Email';
newCase.Subject = 'Subject';
newCase.OwnerId = System.Label.Default_Case_Owner_Queue;
newCase.Status = 'New';
newCase.Priority = 'Medium';
newCase.Description = 'This is a new case';
newCase.Type = 'Invoicing';
newCase.Email__c  = 'email@test.fi';
newCase.Close_Code__c = 'test'; // this is the picklist which is causing issue, the picklist value was already added to record type.
insert newCase;

How can I fix that to pass the tests?
TIA

A: During the insert the record type assignment is missing and the default record type may not have the picklist value that you are trying to insert with, so add the record type assignment-
Case newCase = new Case();
...
newCase.RecordTypeId = '{get value from describe call}';
newCase.Close_Code__c = 'test';
insert newCase;


text:
Q: creating an excel vba loop to list horizontally, dates between a start and finish date for each set of vertical dates I have a list of start and finish dates Cols J & K this list is dynamic. I need to list the individual dates between the two dates to a row (P13) to the right hand side of each set of dates horizontally. The Exit Sub code is to stop the row updating and jump to the next row rather than exiting the sub. I have acheived this for one row, the code I am using is:
Dim StartDate As Date
Dim EndDate As Date
Dim NoDays As Integer

If Range("L13") <> "No" Then
    Exit Sub
End If
StartDate = Range("J13").Value
EndDate = Range("K13").Value
NoDays = EndDate - StartDate + 1
Range("P13").Value = StartDate
Range("P13").Resize(NoDays).DataSeries Rowcol:=xlRows, Type:=xlChronological, Date:= _
    xlDay, Step:=1, Stop:=EndDate, Trend:=False

This works for one set.
I have no idea how to loop through each of the sets which could be as many as 12,000 rows.

A: Can't say I knowe exactly what you are after, but this will loop through row 13 to 1000 and process your code.
Sub DateThing()
    Dim StartDate As Date
    Dim EndDate As Date
    Dim NoDays As Integer
    Dim i As Long

    For i = 13 To 1000

        If Range("L" & i) = "No" Then

            StartDate = Range("J" & i).Value
            EndDate = Range("K" & i).Value
            NoDays = EndDate - StartDate + 1
            Range("P" & i).Value = StartDate

            Range("P" & i).Resize(NoDays).DataSeries Rowcol:=xlRows, Type:=xlChronological, Date:= xlDay, Step:=1, Stop:=EndDate, Trend:=False

        end if

    Next i

End Sub


text:
Q: How to assign a number from a list of lists to another list of lists in python 3? I have a nested list, like this one:
[[2, 4], [1, 2], [2, 5], [3, 4], [3, 10], [2, 3, 4]]

From the nested list, I want to take the max value from index 0 list and assign it to the index 1 list. Similarly, I take the max value from index 2 list and assign it to the index 3 list. Similarly it goes,like this should be the output:
{4: [1,2], 5:[3,4], 10: [2,3,4]}

Is there any possible way of doing this in Python 3?

A: You can zip together offset even strides of the list.
I think this is what you want:
a = [[2, 4], [1, 2], [2, 5], [3, 4], [3, 10], [2, 3, 4]]
{max(x): y for x,y in zip(a[::2], a[1::2])}
# returns:
{4: [1, 2], 5: [3, 4], 10: [2, 3, 4]}


text:
Q: text summarization using Text-Summarizer in python I am trying to use below library which is available in website
https://pypi.org/project/text-summarizer/
from text_summarizer import summarizer
As informed in website i have installed text_summarizer package using below syntax below when loading it in python i am getting error
ImportError: cannot import name 'summarizer'
Can anyone help me if this package is working

A: Check if you have a circular dependencies import. This might just be the same answer as this question here: ImportError: Cannot import name X


text:
Q: Stored procedure out parameter doesn't change I'm calling a stored procedure that inserts a new row, but if the unique name exists, just updates a numerator and SHOULD return the updated id.
CREATE PROCEDURE bear_crm.insert_subject(in_subject_name varchar(100), OUT out_subject_id int)
BEGIN
    DECLARE  t_update_id int;
    set t_update_id := 0;
    INSERT INTO t_subject (subject_name) VALUES (in_subject_name) ON DUPLICATE KEY
    UPDATE pop_index = COALESCE(pop_index,0)+1, subject_id=LAST_INSERT_ID(subject_id);
    set out_subject_id :=  LAST_INSERT_ID();

    insert into testing(aa) values(out_subject_id); # just a test to see values
END//

The numerator is updated after the second attempt to insert the same value.
the "testing" table get the expected updated subject id,
yet my out parameter in the Python side is not effected:
v_id = -999
v_args = ['test subject', v_id]
mycursor.callproc('insert_subject', v_args)
print('id is:', v_args[1])

v_id remains -999


text:
Q: mysql - fill field by other fields I have a birthdate, year, month, day columns where columns "year,month,day" are foreign key to other tables
What I want to do is for each birthdate get id(year(birthdate)) to be the value of year column and the same thing for month and day columns.
How can I do this in MySQL?
Thanks in advance

A: Update mytable
set birthdate = Yearfield + monthfield + dayfield

EDIT
If birthdate is a date field you will have to cast or convert it first.
Update mytable
    set birthdate = Cast(Yearfield + monthfield + dayfield as date)

A: Check out triggers (http://dev.mysql.com/doc/refman/5.0/en/triggers.html) so every time the data is written you calculate and update the information you require.

A: Try
update tableName set birthdate = month + "/" + day + "/" + year;


text:
Q: How to return a JavaScript 'native' array from a C# method? I'm trying to call a C# method from JavaScript by using ActiveXObject:
var myobj = new ActiveXObject('myobject');
var arr = myobj.GetArray();

Eventually, arr will contain a SAFEARRAY object, but not JScript array. Is there any way to return native JavaScript object from a C# method?

A: You can return a JSON string and then parse into a JavaScript object. There are a number of .NET libraries available to serialize .NET objects into JSON and vice-versa-

*

*JSON.NET

*Microsoft ASP.NET AJAX library

*JSONSharp
to name a few.
This question and answer may be of use to you

A: I found the solution by myself, but no documentation exists for this part.
The solution is to use JScript.ArrayObject in the following way:
ArrayObject _lastField;
byte[] byteArray = new byte[]{2,1,2,3};
object[] array = new object[byteArray.Length];
byteArray.CopyTo(array, 0);
_lastField = Microsoft.JScript.GlobalObject.Array.ConstructArray(array);

After that you will be able to use the _lastField array in JavaScript like a native array:
var myobj = new ActiveXObject('myobject');
var arr = myobj.LastField;
alert(arr[1]);

A: You may return delimited Joined String in C# and can split into JavaScript
//C#
public string getArryString()
{
string[] arrstring = new string[]{"1","2","3"};
return string.Join(",", arrstring);
}

//Javascript
var arrstring = objActiveX.getArryString().split(',');

A: Via VBArray it can work like this:

*

*Return object[] from C# (declare so in the dispinterface).

*To get a native JS array in JScript use VBArray:
var jsArray = new VBArray(myobj.GetArray()).toArray();
for (i = 0; i < jsArray.length; i++)
{
   // use jsArray[i]
}

Background information:

*

*JScript supports SafeArrays of Variants only
http://blogs.msdn.com/b/jaiprakash/archive/2007/01/09/jscript-supports-safearrays-of-variants-only.aspx

*Eric's Complete Guide To Type Signatures Of Scriptable Object Models
http://blogs.msdn.com/b/ericlippert/archive/2004/07/14/183241.aspx


text:
Q: Fastest way to compute point to triangle distance in 3D? One obvious method for computing the minimum distance from a point to a 3D triangle is to project the point onto the plane of the triangle, determine the barycentric coordinates of the resulting point, and use them to determine whether the projected point lies within the triangle.  If not, clamp its the barycentric coordinates to be in the range [0,1], and that gives you the closest point that lies inside the triangle.
Is there a way to speed this up or simplify it somehow?

A: I'll lead with my test case results.

The test case code and implementation is in C#
    public void ClosestPointToShouldWork()
    {
        var r = new Random(0);
        double next() => r.NextDouble() * 5 - 1;
        var t = new Triangle(new Vector3(0,0,0), new Vector3(3.5,2,0), new Vector3(3,0.0,0));

        DrawTriangle(t);

        var hash = new Vector3( 0, 0, 0 );
        for (int i = 0; i < 800; i++)
        {
            var pt = new Vector3( next(), next(), 0 );
            var pc = t.ClosestPointTo( pt );
            hash += pc;

            DrawLine(pc,pt);
        }

        // Test the hash
        // If it doesn't match then eyeball the visualization
        // and see what has gone wrong

        hash.ShouldBeApproximately( new Vector3(1496.28118561104,618.196568578824,0),1e-5  );

    }

The implementation code is fiddly as I have a number of framework classes. Hopefully you can treat this as pseudo code and pull out the algorithm. The raw vector types are from https://www.nuget.org/packages/System.DoubleNumerics/.
Note that some of the properties of Triangle could be cached to improve performance.
Note that to return the closest point does not require any square roots and does not require transforming the problem to 2D.
The algorithm first quickly tests if the test point is closest to an end point region. If that is inconclusive it then tests the edge external regions one by one. If those tests fail then the point is inside the triangle. Note that for randomly selected points far from the triangle it is most likely that the closest point will be a corner point of the triangle.
public class Triangle
{
    public Vector3 A => EdgeAb.A;
    public Vector3 B => EdgeBc.A;
    public Vector3 C => EdgeCa.A;

    public readonly Edge3 EdgeAb;
    public readonly Edge3 EdgeBc;
    public readonly Edge3 EdgeCa;

    public Triangle(Vector3 a, Vector3 b, Vector3 c)
    {
        EdgeAb = new Edge3( a, b );
        EdgeBc = new Edge3( b, c );
        EdgeCa = new Edge3( c, a );
        TriNorm = Vector3.Cross(a - b, a - c);
    }

    public Vector3[] Verticies => new[] {A, B, C};

    public readonly Vector3 TriNorm;

    private static readonly RangeDouble ZeroToOne = new RangeDouble(0,1);

    public Plane TriPlane => new Plane(A, TriNorm);

    // The below three could be pre-calculated to
    // trade off space vs time

    public Plane PlaneAb => new Plane(EdgeAb.A, Vector3.Cross(TriNorm, EdgeAb.Delta  ));
    public Plane PlaneBc => new Plane(EdgeBc.A, Vector3.Cross(TriNorm, EdgeBc.Delta  ));
    public Plane PlaneCa => new Plane(EdgeCa.A, Vector3.Cross(TriNorm, EdgeCa.Delta  ));

    public static readonly  RangeDouble Zero1 = new RangeDouble(0,1);

    public Vector3 ClosestPointTo(Vector3 p)
    {
        // Find the projection of the point onto the edge

        var uab = EdgeAb.Project( p );
        var uca = EdgeCa.Project( p );

        if (uca > 1 && uab < 0)
            return A;

        var ubc = EdgeBc.Project( p );

        if (uab > 1 && ubc < 0)
            return B;

        if (ubc > 1 && uca < 0)
            return C;

        if (ZeroToOne.Contains( uab ) && !PlaneAb.IsAbove( p ))
            return EdgeAb.PointAt( uab );

        if (ZeroToOne.Contains( ubc ) && !PlaneBc.IsAbove( p ))
            return EdgeBc.PointAt( ubc );

        if (ZeroToOne.Contains( uca ) && !PlaneCa.IsAbove( p ))
            return EdgeCa.PointAt( uca );

        // The closest point is in the triangle so
        // project to the plane to find it
        return TriPlane.Project( p );

    }
}

And the edge structure
public struct Edge3
{

    public readonly Vector3 A;
    public readonly Vector3 B;
    public readonly Vector3 Delta;

    public Edge3(Vector3 a, Vector3 b)
    {
        A = a;
        B = b;
        Delta = b -a;
    }

    public Vector3 PointAt(double t) => A + t * Delta;
    public double LengthSquared => Delta.LengthSquared();

    public double Project(Vector3 p) => (p - A).Dot( Delta ) / LengthSquared;

}

And the plane structure
public struct Plane
{
    public Vector3 Point;
    public Vector3 Direction;

    public Plane(Vector3 point, Vector3 direction )
    {
            Point = point;
            Direction = direction;
    }

    public bool IsAbove(Vector3 q) => Direction.Dot(q - Point) > 0;

}

A: Assuming you're using one of the known fast algorithms, the only way to speed it up is when you are doing a lot of measurements on a lot of triangles. In that case, you can keep a lot of quantities precomputed in "edge" or "winding" structures. Instead of storing the 3 points, you store meshes comprised of edge structures. Projection then becomes very quick and barycentric tests can be coded so that they are branch-predictable.
The real key is to just keep everything in cache. Processors can do MUL and DIV in nearly 1 clock cycle so memory is usually the bottleneck.
Also, consider writing the algo in SSE3 or something similar (such as Mono's SIMD support). It's work, but you can usually do a couple triangles at a time if you think hard enough about it.
I'll try to find some papers on the topic, but you might want to Google for "Ray Mesh Intersection". That will bring up all the great work from the 80s and 90s when people worked hard on optimizing this stuff.

A: I don't think the barycentric coordinate method can be sped up much per se, but you can pre-compute some some things if you will be testing many points against the same triangle.
Here is some robust code that I wrote for computing this projection, based on this answer combined with this post (which is in turn based on the book Realtime Collision Detection).
Note that you can precompute anything that doesn't depend directly or indirectly upon p (which saves around half the computational work for each test, if you're reusing the same triangle many times).
The code is designed to return null if the orthogonal projection of the point p onto the plane of the triangle does not fall within the triangle. You could extend this to find the closest point on the edge of a triangle if the barycentric coordinates are out of range, by computing the projection of the projection point onto each of the triangle's edge vectors, then checking whether the projection is within any pair of the triangle's vertices. (If not, a corner vertex would be the closest point.) For my purposes though, I only wanted orthogonal projections, which is why this code returns null if the orthogonal projection does not fall within the triangle.
The code is in Java, using the JOML linear algebra library.
/**
 * Find the closest orthogonal projection of a point p onto a triangle given by three vertices
 * a, b and c. Returns either the projection point, or null if the projection is not within
 * the triangle.
 */
public static Vector3d closestPoint(Vector3d p, Vector3d a, Vector3d b, Vector3d c) {
    // Find the normal to the plane: n = (b - a) x (c - a)
    Vector3d n = b.sub(a, new Vector3d()).cross(c.sub(a, new Vector3d()));

    // Normalize normal vector
    double nLen = n.length();
    if (nLen < 1.0e-30) {
        return null;  // Triangle is degenerate
    } else {
        n.mul(1.0f / nLen);
    }

    //    Project point p onto the plane spanned by a->b and a->c.
    //
    //    Given a plane
    //
    //        a : point on plane
    //        n : *unit* normal to plane
    //
    //    Then the *signed* distance from point p to the plane
    //    (in the direction of the normal) is
    //
    //        dist = p . n - a . n
    //
    double dist = p.dot(n) - a.dot(n);

    // Project p onto the plane by stepping the distance from p to the plane
    // in the direction opposite the normal: proj = p - dist * n
    Vector3d proj = p.add(n.mul(-dist, new Vector3d()), new Vector3d());

    // Find out if the projected point falls within the triangle -- see:
    // http://blackpawn.com/texts/pointinpoly/default.html

    // Compute edge vectors
    double v0x = c.x - a.x;
    double v0y = c.y - a.y;
    double v0z = c.z - a.z;
    double v1x = b.x - a.x;
    double v1y = b.y - a.y;
    double v1z = b.z - a.z;
    double v2x = proj.x - a.x;
    double v2y = proj.y - a.y;
    double v2z = proj.z - a.z;

    // Compute dot products
    double dot00 = v0x * v0x + v0y * v0y + v0z * v0z;
    double dot01 = v0x * v1x + v0y * v1y + v0z * v1z;
    double dot02 = v0x * v2x + v0y * v2y + v0z * v2z;
    double dot11 = v1x * v1x + v1y * v1y + v1z * v1z;
    double dot12 = v1x * v2x + v1y * v2y + v1z * v2z;

    // Compute barycentric coordinates (u, v) of projection point
    double denom = (dot00 * dot11 - dot01 * dot01);
    if (Math.abs(denom) < 1.0e-30) {
        return null; // Triangle is degenerate
    }
    double invDenom = 1.0 / denom;
    double u = (dot11 * dot02 - dot01 * dot12) * invDenom;
    double v = (dot00 * dot12 - dot01 * dot02) * invDenom;

    // Check barycentric coordinates
    if ((u >= 0) && (v >= 0) && (u + v < 1)) {
        // Nearest orthogonal projection point is in triangle
        return proj;
    } else {
        // Nearest orthogonal projection point is outside triangle
        return null;
    }
}

A: There are different approaches to finding the distance from a point P0 to a triangle P1,P2,P3.

*

*The 3D method.
Project the point onto the plane of the triangle and use barycentric coordinates or some other means of finding the closest point in the triangle.  The distance is found in the usual way.

*The 2D method.  Apply a translation/rotation to the points so that P1 is on the origin, P2 is on the z-axis, P3 in the yz plane.  Projection is of the point P0 is trivial (neglect the x coordinate).  This results in a 2D problem. Using the edge equation it's possible to determine the closest vertex or edge of the triangle.  Calculating distance is then easy-peasy.
This paper compares the performance of both with the 2D method winning.

A: To find the distance, first one has to compute the closest point in triangle. The following code for finding the closest point in 3D triangle ABC to point P is taken from highly optimized Embree library:
Vec3fa closestPointTriangle(Vec3fa const& p, Vec3fa const& a, Vec3fa const& b, Vec3fa const& c)
{
  const Vec3fa ab = b - a;
  const Vec3fa ac = c - a;
  const Vec3fa ap = p - a;

  const float d1 = dot(ab, ap);
  const float d2 = dot(ac, ap);
  if (d1 <= 0.f && d2 <= 0.f) return a; //#1

  const Vec3fa bp = p - b;
  const float d3 = dot(ab, bp);
  const float d4 = dot(ac, bp);
  if (d3 >= 0.f && d4 <= d3) return b; //#2

  const Vec3fa cp = p - c;
  const float d5 = dot(ab, cp);
  const float d6 = dot(ac, cp);
  if (d6 >= 0.f && d5 <= d6) return c; //#3

  const float vc = d1 * d4 - d3 * d2;
  if (vc <= 0.f && d1 >= 0.f && d3 <= 0.f)
  {
      const float v = d1 / (d1 - d3);
      return a + v * ab; //#4
  }

  const float vb = d5 * d2 - d1 * d6;
  if (vb <= 0.f && d2 >= 0.f && d6 <= 0.f)
  {
      const float v = d2 / (d2 - d6);
      return a + v * ac; //#5
  }

  const float va = d3 * d6 - d5 * d4;
  if (va <= 0.f && (d4 - d3) >= 0.f && (d5 - d6) >= 0.f)
  {
      const float v = (d4 - d3) / ((d4 - d3) + (d5 - d6));
      return b + v * (c - b); //#6
  }

  const float denom = 1.f / (va + vb + vc);
  const float v = vb * denom;
  const float w = vc * denom;
  return a + v * ab + w * ac; //#0
}

Here dot(p,q) = p.x*q.x + p.y*q.y + p.z*q.z is dot product of vectors p and q.
The algorithm is based on partitioning the plane with the triangle on 7 regions by drawing two rays from each vertex outside the triangle orthogonal the adjacent edges of the vertex:

Each if in the algorithm corresponds to Region #1-6. And the section after the last if - to triangle's internals or Region #0.


text:
Q: LibreOffice : how shall I change the names of the weekdays in date format In LibreOffice, I wish to change the weekdays names to have something shorter.
In French, the date format "ddd dd/mm/yy" applied to today 2021-08-17 gives : "mar. 17/08/21". I would prefer "ma 17/08/21" to have narrower columns.
So I wish to change the existing weekdays names "lun., mar., mer., jeu., even., sam., dim." to something shorter : "lu, ma, me, je, ve, sa, di", through the format used by LibreOffice.
I played with French locales (Swiss French, etc.) but it is not satisfactory. I tried to change the list for the sort but it has no effect on the date format.
Is it possible to change the list LibreOffice uses for the weekdays ? How shall I proceed ?

A: You cannot do this with normal formatting (unless you require a change to the national date standard).
However, you can easily get the desired date representation using the TEXTE() and REGEX() functions.
=REGEX(TEXT(A1;"OOO JJ/MM/AA");"(..)([^\.]*\.)(.+)";"$1$3";"g")
Or shorter notation using LEFT() (GAUCHE()):
=LEFT(TEXT(A1;"OOO");2)&TEXT(A1;"\ JJ/MM/AA")
Remember to check that the cell format is French, otherwise you will get an error (not every language uses O-J-A characters)


text:
Q: Dynamically populate taxonomy term dropdown filter menus based on WP_Query I have created a filterable products archive page where you can filter by three taxonomies, product_cat, pa_manufacturer & pa_colour. I'm trying to set it up so the dropdown menus are dynamically updated based on the terms of the posts being queried.
A good example of this is on the ASOS website: https://www.asos.com/men/ctas/fashion-online-1/cat/?cid=13498&ctaref=hp|mw|prime|hero|1|edit|asosdesign where if you select a category, you will see all the other dropdown menus are being updated automatically.
I've kind of got this working by creating a separate WP_Query to get all the post ids based on all the original query and then using the wp_get_object_terms() for each taxonomy to only get the terms for the post ids selected.
This works, however the issue i've got now is when a user just selects a single taxonomy, for example, 'cooking' from product category. It will only show 'cooking' in the selected dropdown menu, meaning the user can't select multiple terms unless they deselect the 'cooking' category first.
If you look at ASOS, this doesn't apply and it allows the user to select multiple categories if they are just searching by a single filter, for example 'category'. However as soon as you filter by 'product type' too, it will then hide the options from the category dropdown.
Does anyone have a solution to make this work like ASOS?
/** @global WP_Query $wp_query */
global $wp_query;

$args         = [];
$tax_query    = $wp_query->tax_query->queries;
$buffer_query = $wp_query->query;

$selected_terms = [];
foreach ( $tax_query as $tq ) {
    if ( $tq === 'AND' || $tq === 'OR' || $tq['taxonomy'] === 'product_visibility' ) {
        continue;
    }
    $selected_terms[ $tq['taxonomy'] ] = $tq;
}

$buffer_query_args = [
    'nopaging' => true,
    'fields'   => 'ids',
];

foreach ( $selected_terms as $selected_term ) {
    $buffer_query_args['tax_query'][] = $selected_term;
}

$custom_query          = new WP_Query( array_merge( $buffer_query, $buffer_query_args ) );
$product_categories    = wp_get_object_terms( $custom_query->posts, 'product_cat', [ 'parent' => 0 ] );
$product_manufacturers = wp_get_object_terms( $custom_query->posts, 'pa_manufacturer', [ 'parent' => 0 ] );
$product_colours       = wp_get_object_terms( $custom_query->posts, 'pa_colour', [ 'parent' => 0 ] );

/**
 * Get $product_filters
 *
 * @var $product_filters
 */
$product_filters = [
    [
        'label'  => __( 'Category' ),
        'slug'   => 'product_cat',
        'values' => $product_categories
    ],
    [
        'label'  => __( 'Manufacturer' ),
        'slug'   => 'pa_manufacturer',
        'values' => $product_manufacturers
    ],
    [
        'label'  => __( 'Colour' ),
        'slug'   => 'pa_colour',
        'values' => $product_colours
    ],
];
?>

<?php _e( 'Filter by' ); ?>:

    <form class="product-filters" method="GET">
        <?php foreach ( $product_filters as $product_filter ) : ?>
            <?php

            $label  = $product_filter['label'];
            $slug   = $product_filter['slug'];
            $tax    = get_taxonomy( $slug );
            $values = $product_filter['values'];

            ?>

                <label for="product_filter_<?php echo esc_attr( $slug ); ?>">
                    <?php echo esc_html( $product_filter['label'] ); ?>
                    <select
                            data-placeholder="<?php echo esc_html( $product_filter['label'] ); ?>"
                            name="<?php echo esc_attr( $slug ); ?>[]"
                            class="product-ajax-filter"
                            id="product_filter_<?php echo esc_attr( $slug ); ?>" multiple="multiple">

                        <?php foreach ( $values as $value ) : ?>
                            <?php
                            $selected = is_array( $_GET[ $slug ] ) && in_array( $value->slug, $_GET[ $slug ] );
                            ?>
                            <option value="<?php echo esc_attr( $value->slug ); ?>"
                                <?php echo $selected ? 'selected' : ''; ?>>
                                <?php echo esc_html( $value->name ); ?>
                            </option>

                        <?php endforeach; ?>
                    </select>

        <?php endforeach; ?>

            <input type="submit" value="<?php _e( 'Submit' ); ?>">

    </form>


text:
Q: MCU pull down input push button with interrupt ESD issue I have an MCU operated at 3 volt with an input pin that is floating by default. I have an external pull down circuit with a 10K resistor connected to the I/O pin. I also have it tied to VCC using a push button. The microprocessor is sleeping until the button is pressed (it is configured to generate an interrupt when the I/O line become high).
The solution have worked flawless, have tested it for months. Last week however I soldered a new batch of 16 units and when I inserted them inte their plastic case I noticed that some of the woke up and started processing and I did not press the button. I now have two theories and would like to know how likely they are:

*

*ESD has damaged the MCU? Personally I do not think so, since I have seen the same problem on at least 7 devices occasionally. This combined with that they work flawless in all other aspects makes me think that this is not the case.

*ESD pulls the line high occasionally when I insert it into the plastic enclosure and in this way the interrupt is triggered in the MCU. Sounds reasonable, I guess a very short ESD near the pins would actually wake up the device. Maybe the reason I see it now and not before is because of winter and a more dry air?
Am I thinking correct here?

*I would also like to know if I need to protect the pin in some way and suggestions on how to do this if required. I read that the chip (TI cc2540) is ESD protected but I don't know if it is enough, maybe it needs more protection. Maybe it has enough protection but I still need to handle short spikes in software.

A: I think #2 is quite plausible, especially since you mentioned plastic case.  You probably generated some static electricity while handling the plastic case, and that got discharged thru the switch line.  The switch is probably sticking out more than other things, so would be more likely to get zapped.
If this only happens when you first install the board in the case, then you can just ignore if necessary.  However, something is marginal, and I'd want to make the system more robust.  There are various options:
*

*Make the pulldown stiffer.  If this unit is not battery powered, then changing the 10 kΩ to 1 kΩ is a easy thing to do.  That will use 25 mW when the switch is pressed.  If this is line powered, than that's irrelevant.

*Put a capacitor to ground on the switch line.  This will require more charge on the line before it gets to a logic high level.  A 1 uF ceramic is cheap and small.  Even with the 10 kΩ pulldown, that's still only 10 ms time constant, so is irrelevant in human time.

*Put a R-C low pass filter after the switch and pulldown.  For example, another 10 kΩ in series followed by 1 µF to ground.  The extra delay is still irrelevant in human time since you have 10 ms time constant towards the switch on state and 20 ms towards the switch off state.  This will definitely filter out short spikes, and provides additional impedance for the pin protection circuitry to work against.


text:
Q: How to configure Kubernetes initContainers runs after the other finished I have a situation where I want to speed up deployment time by caching the git resources into a shared PVC.
This is the bash script I use for checkout the resource and save into a share PVC folder
#!/bin/bash
src="$1"
dir="$2"

echo "Check for existence of directory: $dir"
if [ -d "$dir" ]
   then
     echo "$dir found, no need to clone the git"
  else
     echo "$dir not found, clone $src into $dir"
     mkdir -p $dir
     chmod -R 777 $dir
     git clone $src $dir
     echo "cloned $dir"
fi

Given I have a Deployment with more than 1 pods and each of them have an initContainer. The problem with this approach is all initContainers will start almost at the same time.
They all check for the existence of the git resource directory. Let's say first deployment we dont have the git directory yet. Then it will create the directory, then clone the resource. Now, the second and third initContainers see that the directory is already there so they finish immediately.
Is there a way to make other initContainers wait for the first one to finish?
After reading the kubernetes documentation, I don't think it's supported by default
Edit 1:

*

*The second solution I can think of is to deploy with 1 pod only, after a successful deployment, we will scale it out automatically. However I still don't know how to do this

A: I have found a workaround. The idea is to create a lock file, and write a script to wait until the lock file exists. In the initContainer, I prepare the script like this
#!/bin/bash
src="$1"
dir="$2"

echo "Check for existence of directory: $dir/src"
if [ -d "$dir/src" ]
   then
      echo "$dir/src found, check if .lock is exist"
      until [ ! -f $dir/.lock ]
      do
         sleep 5
         echo 'After 5 second, .lock is still there, I will check again'
      done
      echo "Finish clone in other init container, I can die now"
      exit
   else
      echo "$dir not found, clone $src into $dir"
      mkdir -p $dir/src
      echo "create .lock, make my friends wait for me"
      touch $dir/.lock
      ls -la $dir
      chmod -R 777 $dir
      git clone $src $dir/src
      echo "cloned $dir"
      echo "remove .lock now"
      rm $dir/.lock
fi

This kind of like a cheat, but it works. The script will make other initContainers wait until the .lock is remove. By then, the project is cloned already.


text:
Q: Flask - Can i perform another request in the middle of an AJAX call. So i have an ajax function in my javascript that posts to my flask backend.
Can I succesffuly make the call to /another_ajax_url ?
@app.route('/myroute', methods=['POST, GET'])
def test():
    a = 2 + 2
    requests.post('/another_ajax_url', data = a)
    #do the other stuff and return to /myroute
    b = 3 + 3
    return jsonify(b=b)

A: Yes, you can do that but you may prefer to use something like celery if you don't need the result.
Doing an http request inside the client request will block the client until the request is completed and the remaining of your code executed.


text:
Q: Enabling hardware acceleration in Firefox I'm using Ubuntu 20.04.3 on AMD Ryzen 3 5300U with Renoir graphics, running Firefox 93 x64 on X11. I followed the guide on ArchWiki, but even though MOZ_LOG_="PlatformDecoderModule:5" firefox displays output
libva info: VA-API version 1.7.0
libva info: Trying to open /usr/lib/x86_64-linux-gnu/dri/radeonsi_drv_video.so
libva info: Found init function __vaDriverInit_1_7
libva info: va_openDriver() returns 0

This is all the output of the log. The VA-API got one frame output... isn't shown at all, plus the CPU usage for Firefox hovers at 56-68%. I've set environment variables in .profile as
export MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_X11_EGL=1

What is preventing Firefox from using hardware acceleration here? The mpv successfully uses VA-API and CPU load for 1080p video is around 12-14% so I assume all the VA-API drivers are installed and working if used at all.
Edit: with MOZ_LOG="Dmabuf:5, PlatformDecoderModule:5" firefox I get the following output:
[Child 14739: MediaPDecoder #2]: D/PlatformDecoderModule VA-API Got one frame output with pts=0dts=0 duration=17000 opaque=-9223372036854775808
[Child 14739: MediaPDecoder #2]: D/Dmabuf DMABufSurfaceYUV::CreateYUVSurface() UID 1 from desc
[Child 14739: MediaPDecoder #2]: D/Dmabuf DMABufSurfaceYUV::UpdateYUVData() UID 1
[Child 14739: MediaPDecoder #2]: D/Dmabuf     plane 0 size 1920 x 1080 format 20203852
[Child 14739: MediaPDecoder #2]: D/Dmabuf     plane 1 size 960 x 540 format 38385247
[Child 14739: MediaPDecoder #2]: D/PlatformDecoderModule Created new VA-API DMABufSurface UID = 1
[Child 14739: MediaPDecoder #2]: D/PlatformDecoderModule VideoFrameSurfaceDMABuf: creating surface UID = 1
[Child 14739: MediaPDecoder #2]: D/PlatformDecoderModule VideoFrameSurfaceVAAPI: VAAPI locking dmabuf surface UID = 1

Full log here. Can this indicate VA-API is actually being used? If it really is VA-API, then why is the CPU usage high and after watching a video for 5 minutes continuously the fan gets loud?

A: A better way to check accelerated video decoding is through command sudo watch cat /sys/kernel/debug/dri/0/amdgpu_pm_info and check whether VCN or UVD enables when a video is played. If it stays disabled, then the video is software decoded. In my case VCN enables whenever firefox or mpv plays the video and stays disabled in chromium and opera. On newer cards, we need not use the enhanced-h264ify extension as VP8/VP9 is decoded in hardware.
Removing export MOZ_DISABLE_RDD_SANDBOX=1 doesn't affect firefox VCN capability.


text:
Q: foregroundColor for Textfield in swift Dears,
I'm learning swift and I'm trying to color a textfield text, the issue now is that the color is not applied to the text. please find the code next:
     let textStyle:[String:Any] = [
        NSAttributedStringKey.strokeColor.rawValue: UIColor.black,
        NSAttributedStringKey.foregroundColor.rawValue: UIColor.white,
        NSAttributedStringKey.font.rawValue: UIFont (name: "Impact", size: 50)!,
        NSAttributedStringKey.strokeWidth.rawValue: 3.5
        ]

Thanks

A: The key appears to be the .strokeWidth... If you want stroke and fill, the stroke width needs to be a negative value.
Give this a try:
    let textStyle = [
        NSAttributedStringKey.strokeColor: UIColor.black,
        NSAttributedStringKey.foregroundColor: UIColor.white,
        NSAttributedStringKey.font: UIFont(name: "Impact", size: 50)!,
        NSAttributedStringKey.strokeWidth: -3.5
    ]

A: can you try this...
myTextField.attributedText = NSAttributedString(string: "text",
                         attributes: [NSAttributedStringKey.foregroundColor: UIColor.white])


text:
Q: Work done by moving an object up a hill I was doing this problem:

A body of mass m was slowly hauled
up the hill by a force $F$ which at
each point was directed along a tangent to the
trajectory. Find the work performed by this
force, if height of the hill is $H$, the length of it's base is $L$ and the coefficient of the friction is $K$.

I started with summing up all forces that acts on the object
$$\sum{F_{total} = F -mg\sin\theta - Kmg\cos\theta = F - mg(\sin\theta +K\cos\theta) = ma}$$
then
$$dW = \sum{F_{total} \cdot \mathrm ds =[F - mg(sin\theta +K\cos\theta)}]\cdot\mathrm ds \tag{**}$$
then I assumed the height of the hill depends on the length of the base, so I wrote $f(x)=h$, $ $ $f(L)=H $ and $f(0) = 0$
then I wrote $$ \cos\theta =\frac{1}{\sqrt{1+(f^{'}(x))^2}},\qquad \sin\theta = \frac{f^{'}(x)}{\sqrt{1+(f^{'}(x))^2}},  \qquad ds = \sqrt{1+(f^{'}(x))^2}\,\mathrm dx$$
I plugged those into the $(**)$ equation and got this:
$$
dW=\big[F-mg(f^{'}(x) +K)\big]dx \\
W=\int_0^{L}\big[F-mg(f^{'}(x) +K)\big]dx \\
W=\int_0^{L}Fdx - mg\int_0^{L}(f^{'}(x)+K)dx\\
W=\int_0^{L}Fdx -mg(H+KL)
$$
So I am stuck here trying to find what $F$ is...
Edit:
I think I did it, so here it is :
$$ W=\int_0^{L}\sum{F}=\int_0^{L}F\,\mathrm dx -mg(H+KL)\\
\int_0^{L}ma\,\mathrm dx=\int_0^{L}F\,\mathrm dx -mg(H+KL)\\
W_F=\int_0^{L}F\,\mathrm dx=maL +mg(H+KL)\\$$
Answer: $W_F=maL +mg(H+KL)$
I guess this is for general case because in my textbook answer was $W_F=mg(H+KL)$ so, I suspect  $ a = 0$ in this case, but why acceleration is $0$?

A: The applied force does work on the body. This work can achieve three things here : (i) it can overcome friction ($mgKL$), (ii) it can increase the gravitational potential energy of the body ($mgH$), and (iii) it can increase the kinetic energy of the body ($maL$). The problem states that the body is "slowly hauled" which implies that there is no increase in its kinetic energy, which means there is no acceleration ($a=0$). The force varies so as to ensure that there is no acceleration.
If the applied force is constant there may in fact be acceleration on some parts of a non-linear trajectory, but then there is deceleration on others. The body ends with the same slow speed (and kinetic energy) as it started, so there is no acceleration.

A: Whenever the question says "slowly" it generally means that the force is just enough to cancel other forces and just get the object in motion with a uniform velocity and no acceleration.


text:
Q: jQuery Fade-In Not working So here's my problem, I want an image to appear after a delay of 4 seconds, but this just doesn't work, can you help? Below the codes I have;
html (index.html):
<!DOCTYPE html>

<meta charset="utf-8">

<title>Welcome to DayZ</title>
<link rel="shortcut icon" href="http://dayzgame.com/assets/img/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/fadein.css">

<audio autoplay>
<source src="intro.mp3" type="audio/mpeg">
<source src="intro.ogg" type="audio/ogg">
<embed height="50" width="100" src="horse.mp3">
</audio>

//this is the code for the image to display

CSS (fadein.css):
.delayImg {opacity:0;}

JavaScript (button_fade.js):
$(document).ready(function() {
$(".delayImg").each(function() {
    this.onload = function() {
        $(this).animate({opacity: 1}, 4000);
    };
    this.src = this.getAttribute("delayedSrc");
});
});

A: You need to load the scripts in this order:

A: $(document).ready(function() {
      $(".delayImg").each(function() {
      $(this).onload = function() {
      $(this).animate({opacity: 1}, 4000);
   };
   $(this).src = $(this).getAttribute("delayedSrc");
   });
});

use $(this) insted of just this


text:
Q: How to get the value of a Theano.tensor variable? I have to do something like this:
import Theano.tensor as tt

a = 2
b = 3
c = tt.arctan2(a,b)

c has now as output Elemwise{arctan2,no_inplace}.0. How can I get the computed value of the function? Have already read here that I need to compile the Theano function, but didn't really understood how... Can someone please help me?
Thanks in advance

A: In theano you first need to define your variables as symbols. Then you define a function with those symbols. A theano.function has a List of input parameters and the function which should be executed as parameters.
Once that is done, you can compute your function by substituting the symbols with actual values.
from theano import function
import theano.tensor as tt

a = tt.dscalar('a')
b = tt.dscalar('b')
f = theano.function([a,b], tt.arctan2(a, b))
f(2, 3)

This will output:
array(0.5880026)


text:
Q: How much should I pay to Microsoft when I am selling a desktop & Web base software built on VB.NET using MS SQL 2005 Express Edition? Can I distribute the MS SQL 2005 Express edition along with my application to the customer?

A:
Can i distribute the MS SQL 2005 Express edition

You need to register for the free redistribution rights in order to do so. The contact details are here. Not doing so may mean you are doing something illegal.
From the SQL Server 2005 express download page:

Building and shipping applications with SQL Server Express? Sign up for free redistribution rights here.

You don't have to pay Microsoft when you sell software created using their tools. You may have to pay if you wish to redistribute the tools.


text:
Q: Parts of the UI not showing in a release version I have a flutter app that runs perfectly in debug mode on android emulator, physical device even the release version of the iOS is fine. but on the android release apk the issue appears. it doesn't show a grid view on the home page.
as in the screenshots below.

enter image description here

A: It because you didn't observe the error shown during debug.

Try to run it in debug mode again, check your debug console, there is a warning from the widget. perhaps the alignment of with and height...the log will tel you what is wrong.

Fix and you will be fine

A: The solution for this issue is that you need to fix an error of this type :

Incorrect use of ParentDataWidget Error in Flutter

It seems clean but flutter in debug mode doesn't pay strict attention to the tree order which is not the same case in the release mode and this cause a UI problem, technicaly :

This error occurs when the Child widget has not matched the parent
widget

To solve this error, your child widget must have the expected parent widget. Some of the widget and their parent widgets are:

Make sure to have the right parent for all the widgets using this Table, and you will be good to go!


text:
Q: Push maven project from Bamboo to Nexus I need to set-up plan to push maven project from Bamboo to Nexus. I can connect to GitHub from bamboo, but when I'm running the plan, I'm getting:
Return code is: 401, ReasonPhrase: Unauthorized.

I have all plugins configured in my POM, but I'm guessing, I'm not able to pass some credentials for Nexus from maven settings.xml
How can I pass this Nexus credentials to Bamboo?


text:
Q: Disable Keyboard Shortcuts on Webpage I am working with some others on a web based javascript game, and there is a small issue where occasionally keyboard shortcuts can get in the way. sometimes for example, one might accidentally press Alt+W and that can be annoying (and sometimes a little scary depending on what your doing).
So i would like to know, is there any way to use javascript to disable shortcuts on a webpage? i have looked around quite a lot and have not found anything about how to do this

A: you need to use key codes. try with something like this:
window.onload = function() {
    window.document.body.onkeydown = function() {
        if (event.ctrlKey) {
            event.stopPropagation();
            event.preventDefault();
            try {
                event.keyCode = 0;
            }
            catch (event) {

            }
            return false;
        }
        return true;
    }
}


text:
Q: How to send ETH to a contract function with ethers.js? I am trying to send ETH to a contract function from a web app via metamask and ethers.js. So far I have tried:
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
const splitterManager = new ethers.Contract(contract.address, contract.abi, signer);
var overrides = {value: 5}
const result = await splitterManager.newSplitter(addresses, shares, erc20, overrides);
console.log(result);

But I keep getting 'Error: resolver or addr is not configured for ENS name (argument="name", value="", code=INVALID_ARGUMENT, version=contracts/5.2.0)'.

A: You can call the contracts function and pass it an object containing a value key.
contractInstance.testFunction(<any function args>, { value: ethers.utils.parseUnits("1", "ether") });

This would call your contract's function and send that amount of wei to the contract.
function testFunction() public payable {
    // contract code
}

A: If the contract has implemented the receive function, you can send ether to a contract same as sending ether to any other account. Here's a short example:
const accounts = await provider.listAccounts();
const signer = provider.getSigner(accounts[0]);
tx = {
    to: **CONTRACT_ADDRESS**,
    value: ethers.utils.parseEther('2', 'ether')
};
const transaction = await signer.sendTransaction(tx);

A: await contractInstance
  .connect(rpcProvider)
  .function({
    value: ethers.utils.parseUnits("1","ether")
  });

this should work

A: some address is an invalid address it could be the contract.address, the addresses, or some other address


text:
Q: $f(x)$ is positive, continuous, monotone and integrable in (0,1]. Is $\lim_{x \rightarrow 0} xf(x) = 0$? I'm having trouble with this question from an example test.
We have a positive function $f(x)$ that's monotone, continuous and integrable in $(0,1]$. Is $\lim_{x \rightarrow 0} xf(x) = 0$?
Progress
The only problematic case seems to be when $f(x)$ is unbounded and monotonic decreasing. For that case, I found out that $xf(x)=\int_{0}^{x} f(x)dt$ and that $0\leq xf(x)\leq \int_{0}^{x} f(t)dt$. From here I'm not sure how to go on.
Thanks!

A: If $f$ is improperly integrable over $[0,1]$, then $\lim\limits_{a\rightarrow0^+}\int_a^1 f(x)\,dx=L$ for some finite number $L$.
Note, for any $b$ in $(0,1)$:
$$\eqalign{
L =\int_0^1f(x)\,dx  = \int_0^bf(x)\,dx +\int_b^1f(x)\,dx\cr
}
$$
Now, letting $b\rightarrow0^+$, we have that $ \int_b^1f(x)\,dx$ converges to $L$, which implies that
$$
\lim_{b\rightarrow0^+}\int_0^b f(x)\,dx=0.
$$

A: If $f$ is increasing, then $\lim_{x \to 0^+} f(x) = C < +\infty$ exists, so that the result is trivial.
If $f$ is decreasing, $c < x$ implies $f(c) \ge f(x)$. Now by the mean value theorem for integrals, for every $0 < x < 1$, there exists $0 < c(x) < x$ such that
$$
\int_0^x f(t) \, dt = f(c(x))x.
$$
This gives
$$
0 \le x f(x) \le x f(c(x)) = \int_0^x f(t) \, dt \to 0.
$$
Hope that helps,

A: If there is some $\beta > 0$ and $L>0$ so that $xf(x)  \ge L$ on $(0,\beta)$, then
$f(x) \ge L/x$ on $(0,\beta)$  and hence
$$
\int_0^\beta f(x) dx
$$
doesn't exist.
Otherwise for every $L$ there is a decreasing sequence $\{u_{L,n}\} \to 0$ such that
$u_{L,n}f(u_{L,n}) < L$. Hence by monotonicity,  $xf(x) < L$ on $(0,u_{L,1})$.
Now let $L\to 0$. It follows that $xf(x) \to 0$.

A: Just a longer comment - I'll show that improper integrals are continuous.
Improper integral on $(0,1]$ is just the limit of regular integrals on $[\delta,1]$. If the limit $L$ exists, then for $\delta < \delta_0$ this integral is $\varepsilon$-close to L. From the triangle inequality we know, that two integrals on $[\delta,1]$ and $[\delta',1]$ are $2\varepsilon$-close (note that $\delta,\delta'$ might also be zero here, then we get just $\varepsilon$). It means that when we integrate on an interval included in $[0,\delta_0]$, then the result is smaller than $2\varepsilon$. Moreover on $[\delta_0,1]$ the function is bounded by some $M$ (from its integrability). So, if we take an interval $[a,b]$ shorter than $\min(\delta_0,\varepsilon/M)$, then (by triangle inequality) the integral is smaller than $2\varepsilon + \varepsilon=3\varepsilon$, which shows the continuity of an improper integral.

A: As you pointed out $0\leq x f(x) \leq \int_{0}^{x} f(t)\, dt$. But $F(x):= \int_{0}^{x}f(t)\, dt$ is continuous, so $\lim_{x\to 0} F(x) = F(0) = 0$, and the result follows from the squeeze theorem.


text:
Q: Which model to use with repeated measures data that contains multiple binary dependent variables What model should I use???  I have daily repeated measures data.  It has multiple dependent presence absence variables, (of which, I have collapsed into a CA with continuous variables of CA1 & CA2....or I can choose to not collapse the data and leave each dependent variable as a binary variable).  My independent variables are weather data that was collapsed into a PCA (or I can use each individual weather measurement), 2 categorical variables, and time (or a covariate of time).  I am wanting to create a model that allows me to solve for time (or the covariate of time). I have been looking at SEM latent growth models, logistic regression, time series, or mixed regression models.  The software that is available to me is SAS, SPSS, PCord, and Canoco.
"Gung":More information:  CA: correspondence analysis.  Presence and absence of insects on decomposing organisms that were measured periodically, mostly daily for the first 2 months and then periodically after that as insect presence greatly decreased.  Two organisms were put out in the spring at different times, then some more in the summer, then fall, then winter.  The time component that I am wanting to predict is how long that the organism has been decaying...so once I have a model of my data, I could put in all of the measurable variables of a decomposing organism that I find, and solve for time (decomposition day: how many days that the body has been decomposing).  By covariate of time, which I think would actually be a better predictor is accumulated degree days (ADD).  This is the sum of the daily min and max temp divided by two since the start of decomposition.  This represents the accumulated heat units of the organism, and has been shown to influence different species of insects.  EX) typically, flies are the first to a decomposing organism, so at smaller ADD values.  Later, beetles appear at large ADD values.  All of my independent variables have had literature published that suggest that they influence insect occurrence.  As a second part, I would like to look at the rate of change in community structure (or insect occurrence) over time...or meaning as decomposition progresses.  Thank you so much for any advice!!

A: I now think that my data may be applied to a Generalized Estimating Equations (GEE) model.  This is an extension of a generalized linear model that allows me to account for repeated measures.  Does anyone disagree?


text:
Q: Unique page depending on id Im trying to add a unique page for each row in database. so when i click video.php?id=1
it will show the page of the row where the id=1
i have tried with following code, but it just give me the error: unexpected T_VARIABLE
my code is following:
<?php
include "connect.php";

$id = $_GET['id']
$query = mysql_query("SELECT * FROM article WHERE id='".$id."' ");

   while ($row = mysql_fetch_array($query)) {

        <? echo $row[name]; ?>
        <? echo $row[title]; ?>

   }

?>

A: You forgot to add a semicolon here
$id = $_GET['id'];
-----------------^

EDIT :
Change your echo variables from
<? echo $row[name]; ?>
<? echo $row[title]; ?>

to
echo $row['name'];
echo $row['title'];

Tips :

*

*Don't use mysql_ functions, as they will be deprecated soon. Make use of PDO or MySQLi

*Try to sanitize the variables before you directly send it inside the query.

A: You're missing a semi-colon:
$id = $_GET['id'] // <-- here it is missing

should be:
$id = $_GET['id'];

A: use:
http://us2.php.net/mysql_real_escape_string
and try to debug the result like:
var_dump($row);