text:
Q: Successive glDrawArraysIndirect calls Let's say I want to launch a shader program with glDrawArraysIndirect, so I have a buffer which contains a vertex count at the start, followed by other data for the command. That buffer is bound as atomic counter buffer to the same shader program and the vertex shader is decreasing the vertex count by some rule. If the vertex count is not 0 at the end, the shader program should be relaunched. So this is done till the vertex count is 0.
But what is the best way to know if the program needs the be relaunched? Is it possible to do this completely without reading back data(the vertex count)? If not, what is the most efficient way to read the data back? I'm currently running the shader program in a loop with a fixed number of iterations for which it's guaranteed to decrease the vertex count to 0, but with this approach I'm throwing away time for draw calls with 0 vertices(around 3ms each), or is that still better than reading back data? I've got 10 draw calls, normally the vertex count is 0 at the 3rd - 6th draw call.

A: Any CPU readback operation is highly unlikely to be faster than leaving this stuff on the GPU. This is because it will have to provoke a full GPU/CPU synchronization, which will kill any hope of pipelining and asynchronous execution.
It's hard to say what an efficient way to do what you're doing is when you haven't said what exactly it is that you're doing. For example, would it be reasonable to develop a compute shader who's sole job is to compute compute how many iterations of each rendering command would be needed? If so, then the CS invocations could just build up a series of indirect rendering commands, which can be dispatched in one shot via glMultiDrawIndirect.


text:
Q: Linux Ubuntu 12.04 Fortran77 OpenMP seg fault with ulimit -s unlimited I'm having a seg fault issue with a F77 script (to be given below) which employs OpenMP, when I increase the the index of a loop past a certain threshold. I realize this is a common issue, but I have found a work around on a mac, and am trying to figure out how to do the same thing on my linux machine.
The code is included below, and I apologize for its length - the majority of the script is devoted to setting up matrices to be multiplied via ZGEMM. Note, as I increase the number of equations, denoted by neq in my code, I get the aforementioned seg fault issues.
  program test2

  implicit none
  include 'omp_lib.h'
  integer neq, niv, Mt
  parameter (neq = 4*200)
  parameter (niv = neq/4)
  double precision y(neq), yp(neq), atol(neq), u(niv)
  integer m, j, kk, l, n, l1, l2, l3, i, ll, indsum, indsum2
  integer indsum3, i4, k, k1, k2,k3, k4, k5, k6, l2p, l2pp
  integer k3a, k3b
  double complex p(-niv:niv,-niv:niv), V(niv), resd2a,
 &  Vec(-niv:niv), p2(1:niv,-niv:niv)
  double complex qmat(-niv:niv,-niv:niv,-niv:niv)
  double complex qmat2(1:niv,-niv:niv)
  double complex sqmat(-niv:niv,-niv:niv,-niv:niv)
  double complex sqmat0(-niv:niv,-niv:niv,-niv:niv)
  double complex sqmat1(-niv:niv,-niv:niv,-niv:niv)
  double complex sqmat2(-niv:niv,-niv:niv,-niv:niv)
  double complex sqmat3(-niv:niv,-niv:niv,-niv:niv),
 &  C(-niv:niv,-niv:niv)
  double complex sqmat3b(-niv:niv,-niv:niv,-niv:niv),
 &  sqmat3c(-niv:niv,-niv:niv,-niv:niv)
  double complex q(-niv:niv,-niv:niv), q2(-niv:niv,-niv:niv),
 & smat(-niv:niv,-niv:niv,-niv:niv), alpha, beta
  double complex sumdum, sum1, sum2(niv), sum3(niv), qsum,
 &  resd, resd2, sumdum2, out(-niv:niv,-niv:niv)
  double complex ssum1, ssum2, forcing(niv)
  double precision seconds

  call omp_set_num_threads ( 16 )
  seconds = omp_get_wtime ( )

  write ( *, '(a)' ) ' '
  write ( *, '(a,i8)' )
 &  '  Number of processors available = ', omp_get_num_procs ( )
  write ( * ,'(a,i8)' )
 &  '  Number of threads =              ', omp_get_max_threads ( )
  y = 0
  do i = 1, niv
  y(i) = 0.1d0*i
  enddo
  do i = niv+1,2*niv
  y(i) = 0.2d0
  enddo

  do  j = -niv, niv
      do m = -niv, niv
      kk = m-j
      l = m-j
      k1 = m
      k2 = j
      k3a = m
      k3b = j
      k4 = m-j
      k5 = j
      k6 = m-j
      if (abs(kk) .gt. niv) then
      kk = 0
      else
      kk = 1
      end if
      if (k1 .eq. 0) then
      k1 = 0
      else
      k1=1
      end if
      if (k2.eq.0) then
      k2 = 0
      else
      k2 = 1
      end if
      if (k3a .eq. 0) then
      k3a=1
      else
      k3a=0
      end if
      if (k3b .eq. 0) then
      k3b=1
      else
      k3b=0
      end if
      if (k4 .eq. 0) then
      k4 = 0
      else
      k4 = 1
      end if
      if (k5 .eq. 0) then
      k5=2
      else
      k5=1
      end if
      if (k6 .eq. 0) then
      k6=2
      else
      k6=1
      end if
  p(m,j)=(0.5*k5*k6*kk*abs(k4*sign(1,m-j)-k2*sign(1,j))*cmplx(k4
 & *y(abs(m-j))+1-k4,k4*y(niv+abs(m-j))*sign(1,m-j))-0.5*cmplx(k1*
 & y(abs(m))+(1-k1), k1*y(abs(m)+niv)*sign(1, m))*cmplx(k2*y(abs(j
 & ))+(1-k2),-k2*y(abs(j)+niv)*sign(1,j)))/((abs(m)+k3a)**(0.5)*(
 & k3b+abs(j)))
   enddo
  enddo

  Mt= 2*niv+1
  alpha = cmplx(0.25d0,0.0d0)
  beta = cmplx(0.0d0,0.0d0)

  call ZGEMM('T','N',Mt,Mt,niv,alpha, p(1:niv,-niv:niv),niv,
 &p(-1:-niv:-1,-niv:niv),niv,beta, q ,Mt)

  do m= -niv, niv
  do j= -niv, niv
  do n= -niv, niv
  kk = m-j
  k1 = m
  k2 = j
  k3a = m
  k3b = j
  k5 = m-j
  k6 = j
  l = m-j
   if (abs(kk). gt. niv) then
    kk = 0
   else
    kk = 1
   end if
   indsum = m-j-n
   if (indsum .eq. 0) then
   indsum = 1
   else
   indsum = 0
   end if
   indsum2 = m+j-n
   if (indsum2 .eq. 0) then
   indsum2 = 1
   else
   indsum2 = 0
   end if
   indsum3 = j+n
   if (indsum3 .eq. 0) then
   indsum3 = 1
   else
   indsum3 = 0
   end if
   i4 = m-n
   if (i4 .eq. 0) then
   i4 = 1
   else
   i4 = 0
   end if
   if (k3a .eq. 0) then
   k3a=1
   else
   k3a=0
   end if
   if (k3b .eq. 0) then
   k3b=1
   else
   k3b=0
   end if
   if (k1 .eq. 0) then
   k1 = 0
   else
   k1 = 1
   end if
   if (k2 .eq. 0) then
   k2 = 0
   else
   k2 = 1
   end if
      if (k5 .eq. 0) then
      k5=2
      else
      k5=1
      end if
      if (k6 .eq. 0) then
      k6=2
      else
      k6=1
      end if
      if (l.eq.0) then
      l = 0
      else
      l = 1
      end if
   qmat(m,j,n) = (0.5*k5*k6*kk*abs(l*sign(1,m-j)-k2*sign(1,j))*
 &    cmplx(indsum,0)-0.5*indsum3*cmplx(y(abs(m))+1-k1,sign(1,
 &    m)*y(abs(m)+niv))-0.5*i4*cmplx(y(abs(j))+1-k2, -sign(1,
 &    j)*y(abs(j)+niv)))/((abs(m)+k3a)**(0.5)*(
 &    k3b+abs(j)))
  enddo
  enddo
  enddo

  c$omp parallel private(n) shared(sqmat3)
  c$omp do

  do n=-niv  ,niv
  call ZGEMM('T','N',Mt,Mt,niv,alpha, qmat(1:niv,-niv:niv,n),niv,
 &p(-1:-niv:-1,-niv:niv),niv,beta, sqmat0(:,:,n),Mt)
  call ZGEMM('T','N',Mt,Mt,niv,alpha,p(1:niv,-niv:niv)
 & ,niv,qmat(-1:-niv:-1,-niv:niv,n),niv,beta, sqmat2(:,:,n),Mt)
   sqmat3(:,:,n) = sqmat0(:,:,n)+sqmat2(:,:,n)
  enddo

  c$omp end do
  c$omp end parallel

  seconds = omp_get_wtime ( ) - seconds;
  print*, seconds

  return
  end

The seg fault is due to the last loop, involving the loop over matrix multiplications.
Now, I compile this on my mac using:
  $gfortran -fopenmp -O3 -Wl,-stack_size,0x320000000 test.f -lblas

and I find that the program executes and gives me the expected result. Note, if I set the stacksize to, for instance,
  -stack_size,0x80000000

I get a seg fault.
On my linux machine (Ubunut 12.04 _x86_64) I have set
  ulimit -s unlimited

and compile with
  $gfortran -fopenmp -O3 test2.f /home/user/OpenBLAS/libopenblas.a

and I get a segmentation fault. Checking ulimit -a, I see the stacksize is set to unlimited. Also, I have played around with setting the stacksizes of the slave threads using, for instance,
 $export OMP_STACKSIZE=16M

but this does not seem to help. It seems to me that, based on a similar issue on my mac, I must increase the stacksize to something over 8M, but can't seem to force the linux machine to do this.
So, my question is, what is the easiest way to overcome an issue like this? I am certainly a beginner, so any recommendations are appreciated.
Nick

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the graphical user interface used to access PostgreSQL? Is PostgreSQL accessible via phpMyAdmin (like MySQL) or any other similar graphical user interface that could manage it?
Note: the the database is being developed locally using MAMP.

A: Sure, default GUI for pgSQL is http://www.pgadmin.org/


text:
Q: Swift 3 (macOS) : keyDown(with event: NSEvent) doesn't get called I am trying to write a simple program in Swift 3 where I need to perform an action every time the user presses an arrow key. After a bit of research, I found that the method I needed to use was keyDown(with event: NSEvent) ; the problem is that it simply doesn't get called whenever I press any key.
Here's my code
import Cocoa

let LEFT: UInt16  = 123
let RIGHT: UInt16  = 124
let DOWN: UInt16  = 125
let UP: UInt16  = 126

class GameViewController: NSViewController {

...

  override func keyDown(with event: NSEvent) {
          print("abc")
          switch event.keyCode {
          case LEFT:
              print("left")
              break
          case RIGHT:
              print("right")
              break
          case DOWN:
              print("down")
              break
          case UP:
              print("up")
              break
          default:
              print("other")
              super.keyDown(with: event)
              break
          }
          print("Key with number: \(event.keyCode) was pressed")
      }
}

I tried pressing all the arrow keys, and other key to test if my arrow keys had a problem, but nothing happened - except me getting the error sound from macOS.
I don't know where the problem could be from - I'm rather new to Swift, so it may be something quite obvious that I am not seeing. Do you guys have any idea of what I am doing wrong ?
Many thanks in advance

A: I notice that you've implemented the keyDown method in the code of your view controller.  That's actually the incorrect place—that method should go inside the code of the view, not the view controller.   If you aren't currently using a custom view (with code you can modify), then you should create a new subclass.


text:
Q: where are the numbers ' baseline? i study the app like this , .
    /**
     * draw the hour text (12、3、6、9)
     * draw the arc
     */
    private void drawTimeText() {
        //draw the hour text
        String timeText = "12";
        mTextPaint.getTextBounds(timeText, 0, timeText.length(), mTextRect);
        int textLargeWidth = mTextRect.width();//两位数字的宽
        mCanvas.drawText("12", getWidth() / 2 - textLargeWidth / 2, mPaddingTop + mTextRect.height(), mTextPaint);
        timeText = "3";

        mTextPaint.getTextBounds(timeText, 0, timeText.length(), mTextRect);
        int textSmallWidth = mTextRect.width();//一位数字的宽
        mCanvas.drawText("3", getWidth() - mPaddingRight - mTextRect.height() / 2 - textSmallWidth / 2,
                getHeight() / 2 + mTextRect.height() / 2, mTextPaint);

        mCanvas.drawText("6", getWidth() / 2 - textSmallWidth / 2, getHeight() - mPaddingBottom, mTextPaint);
        mCanvas.drawText("9", mPaddingLeft + mTextRect.height() / 2 - textSmallWidth / 2,
                getHeight() / 2 + mTextRect.height() / 2, mTextPaint);

      //draw the arc
        mCircleRectF.set(mPaddingLeft + mTextRect.height() / 2 + mCircleStrokeWidth / 2,
                mPaddingTop + mTextRect.height() / 2 + mCircleStrokeWidth / 2,
                getWidth() - mPaddingRight - mTextRect.height() / 2 + mCircleStrokeWidth / 2,
                getHeight() - mPaddingBottom - mTextRect.height() / 2 + mCircleStrokeWidth / 2);
        for (int i = 0; i < 4; i++) {
            mCanvas.drawArc(mCircleRectF, 5 + 90 * i, 80, false, mCirclePaint);
        }

i don't know  when draw the hour text "3",
mCanvas.drawText("3", getWidth() - mPaddingRight - mTextRect.height() / 2 - textSmallWidth / 2,
                    getHeight() / 2 + mTextRect.height() / 2, mTextPaint);

use canvas.drawText(),
void drawText (String text,
                int start,
                int end,
                float x,
                float y,
                Paint paint)

"y" means the baseline of number ,i don't know the rules of number's baseline ,like "3",where is the baseline of number ? i search google the "baseline",but it just about English alphabet baseline , nothing about the number baseline.

A: The baseline for numbers is the same as for letters as far as I'm aware.  Most font's number will all sit on the baseline, but some will extend below the baseline much like a 'g' or a 'j' does in most fonts (some 'old style' or 'script' fonts are a good example of this)......

The dotted lines here are the baselines.
Don't forget, when you send the y coordinate into the drawText method, it's expecting the baseline and not the top of the characters.
Hope this helps.


text:
Q: How can UI thread waits untill Background thread finish up processing? I have this code  in Main Thread:
// in MyAsyncTask doinBackground and onPostExecute Fill up my secondArray with items
public class MainActivity extends Activity {

    ArrayList<String> secondArray = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView lv= (ListView) findViewById(R.id.listView);
        final ListView lv2= (ListView) findViewById(R.id.listView2);
          AsyncTas o = new AsyncTas();

        Toast.makeText(MainActivity.this, secondArray.get(0), Toast.LENGTH_LONG).show();

    }

    private  class AsyncTas extends AsyncTask  {
ArrayList<String> firstArray = new ArrayList<String>();
        @Override
        protected ArrayList<String> doInBackground(Object[] params) {
            firstArray.add("item1");
            firstArray.add("item2");
            firstArray.add("item3");
            try {
                Thread.sleep(1200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return firstArray;

        }
        @Override
        protected void onPostExecute(ArrayList<String> o) {
            secondArray.clear();
            secondArray.addAll(o);

        }
    }
}

But I have an Error caused by java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
My Question Is How to hang up or let Main thread waits untill Background ends its all processing  and thank you ??
I found an answer in Waiting till the async task finish its work  but it not work with me ..

A: 2 points - you are not actually executing your async task - you create it with
AsyncTas o = new AsyncTas();

but you need to then call
o.execute();

The next problem is that the Toast immediately tries to access the data which will be created by the Task. You need to move
Toast.makeText(MainActivity.this, secondArray.get(0), Toast.LENGTH_LONG).show();

...to the onPostExecute() method of the Task:
@Override
        protected void onPostExecute(ArrayList<String> o) {
            secondArray.clear();
            secondArray.addAll(o);
            Toast.makeText(MainActivity.this, secondArray.get(0), Toast.LENGTH_LONG).show();
        }

The means the Toast will only execute once the data is ready and execute in the UI thread.

A: Please execute aysnctask first then in its onPostExecute add all response in array then find this array.get(0). Your array is still empty but you are trying to get value at zeroth position.
new AsyncTas().execute();

then in onPostExecute() -
secondArray.clear();
secondArray.addAll(o);
Toast.makeText(MainActivity.this, secondArray.get(0), Toast.LENGTH_LONG).show();

Hope it will help.

A: import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends Activity {

    private ArrayList<String> secondArray;
    private ListView lv, lv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.listView);
        lv2 = (ListView) findViewById(R.id.listView2);

        new Task().execute();
        Toast.makeText(MainActivity.this, secondArray.get(0), Toast.LENGTH_LONG).show();

    }

    class Task extends AsyncTask<Void, Void, ArrayList<String>> {

        @Override
        protected ArrayList<String> doInBackground(Void... params) {
            ArrayList<String> firstArray = new ArrayList<String>();
            firstArray.add("item1");
            firstArray.add("item2");
            firstArray.add("item3");
            return firstArray;
        }

        @Override
        protected void onPostExecute(ArrayList<String> strings) {
            super.onPostExecute(strings);
            secondArray = strings;
        }
    }
}


text:
Q: Why tf.placeholder returns serialized example(s)? I'm reading mnist_saved_model.py
At line 62~64, tf.placeholder returns serialized example. And tf.parse_example function uses it like this,
serialized_tf_example = tf.placeholder(tf.string, name='tf_example')
feature_configs = {'x': tf.FixedLenFeature(shape=[784], dtype=tf.float32),}
tf_example = tf.parse_example(serialized_tf_example, feature_configs)

I knew placeholder returns a Tensor. Then, what exactly 'serialized tf.Example' means?

A: tf.placeholders can be used as entry points to you model for different kinds of data. For example, you could use x = tf.placeholder(shape=[784], dtype=tf.float32), which is suitable for feeding NumPy arrays with shape [784] and type float.
In your example, the placeholder should be fed with a string type. This is useful if you obtain your data directly from a text file or from a TFRecord / protobuf (which is a format for serializing your data). (To obtain the string from a protobuf, you can use tf.python_io.tf_record_iterator. You can also use the tf.data.Dataset API).
When you obtain the string from a TFRecord file, it is a serialized representation of your example. You now want to parse it into a tf.Tensor. This is done using tf.parse_example. The feature_configs dictionary specifies how to parse the data from the string.
(Note: tf.parse_example does not actually parse anything - it only adds an operation to the computational graph that can perform parsing. The parsing itself will occur when you run the graph, using sess.run(...))
The tensor, after parsing, is tf_example['x'].

EDIT:
To elaborate some more, as a response to your comment: In your example, serialized_tf_example is a tf.Tensor (as can be verified by running type(serialized_tf_example)). Its data type are strings (as can be verified by running serialized_tf_example.dtype). As with all tensors, this means that you can feed it any multidimensional array of its data type (which is strings). (If in the tf.placeholder() call you would have given a value to the shape argument, that would force you to use a specific shape for the multidimensional array). So, for example, these are valid calls:
sess = tf.Session()
sess.run(serialized_tf_example, feed_dict={serialized_tf_example:'abc'})
sess.run(serialized_tf_example, feed_dict={serialized_tf_example:[['some','strings'],['in an','array']]})

This tensor instance is named serialized_example, since its purpose is to be fed with a serialized encoding of the example that is going to be processed. This tensor is then converted from this encoding to a numerical multidimensional array, using tf.parse_example()


text:
Q: How can I force specific sites' pages into Reader View in Firefox? In Firefox (Windows, latest version 50+), is there a way to configure it so that specific sites' pages are automatically opened in Reader View?
Firefox's Reader View help page didn't yield any results.
Please note: I am asking for an automated switch to Reader View (not manual like this question); and the question assumes that the given site fully supports Reader View, so every page already has the view icon available).

A: I think I have a reasonable answer for you, but it's a bit buggy.
Via the Readability based Reader View add-on I can get an entire site to switch to Reader mode.
Firstly, although this isn't the official FireFox Reader View it is using the underlying Readability library:

This extension enhances the readability of web pages by removing clutter. It uses Mozilla's Readability library to provide a similar experience to the one you get when using Firefox.
-- FAQ

Once you've installed it you can actually get an entire site to switch to Reader View via the options.

There is an 'Automatic Switch' section where you can specify

a comma-separated list of hostnames or regular expressions to automatically switch to the reader view

For example I chose mathshistory.st-andrews.ac.uk (note a regular URL https://mathshistory.st-andrews.ac.uk doesn't work).
On top of that I ticked the 'Link Opening' checkbox that opens the links in the Reader View also in the Reader View. This effectively means I can stay in Reader View for the entire site.
It has a bug/feature where if you use Alt+Backspace it switches back to normal view.
Since you want just a particular page you can use something like:
mathshistory.st-andrews.ac.uk/Biographies/Abu_Kamil/
in the options.


text:
Q: Rich Text Column content in Display template for Search Results webpart I am trying to display content from a rich text column (ArticleContent) in my search results webpart using a custom display template.

                    _#=ctx.CurrentItem.Title=#_

                     _#=ctx.CurrentItem.ArticleContent=#_

The Title and any other single line of text or number column is displaying fine, but when I am use a rich text column, the result is plain text. So in order to maintain formatting I changed the site column to Publishing HTML (Page Content) but now the content is always blank. Any ideas?
Update: Search crawls are running fine. I have also run a full crawl to be sure.

A: I found the solution finally, I was mapping to the column field itself (ArticleContent) which was not providing any results. What I did not notice was that Sharepoint Search created a managed property for the Publishing HTML field (ArticleContentOWSHTML) which was now available.
I added a reference to the managed property in the managed property mapping
<mso:ManagedPropertyMapping msdt:dt="string">'Title':'Title' ... ,'ArticleContentOWSHTML':'ArticleContentOWSHTML'></mso:ManagedPropertyMapping>

and referenced the same in the display template body

    _#=ctx.CurrentItem.ArticleContentOWSHTML=#_

Now Rich text content is flowing into the search results without issues!


text:
Q: Is there any way to do a CentOS minimal install without LVM / ext4? I'm trying to benchmark the disk throughput of a base CentOS install on my lab XenServer setup, and am installing from the CentOS 6.4 minimal CD.  However, the install ISO boots into a text-mode anaconda setup, which only offers me the option to next through some rudimentary setup steps.
From memory, I'm sure the full CD used to allow me to partition, choose mount points and filesystems, but is a massive ISO, with a lot of packages I will probably never use.  This minimal one just offers "use the whole disk", "replace an existing linux" and "use free space" and then merrily goes off and creates an LVM volume group, root and data volumes, and formats both as ext4.
Benefits of LVM appreciated and not withstanding, I just want plain old MSDOS-labelled primary ext3 partitions for /boot and / (and possibly one more for /home).
Do I have to use the full CD for something so simple?

A: From the CentOS 6.0 Release Notes:

4. Known Issues
The text installer has limited capabilities compared to the GUI installer. Most notably there is no support for configuring partition layout, storage methods or package selection. Please refer to the official documentation for details. Here you can find some useful information on creating and using kickstart files which can be used to perform advanced configuring without the need for the GUI installer.

However, you can use the GUI installer to do custom layouts.
References

*

*[CentOS] CentOS 6 can't custom partition layout in text mode install


text:
Q: Compute $\int _Lye^{xy}dx +xe^{xy}dy$ from $(0,0)$ to $(2,1)$, $L : x = 2ye^y$ Compute $$\int _Lye^{xy}dx +xe^{xy}dy$$ from $(0,0)$ to $(2,1)$, $L : x = 2ye^y$
What I've tried:
If I input $0,0$ then I get $(0,0)$, if I input $(2,1)$ I get $(2e,1)$.
I also know that $P'_y = Q'_x$.
But I couldn't manage to solve this anyways. I tried to break it to two integrals because it'd be easier to go from $(0,0)$ to $(2e,0)$ and from $(2e,0)$ to $(2e,1)$ but I still didn't get to the solution which is $e^2-1$. Any ideas?

A: Since $$ye^{xy}dx +xe^{xy}dy=d(e^{xy}),$$
we have
$$\int _L ye^{xy}dx +xe^{xy}dy=\int _L d(e^{xy})=e^{xy}|_{(0,0)}^{(2,1)}=e^2-1.$$

A: Recall that if we let $c(t) = (x(t), y(t))$ and  $F = \langle F_1,F_2 \rangle$ then we can rewrite the line integral as;
$$\\$$
$$\int_c F \cdot ds = \int_{t=a}^{t=b} \langle F_1(c(t)), F_2(c(t)) \rangle \cdot \langle x'(t), y'(t) \rangle \ dt = \int_c F_1 \ dx + F_2 \ dy$$
$$\\$$
You can parametrize $L$ by letting $y = t$ then $x = 2te^t$ and so you have $L(t) = (2te^t,t)$ where $0 \leq t \leq 1$. Now just proceed by the above.


text:
Q: How to obtain all the data inside many dictionaries inside a big dictionary I just recently got into API request and after requesting some information i get a lot of data inside of a lot of dictionaries, it basically goes like this and i want to orgazine and print only the download URLs, thank you for the help.
Here is the example of json:
{
    'errorCode': None,
    'error': '',
    'data': {
        'numberReturned': 10,
        'totalHits': 388958,
        'firstRecord': 1,
        'lastRecord': 10,
        'nextRecord': 11,
        'results': [{
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-130.96631, 52.48409],
                        [-128.40618, 52.04284],
                        [-127.5665, 53.69859],
                        [-130.22375, 54.15318],
                        [-130.96631, 52.48409]
                    ]
                ]
            },
            'sceneBounds': '-130.96631,52.04284,-127.5665,54.15318',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/052/023/LT08_L1GT_052023_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80520232013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80520232013067LGN02/INVSVC/',
            'entityId': 'LT80520232013067LGN02',
            'displayId': 'LT08_L1GT_052023_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80520232013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80520232013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_052023_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 52, Row: 23'
        }, {
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-131.56161, 51.07001],
                        [-129.07552, 50.63805],
                        [-128.28062, 52.29816],
                        [-130.85695, 52.74239],
                        [-131.56161, 51.07001]
                    ]
                ]
            },
            'sceneBounds': '-131.56161,50.63805,-128.28062,52.74239',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/052/024/LT08_L1GT_052024_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80520242013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80520242013067LGN02/INVSVC/',
            'entityId': 'LT80520242013067LGN02',
            'displayId': 'LT08_L1GT_052024_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80520242013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80520242013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_052024_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 52, Row: 24'
        }, {
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-132.12903, 49.65182],
                        [-129.71182, 49.22835],
                        [-128.95719, 50.89234],
                        [-131.45832, 51.32713],
                        [-132.12903, 49.65182]
                    ]
                ]
            },
            'sceneBounds': '-132.12903,49.22835,-128.95719,51.32713',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/052/025/LT08_L1GT_052025_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80520252013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80520252013067LGN02/INVSVC/',
            'entityId': 'LT80520252013067LGN02',
            'displayId': 'LT08_L1GT_052025_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80520252013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80520252013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_052025_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 52, Row: 25'
        }, {
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-164.20358, 23.86964],
                        [-162.48625, 23.52277],
                        [-162.05927, 25.23064],
                        [-163.80043, 25.58141],
                        [-164.20358, 23.86964]
                    ]
                ]
            },
            'sceneBounds': '-164.20358,23.52277,-162.05927,25.58141',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/068/043/LT08_L1GT_068043_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80680432013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80680432013067LGN02/INVSVC/',
            'entityId': 'LT80680432013067LGN02',
            'displayId': 'LT08_L1GT_068043_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80680432013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80680432013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_068043_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 68, Row: 43'
        }, {
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-164.53819, 22.4285],
                        [-162.83937, 22.08332],
                        [-162.4197, 23.79243],
                        [-164.14054, 24.14135],
                        [-164.53819, 22.4285]
                    ]
                ]
            },
            'sceneBounds': '-164.53819,22.08332,-162.4197,24.14135',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/068/044/LT08_L1GT_068044_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80680442013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80680442013067LGN02/INVSVC/',
            'entityId': 'LT80680442013067LGN02',
            'displayId': 'LT08_L1GT_068044_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80680442013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80680442013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_068044_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 68, Row: 44'
        }, {
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-164.86886, 20.98582],
                        [-163.18712, 20.6422],
                        [-162.77413, 22.35249],
                        [-164.47616, 22.69974],
                        [-164.86886, 20.98582]
                    ]
                ]
            },
            'sceneBounds': '-164.86886,20.6422,-162.77413,22.69974',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/068/045/LT08_L1GT_068045_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80680452013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80680452013067LGN02/INVSVC/',
            'entityId': 'LT80680452013067LGN02',
            'displayId': 'LT08_L1GT_068045_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80680452013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80680452013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_068045_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 68, Row: 45'
        }, {
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [79.72568, 15.2114],
                        [81.3526, 14.87269],
                        [81.74391, 16.58657],
                        [80.103, 16.92848],
                        [79.72568, 15.2114]
                    ]
                ]
            },
            'sceneBounds': '79.72568,14.87269,81.74391,16.92848',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/142/049/LT08_L1GT_142049_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT81420492013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT81420492013067LGN02/INVSVC/',
            'entityId': 'LT81420492013067LGN02',
            'displayId': 'LT08_L1GT_142049_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT81420492013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT81420492013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_142049_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 142, Row: 49'
        }, {
            'acquisitionDate': '2013-03-08',
            'startTime': '2013-03-08',
            'endTime': '2013-03-08',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [79.41052, 13.76653],
                        [81.02677, 13.42875],
                        [81.41387, 15.1434],
                        [79.78508, 15.4843],
                        [79.41052, 13.76653]
                    ]
                ]
            },
            'sceneBounds': '79.41052,13.42875,81.41387,15.4843',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/142/050/LT08_L1GT_142050_20130308_20170505_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT81420502013067LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT81420502013067LGN02/INVSVC/',
            'entityId': 'LT81420502013067LGN02',
            'displayId': 'LT08_L1GT_142050_20130308_20170505_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT81420502013067LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT81420502013067LGN02/save_xml',
            'modifiedDate': '2017-05-05',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_142050_20130308_20170505_01_T2, Acquisition Date: 08-MAR-13, Path: 142, Row: 50'
        }, {
            'acquisitionDate': '2013-03-09',
            'startTime': '2013-03-09',
            'endTime': '2013-03-09',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-120.15339, 38.24051],
                        [-118.15904, 37.86641],
                        [-117.61337, 39.55749],
                        [-119.65581, 39.938],
                        [-120.15339, 38.24051]
                    ]
                ]
            },
            'sceneBounds': '-120.15339,37.86641,-117.61337,39.938',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/042/033/LT08_L1GT_042033_20130309_20170310_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80420332013068LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80420332013068LGN02/INVSVC/',
            'entityId': 'LT80420332013068LGN02',
            'displayId': 'LT08_L1GT_042033_20130309_20170310_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80420332013068LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80420332013068LGN02/save_xml',
            'modifiedDate': '2017-03-10',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_042033_20130309_20170310_01_T2, Acquisition Date: 09-MAR-13, Path: 42, Row: 33'
        }, {
            'acquisitionDate': '2013-03-09',
            'startTime': '2013-03-09',
            'endTime': '2013-03-09',
            'spatialFootprint': {
                'type': 'Polygon',
                'coordinates': [
                    [
                        [-120.56102, 36.80643],
                        [-118.60521, 36.4365],
                        [-118.07638, 38.1302],
                        [-120.07712, 38.50615],
                        [-120.56102, 36.80643]
                    ]
                ]
            },
            'sceneBounds': '-120.56102,36.4365,-118.07638,38.50615',
            'browseUrl': 'https://ims.cr.usgs.gov/browse/landsat_8_c1/2013/042/034/LT08_L1GT_042034_20130309_20170310_01_T2.jpg',
            'dataAccessUrl': 'https://earthexplorer.usgs.gov/order/process?dataset_name=LANDSAT_8_C1&ordered=LT80420342013068LGN02&node=INVSVC',
            'downloadUrl': 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80420342013068LGN02/INVSVC/',
            'entityId': 'LT80420342013068LGN02',
            'displayId': 'LT08_L1GT_042034_20130309_20170310_01_T2',
            'cloudCover': None,
            'metadataUrl': 'https://earthexplorer.usgs.gov/metadata/xml/12864/LT80420342013068LGN02/',
            'fgdcMetadataUrl': 'https://earthexplorer.usgs.gov/fgdc/12864/LT80420342013068LGN02/save_xml',
            'modifiedDate': '2017-03-10',
            'orderUrl': None,
            'bulkOrdered': False,
            'ordered': False,
            'summary': 'Entity ID: LT08_L1GT_042034_20130309_20170310_01_T2, Acquisition Date: 09-MAR-13, Path: 42, Row: 34'
        }]
    },
    'api_version': '1.4.0',
    'access_level': 'user',
    'catalog_id': 'EE',
    'executionTime': 208.667964220047
}

How to obtain all the data inside many dictionaries inside a big dictionary?

A: Dictionaries are made to be nested in Python, just access the dictionary keys one level at a time:
data = { .. your big data file ...}
download_urls = [result['downloadUrl'] for result in data['data']['results']]
print(download_urls) # ['https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80520232013067LGN02/INVSVC/', 'https://earthexplorer.usgs.gov/download/external/options/LANDSAT_8_C1/LT80520242013067LGN02/INVSVC

A: After the first line below, you have one dictionary with all the data. I added code below it to print out all the URL's:
>>> exec(f"d = {open('/Users/todd/projects/landsat/landsat.json', 'r').read()}")
>>>
>>> def print_urls(o, k=None):
...     ot = type(o)
...     if ot is list:
...         for li in o:
...             print_urls(li)
...     elif ot is dict:
...         for k, v in o.items():
...             print_urls(v, k)
...     elif ot is str and o.startswith("http"):
...         if k and k.startswith("download"):
...             print(f"{k}: {o}")
...         else:
...             pass
...             #print(o)
...             # If you want to print these too, uncoment above line.
...
>>> print_urls(d)

If you wanted to flatten this dictionary, I don't know if that's possible since you have many keys with the same name nested in it.


text:
Q: Get user from DB and put attribiutes in label I have simple Vaadin GUI which I would like connect with my Rest API on localhost:8080:
@Route("hello")
public class EmployeeGui extends VerticalLayout {

    private final WebClient webClient = WebClient.create("http://localhost:8080");

    public EmployeeGui() {
        TextField textEmployee = new TextField("Give id of user");
        Button buttonOK = new Button("OK");
        Label label = new Label();

        buttonOK.addClickListener(buttonClickEvent -> {
            this.webClient.get()
                    .uri(uriBuilder -> uriBuilder
                            .path("/employee/{id}")
                            .build(textEmployee.getValue()))
                            .retrieve()
                            .bodyToMono(EmployeeTo.class)
                            .subscribe(emp -> {
                                   label.setText(emp.getName());
                                });
                            });

        add(textEmployee,buttonOK, label);
    }
}

On localhost:8080 works my backend application which give me REST API to retrive some data from DB.
In text field we can put id of user and then click OK-button. After that in label we set name of user. Unfortunately I got exception (in line label.setText(emp.getName());):

java.lang.IllegalStateException: Cannot access state in VaadinSession or UI without locking the session.

I understood it, but how can I omit this problem? How can I put user Id and then return User attributes to label after OK button was clicked?

A: When you react to the request from your API, the "request" from Vaadin is
already done.  If you want to make that work you would have to enable @Push
(so Vaadin can send changes from the server when they happen) and make sure you
access the UI in a safe way (see "Asynchronous Updates" in the
docs for
details).
Or you actually don't need that to be async and
use the web client in a blocking way (so the client blocks and the label change
happens inside the "request" triggered by the button.

A: The direct answer to the question is using @Push (Doc 1, Doc 2) to update the ui when the main request has already been responded to (because your webClient.get() is asynchronous). The fix to your problem looks like this:
@Push
@Route("hello")
public class EmployeeGui extends VerticalLayout {

    private UI ui;
    private final WebClient webClient = WebClient.create("http://localhost:8080");

    public EmployeeGui() {
        TextField textEmployee = new TextField("Give id of user");
        Button buttonOK = new Button("OK");
        Label label = new Label();

        // keep instance of UI in a field,
        // and update it whenever the EmployeeGui is (re-)attached to the page
        // (important when using @PreserveOnRefresh or RouterLayout)
        addAttachListener(event -> {
            this.ui = event.getUI();
        });

        buttonOK.addClickListener(buttonClickEvent -> {
            this.webClient.get()
                    .uri(uriBuilder -> uriBuilder
                            .path("/employee/{id}")
                            .build(textEmployee.getValue()))
                            .retrieve()
                            .bodyToMono(EmployeeTo.class)
                            .subscribe(emp -> {
                                   // use ui.access to obtain lock on UI, perform updates within
                                   getUI().access(() -> label.setText(emp.getName()));
                                });
                            });

        add(textEmployee,buttonOK, label);
    }

    private UI getUI(){
        return this.ui;
    }
}

But depending on what you want to do with your application, I can recommend using Spring Security to make the user Log in, then you have easy and direct access to the current username.


text:
Q: what would be time complexity of this recursive function I am trying to find time complexity of this chunk, is it O(n!) or O(2^n), how??
void fun(int n)
{
    int i;
    count++;
    if(n>0)
    {
        for(i=1;i<n;i++)
        fun(n-i);
    }
}

I tried it for diff values of n and count giving value acc. to 2^n
??
thanks

A: Every call of T(n), invokes T(n-1), T(n-2), ..., T(1).
This gives us the complexity function of:
T(1) = 1
T(n) = T(n-1) + T(n-2) + .... + T(1)

If we will use induction, and hypothesis T(k) <= c*2^k for any k < n and for some constant c (and after properly checking T(1) = 1 <= 2^1, we get:
T(n) = T(n-1) + ... + T(1) + 1 =
     = c*2^(n-1) + c*2^(n-2) + ... + c*2^1 + 2^0  <=
    <= c*(2^n - 1) <= c*2^n

The last equality is from sum of geometric series.
Thus, we can conclude T(n) is in Theta(2^n)


text:
Q: Protractor afterEach extract browser.manage().logs() to a helper function My overall goal is to extract the browser.manage().logs() to a helper function.  I'm stepping towards this goal by including the browser.manage().logs() functionality inside the afterEach call inside the test.
I know that my test is throwing a console error.
The inline version of browser.manage().logs() will print the error.  Neither the afterEach nor the checkConsole will print the logs.
What do I need to do to fix this?
Is the inline browser.manage().logs() retrieving the error and wiping the log?  I've tried every combination of having them all commented out and the only one that ever works is the inline version.
I also have protractor-screenshoter-plugin configured and the report it produces shows the console error under the Show browsers logs button.  Is this somehow grabbing the errors and preventing browser.manage().logs() from getting it?
conf.ts
import { browser, Config } from 'protractor';

export let config: Config = {
    plugins: [{
        package: 'protractor-screenshoter-plugin',
        screenshotPath: './protractor/screenshots',
        screenshotOnExpect: 'failure+success',
        screenshotOnSpec: 'none',
        withLogs: true,
        writeReportFreq: 'asap',
        imageToAscii: 'none',
        clearFoldersBeforeTest: true
    }],

    capabilities: {
        'browserName': 'chrome',
        chromeOptions: {
            args: [ '--disable-gpu', '--window-size=1440x900', '--headless'],
        },
        'moz:firefoxOptions': {
            args: [ '-headless' ],
        },
        'loggingPrefs' : {"driver": "ALL", "server": "ALL", "browser": "ALL"}
    },

    directConnect: true,
    framework: 'jasmine2',

    baseUrl: 'https://localhost/',
    rootElement: 'app',

    getPageTimeout: 10000,
    allScriptsTimeout: 11000,
    jasmineNodeOpts: {
        defaultTimeoutInterval: 52000,
        onComplete: null,
        showColors: true,
        includeStackTrace: true,
    },

    onPrepare: function() {
        // returning the promise makes protractor wait for the reporter config before executing tests
        return browser.getProcessedConfig().then(function(pconfig) {
            // console.log("pconfig", pconfig);
        });
    }
};

console_helper.ts
import { browser } from 'protractor';

export let checkConsole = () => {
    browser.manage().logs().get('browser').then((browserLog: any) => {
        // this also fails to print the error message
        console.log("browserLog", browserLog);
   });
}

project.ts
import { browser, element, by, ExpectedConditions } from 'protractor';
const EC = ExpectedConditions;

import { checkConsole } from "./helpers/console_helper";

afterEach(function() {
    browser.manage().logs().get('browser').then(function(browserLogs) {
        // this fails to print the error message
        console.log("browserLogs", browserLogs);
    });
});

it("should click on the button and redirect", () => {
    browser.get('/url-it-needs');
    browser.wait(EC.urlContains('/url-it-needs'), 5000);
    let button = element(by.cssContainingText('button', 'BUTTON TEXT'));
    browser.wait(EC.visibilityOf(button), 5000);
    browser.wait(EC.elementToBeClickable(button), 5000);
    button.click();
    browser.sleep(500);  // wait for the error to be returned from the backend
    /*
    // this will print the proper error message
   browser.manage().logs().get('browser').then(function(browserLogs) {
          console.log("browserlogs Inline", browserLogs);
     });  */

   // this times out
   browser.wait(browser.getCurrentUrl().then((url: string) => {
       console.log("URL after click", url);
       expect(url).toMatch("/properUrl");
   }, 5000);
  });

A: We use a similar mechanism to read the console when a test fails.
Our solution looks something like this:
export function printConsole () {
    return browser.manage().logs().get('browser').then(browserLog => {
        browserLog.forEach(log => console.error(log.message));
    })
    .catch(() => console.log('Could not get browser log.'));
};

It might make sense to modify it slightly to actually return the log as well:
export function getConsole () {
    return browser.manage().logs().get('browser')
    .catch(() => console.log('Could not get browser log.'));
};

export function printConsole () {
    return getConsole.then(browserLog => {
        browserLog.forEach(log => console.error(log.message));
    });
};

That way you could also use it for assertions, i.e. check length === 0 to assert that no console errors are present.

A: Each time after you read browser.manage().logs() in your test case. The logs would be empty. So, you get no logs in the afterEach.
You can try to remove browser.manage().logs() in your test case and only keep it in the afterEach.


text:
Q: dismissing Progress Dialog   I have a situation where I am loading a bunch of images. During this process, I am trying to show a progress Dialog until the images get loaded fully. I have overrided the onBackPressed() method, such that when the user presses the back button, the activity will be finished.
But if I press the back button when the progress dialog is being displayed, the back key event was not called. So I tried providing progressDialog.setCancelable(true). So this now allows me to dismiss the progress Dialog, but my back key event is not being called anyway and so my activity loads images in the background.
So how do I make both the progressDialog and activity to be stopped when the user presses the back key.

A: Use Dialog.setOnCancelListener to cancel your background task

A: Ok. I have found out a solution at last.
progressDialog.setCancelable(true);
    progressDialog.setOnCancelListener(new OnCancelListener() {

        public void onCancel(DialogInterface dialog) {

        Log.i("inside on cancel","Cancel Called");
        finish(); //If you want to finish the activity.
        }
    });

A: Load your images in a different thread. When the user indicates they want to cancel the load, set a flag that is checked in the loading thread's processing loop. You can also call the loading thread's interrupt() method to handle those cases where the thread is stuck in a wait() or sleep() or something.

A: Use onKeyDown() method, however you'd have to check whether the dialog is showing, whether the button being pressed is the 'back' button, and you should also make a call to super.onKeyDown() to make sure that the default method is also executed.
 public boolean onKeyDown(int keyCode, KeyEvent event)

{

if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing())
{
    // DO WHATEVER YOU WANT
}

// Call super code so we dont limit default interaction
super.onKeyDown(keyCode, event);

return true;
}

Can you paste the code for correct answer?


text:
Q: set configuration constants depending on environment in rails I would like to define a constant (like the admin-email-adress) depending on the environment. What is the easiest way to do this?
I'd like something like that, in development.rb (or test or production.rb):
ADMIN_EMAIL = "foo@bar.com"

And be able to access it by calling something like
ADMIN_EMAIL

Is there an easy way or do I have to do something like creating a module and initialize it and stuff (and in case you're wondering if I have any idea about this, unfortunately: I don't)

It works this way, but one has to
  restart the server, for the constants
  to take effect.

A: In config/environments/, there are some configuration files that get executed based on what environment you're currently in. Try defining a constant in one of those.


text:
Q: Change column value based on another column, but only for certain conditions in the first AND second column (R) I have a dataframe.
city <- as.character(c("London", "Unknown", "Birmingham", "Bristol", "Unknown", "Unknown", "Unknown", "Unknown"))
city_details <- as.character(c("London", "Camden", "Birmingham", "Outside London", "Camden Town", "Westminster", "London", "Birmingham"))
city_data <- data.frame(city, city_details)

Although several of the values in the city column are unknown, looking at the city_details reveals that most of these are actually in London.
So, I can replace some of these:
city_data$city[grepl("Camden|Westminster", city_data$city_details)] <- 'London'

However, this is more difficult with the one that says "London" in the city_details, because there is also one that says "Outside London", so I don't want to just pick up anything that has the "London" pattern in it.
For the purposes of this, I'm not looking for a way to only include exact matches (because that won't be quite right for my real data).
So what I want to do is only perform this replacement on city values that are unknown.
At the moment I have tried the following, but clearly the logic is off because what it is actually doing is just changing all the unknown values in the city column to London.
city_data <- within(city_data, city[city == "Unknown"] <- (city[grepl("London", city_details)] <- 'London'))

Can anyone help?

A: I assume that you only want to replace the city names when city is unknown and city_details mentions "London". In this case you can use the following:
city_data$city[(as.numeric(grepl("Unknown", city)) + as.numeric(grepl("London", city_details))) == 2] <- "London"
Does this answer your question?

A: I would suggest the following:
one_hot <- grepl("Camden|Westminster|London", city_data$city_details) &
  city_data$city == "Unknown"
city_data$city[one_hot] <- "London"

Example:
city <- as.character(c("London", "Unknown", "Birmingham", "Bristol", "Unknown", "Unknown", "Unknown", "Unknown"))
city_details <- as.character(c("London", "Camden", "Birmingham", "Outside London", "Camden Town", "Westminster", "London", "Tottenham"))
city_data <- data.frame(city, city_details)

> city_data
        city   city_details
1     London         London
2    Unknown         Camden
3 Birmingham     Birmingham
4    Bristol Outside London
5    Unknown    Camden Town
6    Unknown    Westminster
7    Unknown         London
8    Unknown      Tottenham

> one_hot <- grepl("Camden|Westminster|London", city_data$city_details) &
+   city_data$city == "Unknown"
> city_data$city[one_hot] <- "London"
> city_data
        city   city_details
1     London         London
2     London         Camden
3 Birmingham     Birmingham
4    Bristol Outside London
5     London    Camden Town
6     London    Westminster
7     London         London
8    Unknown      Tottenham

A: I also worked out the following way of doing it, which seems a bit neater and more intuitive to me. No need to convert to numeric.
city_data$city[grepl("Unknown", city_data$city) &
               grepl("London|Camden|Westminster", city_data$city_details)] <- "London"


text:
Q: Java / java stored procedure avoid to load certificate from file system each time I have done a java stored procedure on oracle database which uses p12 certificate to sign some data + SHA256withRSA. The certificate is located on database file system.
Each time I call the procedure the code will load a certificate from file system.
What I want is to know what other possibility exists to avoid loading certificate from disk each time the function is called? (maybe to store the file into array of byte?)
here is my example:
        KeyStore p12 = KeyStore.getInstance("pkcs12");
        p12.load(new FileInputStream("c:/cert/testfurs.p12"), "password".toCharArray());

regards

A: You can store it in a static field.
Static fields last for the duration of the database session, aka connection.
See this link for more detail: Using Java in Oracle Database - Automated Storage Management With Garbage Collection


text:
Q: npm is raising and error on mac, and not working in any way When i run npm or npm start and so on... It is raising the following error.
    npm ERR! code MODULE_NOT_FOUND
    npm ERR! Cannot find module 'ci-info'
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/narendra/.npm/_logs/2018-09-21T11_19_20_365Z- debug.log

I'am not able to understand what that 'ci-info' is and even not able to search for that module in npm, because of the same error, which is not letting me use the npm.
Can anyone help me with this.
note: npm --version is working.


text:
Q: Why cant this binary search find my value?
hi everyone, my binary search keeps returning 'not found', because it cant find the value im passing it. please let me know what im doing wrong, thanks!

const binary_search = (arr, value) => {
let high = arr.length -1;
let low = 0;
let mid = 0;

while (low <= high){
    mid = Math.floor = ((high + low) / 2)
    //middle value being searched
    if (arr[mid] == value){
        //return value
        return arr[mid];
    } else if (value > arr[mid]){
        // move the low up one
        low = mid + 1;
    }   else  {
        // move the high down one
        high = mid -1;
    }
}
return 'not found'
}

let array = [12, 45, 37, 37, 84, 61, 12, 266]

let sorted = array.sort (function(a,b){return a-b})
let wif = binary_search(sorted,37)
console.log(sorted)
console.log(wif)

A: const binary_search = (arr, value) => {
    let high = arr.length -1;
    let low = 0;
    let mid = 0;

    while (low <= high){
        mid = Math.floor = ((high + low) / 2)
        mid = Math.round(mid);

        //middle value being searched
        if (arr[mid] == value){
            //return value
            return arr[mid];
        } else if (value > arr[mid]){
            // move the low up one
            low = mid + 1;
        }   else  {
            // move the high down one
            high = mid -1;
        }
    }
    return 'not found'
    }

    let array = [12, 45, 37, 37, 84, 61, 12, 266]

    let sorted = array.sort (function(a,b){return a-b})
    let wif = binary_search(sorted,37)
    console.log(sorted)
    console.log(wif)

The Value in of mid = Math.floor = ((high + low) / 2) are in interger in every iteration due to which it cannot get the index. Like 7 / 2 = 3.5 and arr[3.5]. there will be no value.

A: Your code says:
mid = Math.floor = ((high + low) / 2)

I dont think thats what you meant there


text:
Q: Editing legend (text) labels in ggplot with aes(factor) or maybe position dodge I am trying to change the legend title and labels related to the colors. I tried using this answer as a guide, but it didn't seem to have an impact on the legend text. I think it is because I am using a factor, or because I am using a position dodge? The script and outcome are below:
ggplot(ggplot_survey, aes(factor(hurricanes), fill = factor(bldg_flooding))) +
  geom_bar(position = position_dodge2(width = 0.9, preserve = "single")) +
  facet_wrap(facets = vars(C0_time)) +
  scale_color_discrete(labels=c("No", "Yes", "No Response")) +
  labs(title = "Would frequent flooding (building) prompt you to install WCS?",
       color = "Response",
       x = "Reported Hurricane Exposure",
       y = "Count"
       )

Basically, I want the text above the legend to read "Response", the 0 to be "No", 1 to be "Yes", and NA to be "No Response". Any advice on where I am going wrong?

A: Per @silentdevildoll's response:
    ggplot(ggplot_survey, aes(factor(hurricanes), fill = factor(bldg_flooding))) +
  geom_bar(position = position_dodge2(width = 0.9, preserve = "single")) +
  facet_wrap(facets = vars(C0_time)) +
  scale_fill_discrete(labels=c("No", "Yes", "No Response")) +
  labs(title = "Would frequent flooding (building) prompt you to install WCS?",
       fill = "Response",
       x = "Reported Hurricane Exposure",
       y = "Count"
       )

Key was to replace color in both the scale_color_discrete (now scale_fill_discrete), and in the labs() bit. Thanks again!


text:
Q: Adding row with null field to another row I have a table in my SQL Server database that looks like:
Date  Hours  Name
11-01      3               a
11-01      4              b
11-01      6               null
12-01      2               a
12-01      3               c
12-01      1              null
I want to add the hours from the "null" column into the "a" column for each month.  So it would look like:
Date  Hours  Name
11-01      9                a
11-01      4                b
12-01      3                a
12-01      3                c
The only way I was able to get this to work was by modifying the table prior to the select to prevent the null from showing up.  But I'd like to be able to do this without modifying the database.
What would be the best way to go about this?
Thanks

A: This'll do it for you - grouping by name or 'a' (when name is null) conditionally, and taking the sum of hours from there.
SELECT Date, SUM(Hours) AS Hours, MAX(Name) AS Name
FROM TableName
GROUP BY (CASE WHEN Name IS NULL THEN 'a' ELSE Name END)


text:
Q: Error:CreateProcess error=216, This version of %1 Gradle sync failed etc etc I am unable to install Android Studio.
This error comes.

Error:CreateProcess error=216, This version of %1
Gradle sync failed.

I have Windows 10 ( 32bit) with 4Gb ram and i5
Is there any solution? What should I do?
I Will be very grateful please help me.


text:
Q: How to use a element function in template polymer? I want to use a function defined in the element. Like this:
<template>

</template>

Is there a similar approach?
<template>

</template>

A:
To add event listeners to local DOM children, use on-event annotations in your template. This often eliminates the need to give an element an id solely for the purpose of binding an event listener.

Source: https://www.polymer-project.org/1.0/docs/devguide/events.html#annotated-listeners
<dom-module id="test-ele">
  <template>
    Click Here
  </template>

</dom-module>

A: The simple answer is no, you can't.  will try to initiate the function {{{test}}}, instead of reading it as a template variable.
Further more, your first example is wrong.
<template>

</template>

will try to load this.parentElement.test(); as the function. Simply use
<template>

</template>

Polymer knows it should call a function in the parent element.


text:
Q: How to edit the table record due to login user The problem I encountered for edit multiple records of the table according to the login user id. When I edit the one record and update the record into the database, the id is 0, as well as whatever I click the edit button only can edit the first record. How can I edit and update the multiple of the table as each row?
$login_user=$_SESSION['id'];


text:
Q: Energy conservation of a falling Rod fixed at one end I have seen many questions that use energy conservation to find the angular speed of the rod. For example, if the rod is vertical and starts to fall, the decrease in potential energy will transfer to the kinetic energy of the rotation ONLY. What I do not understand is, since the center of the rod has translational speed, wouldn't that account for some kinetic energy that is converted from potential energy?

A: The kinetic energy of a rigid body can be written as the sum of two contributions
$K = \dfrac{1}{2} m |\mathbf{v}_G|^2 + \dfrac{1}{2} \mathbf{\omega} \cdot \mathbb{I}_G \cdot \mathbf{\omega}$.
Assuming a planar motion of a beam hinged at one of its end, the system has only one degree of freedom. Let's choose the angle of rotation w.r.t. the vertical direction. We can write:

*

*angular velocity: $\mathbf{\omega} = \dot{\theta} \mathbf{\hat{k}}$

*velocity of the center of mass: $\mathbf{v}_G = \dfrac{\ell}{2} \dot{\theta} \mathbf{\hat{\theta}}$

*component of the inertia tensor in $\mathbf{\hat{k}} \otimes \mathbf{\hat{k}}$: $I_{G,kk} = \dfrac{1}{12} m \ell^2$

*vertical component of the center of mass w.r.t. the hinge $z_G = \dfrac{\ell}{2} \cos \theta$.

Thus we can write the kinetic energy as
$K = \dfrac{1}{2} m\dfrac{\ell^2}{4}\dot{\theta}^2 + \dfrac{1}{2} m\dfrac{\ell^2}{12}\dot{\theta}^2 = \dfrac{1}{6} m \ell^2 \dot{\theta}^2$,
the potential energy
$V = m g z_G = m g \dfrac{\ell}{2} \cos \theta$
and the principle of conservation of energy as
$E = \dfrac{1}{6} m \ell^2 \dot{\theta}^2 + m g \dfrac{\ell}{2} \cos \theta = \text{const.}$,
and taking the time derivative you can get the equation of motion
$\left( \dfrac{1}{3} m \ell^2 \ddot{\theta} + m g \dfrac{\ell}{2} \sin \theta \right) \dot{\theta} = 0$


text:
Q: How to improve the LINQ query? This is what i got:
int? productID = (ClientProduct != null ? (int?)ClientProduct.ProductID : null);

result = (from po in ((Chase_Media_Pro_Entity_Model)this.NavigationItem.ObjectContext).raPurchaseOrder_List
                  where po.ClientID == Client.CustomerID
                        && ((object.Equals(po.ClientProductID, productID)) || (po.ClientProductID == (productID ?? po.ClientProductID)))
                        && (po.Is_Active == (isActive ?? po.Is_Active))
                        && (po.IsApproved == (isApproved ?? po.IsApproved))
                  orderby po.Is_Active descending, po.IsApproved ascending
                  select po);

Is there a way to improve this line:
&& ((object.Equals(po.ClientProductID, productID)) || (po.ClientProductID == (productID ?? po.ClientProductID)))

This was the only way i could get the right results.

A: && (!productID.HasValue || (productID == po.ClientProductID))

A: How about
&& ((productID.HasValue && po.ClientProductID.HasValue) ? po.ClientProductID.Value = productID.Value : true)


text:
Q: Angular 6 how to provide data as void array I've done search which gets array and then filters the names of it on input. Everything works just fine if I write static :
export class AddComponent {
  protected dataService: CompleterData;
  protected searchData = [
    {name: '84A4DA'},
    {name: '846ASD'},
    {name: '8444AS'},
]
constructor(private completerService: CompleterService, private router: Router, public back: BackService,
             ) {
this.dataService = completerService.local(this.searchData, 'name', 'name');
}

But when I try to make my searchData from db firebase :
getArray(): void {
    this.afDatabase.list('/imones')
      .valueChanges()
      .subscribe(res => {
        console.log(res)//should give you the array of percentage.
        this.array = res;
      })
}

this.searchData = this.back.getArray();
  constructor(private completerService: CompleterService, private router: Router, public back: BackService,
             ) {
    this.dataService = completerService.local(this.searchData, 'name', 'name');
}

I get error :

How to fix it ?

A: The problem is that, in the constructor, this.SearchData is NOT an array. The solucion is.
1.-Your service must be return an observable. NOT subscribe in service
2.-Move your code from constructor to ngInit
3.-Is in subscribe function where you has the value of searchData
It's difficult understand your code for me, but, if your service return Observables -not data- I supouse your component can be like
constructor(private completerService: CompleterService,
            private router: Router, public back: BackService){}
ngOnInit()
{
  this.back.getArray().subscribe(res=>{
      this.searchData=res;
      completerService.local(this.searchData, 'name', 'name').subscribe(res=>
      {
          this.dataService=res;
      });
  })
}

//Or , better, using switchMap
ngOnInit()
{
  this.back.getArray().pipe(switchMap(res=>{
      this.searchData=res;
      return completerService.local(this.searchData, 'name', 'name')
      }))
      .subscribe(res=>
      {
          this.dataService=res;
      });
}

A: getArray() method does not return any array, but when you subscribe to your afDatabase.list, you get an array of values i assume, and hence in the subscribe callback, you should assign the value to your array.
getArray(): void {
this.afDatabase.list('/imones')
  .valueChanges()
  .subscribe(res => {
    console.log(res)//should give you the array of percentage.
    this.searchData = res;
  })}

Or if you are getting values one by one, write
getArray(): void {
    this.afDatabase.list('/imones')
      .valueChanges()
      .subscribe(res => {
        console.log(res)//should give you the array of percentage.
        this.searchData.push(res); //searchData must be initialized as empty array
      })
}


text:
Q: Import classes into the global scope I am trying to import a class into the global scope, and I am able to do it, but then when I try to extend the class I get an error saying:

Type 'any' is not a constructor function type.

So this is what I am doing to get that error:
main.ts
const MyClass = require('./core/MyClass');

class MyTestClass extends MyClass {

}

I then tried using import MyClass from './core/MyClass', instead of a const, but that seems as if it is only within the scope of the current file, which doesn't help me either.
core/MyClass.ts
export default class MyClass {

}

I have tried using namespaces which works the way I want in typescript, but once compiled into javascript the namespace is undefined.
Is there a way I can import my class into the global scope and not get the error above when extending the class?

A: In your code you have :
require('./core/MyClass');

If you don't have import / export in your file then TypeScript assumes the file is global. However depending upon your usage of the file (e.g in NodeJS or if using a bundler like webpack) the file is still a module and not global.
Cool, with that out of the way you can put something on the global like:
export default class MyClass {
}
(global as any).MyClass = MyClass;

Be sure to include node.d.ts to get global.
More
And of course I would also like to warn against default as the const / require you wrote is also wrong. You need something like const {default} = require('module/foo');. More: https://basarat.gitbooks.io/typescript/content/docs/tips/defaultIsBad.html


text:
Q: How to get npm always fetch the last prerelease version? I am trying to use pre-release versions with npm. But it doesn't get the last prerelease version when I do npm install.
In my client app, I have this :
$ cat package.json| grep mylib
"mylib": ">1.2.4-dev.0",

Which at first fetched the version 1.2.4-dev.201810160008.0
Then, I set a new pre-release version.
npm version --no-git-tag-version prerelease --preid=dev-$(date +%Y%m%d%H%M)
v1.2.4-dev.201810160906.0

I publish to a nexus repository :
npm publish --registry http://X.X.X.X:8080/repository/npm-private-snapshot/

Then I can see this new version :
npm view mylib versions --json
[
  "1.0.0",
  "1.2.2",
  "1.2.3",
  "1.2.4-0",
  "1.2.4-201810101547.0",
  "1.2.4-201810111027.0",
  "1.2.4-201810111231.0",
  "1.2.4-201810111445.0",
  "1.2.4-201810151548.0",
  "1.2.4-201810151550.0",
  "1.2.4-dev.201810160006.0",
  "1.2.4-dev.201810160008.0",
  "1.2.4-dev.201810160011.0",
  "1.2.4-dev.201810160906.0",
  "1.2.5-201810111819.0"
]

Finally, I would like to have this new version used by my client app, so I run npm install but it does not update mylib, the version is still the old one :
cat package-lock.json| grep mylib
    "mylib": {
      "resolved": "http://X.X.X.X:8080/repository/npm-group/mylib/-/mylib-1.2.4-dev.201810160008.0.tgz"

I have to run rm -rf node_modules/mylib ./package-lock.json to get it working as I expect.
$ rm -rf node_modules/mylib ./package-lock.json
$ npm install
$ package-lock.json| grep mylib
    "mylib": {
      "resolved": "http://X.X.X.X:8080/repository/npm-group/mylib/-/mylib-1.2.4-dev.201810160906.0.tgz",

How can I get npm fetch the last pre-release version each time I run npm install ?


text:
Q: Conflict control ID I am having problem in publishing my custom project in Acumatica ERP. It prompts me the following message.

Conflict control ID:phG_tab_Items#0_grid_Levels#0 from page
  ~/pages/so/so303000.aspx Validation failed.

Here is what my code looks like in the Invoices page (ScreenID: SO303000)
<Page path="~/pages/so/so303000.aspx" ControlId="2" pageSource="711Ft7m6F+foDk0z4+/8B">
    <PXGridLevel DataMember="Transactions" ParentId="phG_tab_Items#0_grid_Levels#0" TypeFullName="PX.Web.UI.PXGridLevel">
        <Children Key="Columns">
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrContractID" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrPhoneNumber" />
                    <Prop Key="Width" Value="70" />
                </PXGridColumn>
            </AddItem>
            <AddItem>
                <PXGridColumn TypeFullName="PX.Web.UI.PXGridColumn">
                    <Prop Key="DataField" Value="UsrSIMCardID" />
                    <Prop Key="Width" Value="160" />
                </PXGridColumn>
            </AddItem>
        </Children>
    </PXGridLevel>
</Page>

I have shortened the pageSource value for readability.

Since, I have another custom project as well, and got answer that that could cause this, I have no idea what changes should I do to make this work.

A: When you publish more that one customization project, the system merges the content of all projects into a single customization project. If different projects include customization for the same ASPX page, the platform tries to merge the changes. For example, the platform can merge different properties of the same control in an ASPX page.
On the Customization Projects form, you can specify an optional number (level) for each customization project, assigning the highest number to the most important change. The level can be used to resolve conflicts that arise while you are publishing customization projects if multiple modifications for the same ASPX page are merged. As a result, the customization from the project with the highest level is added to the merged project.
For more information on this topic, please check Acumatica Customization Guide

A: I don't know if it's the best way to do it, but here is what I did.
I copied the changes from the my one custom project to another custom project in the same page screen. And it worked!
This worked for now. But please let me know if there is better way to do this.


text:
Q: Entity Framework foreign key error in two connect class I use Entity Framework 6.1 in ASP.NET MVC.
My model is :
public class Article
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string Name { get; set; }
    public double Price { get; set; }

    [InverseProperty("Article")]
    public virtual ICollection<FormulaItem> FormulaItem { get; set; }
}

public class FormulaItem
{
    [Key]
    [Column(Order = 0)]
    public int Id { get; set; }

    [ForeignKey("IdMaster")]
    public virtual Formula Formula { get; set; }
    public int IdMaster { get; set; }

    [ForeignKey("IdArticle")]
    public virtual Article Article { get; set; }
    public int IdArticle { get; set; }

    public string Comment { get; set; }
    public int Count { get; set; }
}

public class Formula
{
    [Key]
    [Column(Order = 0)]

    public int Id { get; set; }
    public FormulaMode Mode { get; set; }

    // Wen add this line I get error
    //[ForeignKey("IdArticle")]
    //public virtual Article Article { get; set; }
    //public int? IdArticle { get; set; }

    public string Comment { get; set; }
    public virtual IList<FormulaItem> Items { get; set; }

    public Formula()
    {
        Items = new List<FormulaItem>();
    }
}

This sample works fine, but when add the new poco:
    // When I add this line in class formula I get error
    [ForeignKey("IdArticle")]
    public virtual Article Article { get; set; }
    public int? IdArticle { get; set; }

to class Formula I get error:

Formula_Items_Source_Formula_Items_Target: : The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical

A: Consider using FluentAPI as it is more user-friendly:
    modelBuilder.Entity<FormulaItem>()
        .HasOptional(b => b.Article )
        .WithMany(a => a.FormulaItem);

And in your case you must be missing another InverseProperty attribute:
[InverseProperty("FormulaItem")]
public virtual Article Article { get; set; }

A: I add:
modelBuilder.Configurations.Add(new FormulaConfig());
public class FormulaConfig : EntityTypeConfiguration<Formula>
{
    public FormulaConfig()
    {               // one-to-many
        this.HasRequired(x => x.Article)
            .WithOptional(x=>x.Formula)
            .WillCascadeOnDelete();

    }
}

but get error :
Article_Formula_Target: : Multiplicity is not valid in Role 'Article_Formula_Target' in relationship 'Article_Formula'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.


text:
Q: Как корректно переписать код условия на Javascript Есть условия выигрышных комбинаций игры, но видимо начал неправильно и получилось много кода. Получится так, если я еще буду делать условия для оппонента, кода станет в два раза больше.
Подскажите как это правильно и профессионально делается на Javascript?
Вот ссылка на JsFiddle
Образец условий:
this.rezult = function(){
    this.arr2.forEach(function(arr, i, innerArr){
        arr.forEach(function(val, j){
            var wincomb = innerArr[i][j] === "X" && innerArr[i][j+1] === "X" && innerArr[i][j+2] === "X";
            var wincomb2 = innerArr[i][j] === "X" && innerArr[i+1][j] === "X" && innerArr[i+2][j] === "X";
            var wincomb3 = innerArr[i][j] === "X" && innerArr[i+1][j+1] === "X"&& innerArr[i+2][j+2] === "X";
            var wincomb4 = innerArr[i][j] === "X" && innerArr[i-1][j+1] === "X"&& innerArr[i-2][j+2] === "X";

            // console.log(wincomb == "X");
            // console.log(innerArr);

            if(wincomb || wincomb2){
                alert(' X wins!');
            }
        })
    })
}

A: По сути, твой вопрос - это "перепишите за меня программу", и, кроме того, проблемы твоего примера не в том "как это правильно и профессионально делается на Javascript", а в логическом подходе к самой структуре програмы (конкретный язык здесь уже вторичен). Кроме того, ты не удосужился ни описать достаточно подробно, что делает твоя программа, ни задокументировать код (мол, разбирайтесь как хотите, что это, как работает и что делает) - не надо так делать
По этому, полностью готовый и исправленный вариант я расписывать не стану, а ограничусь несколькими советами, из которых ты сам сможешь разобраться и создать то, что тебе конкретно нужно
Перепиши функцию this.rezult
а) Добавь возможность передавать в нее параметр, либо вынеси проверку в отдельную функцию, если хочешь использовать один фрагмент кода для обоих оппонентов. Что-то вроде такого:
this.proverka = function(param){
    var resultat = false;//По умолчанию - не правильно
    /*Код проверки [...], если условия выполняюся resultat = true;*/
    return resultat;
}
this.rezult = function(){
   var resultat = {X: this.proverka("X"), O:  this.proverka("O")}
  /*Получится что-то вроде {X: true, O: false} ( когда победил X)*/
}

б)Функия проверки.
Во-первых используй лучше не forEach, а for (или for in) и break/continue и проходи им сразу по основному массиву innerArr
если я правильно понял суть, у тебя возможно только 3 варианта:
по диагонали из угла в угол (считай, имея ширину(кол. ячеек) (i_max) и высоту (j_max) поля, из угда innerArr[0,0] по возрастающей до innerArr[(i_max-1),(j_max-1)] и из угла innerArr[(i_max-1),0] по убыванию i innerArr[0,(j_max-1)]) - проверяешь наличие param (твоего "Х" или "О") в этих углах, затем проходишь циклом по диагонале:
/*Пример цикла*/
resultat = true; for(var z=0; z<i_max; z++){if(innerArr[z,z]!=param){resultat = false; break;}}

либо (если по прежнему resultat == false) остается возможность: полное заполнение столбца по вертикали или строки по горизонтали: соответственно, проходишь сначала 1ю строку и ищешь в ней param, если находится, начинаешь проверять столбец. Если столбец полный - готово, если нет - продолжаешь, пока не дойдешь до конца строки. Если ничего в строке не нешлось - значит столбцов нет - переходишь к проверке строк: берешь таким же образом 1й столбец и проходишься по нему таким же образом. Если и тут ничего не нашлось - то значит пользователь продул
Для строк будет выглядить примерно так:
for(var i=0; i<i_max; i++){//Перебор 1й строки

   if(resultat == true){break;}//Если предыдущие манипуляции уже дали положительный результат, то перебор прекращается (стоит вначале, чтобы перехватить как результаты предыдущих проходов цикла, так и манипуляций до него - иначе бы всю конструкцию пришлось бы обернуть в if(resultat == false){ [...] }

   if(innerArr[i,0]==param){ resultat = true;//Если что-то нашлось, мен. значение по умолчанию на положительное и начинаем перебирать столбец
     for(var j=0; j<j_max; j++){//Перебор столбца
        if(innerArr[i,j]!=param){resultat = false; break;}//Если облом - то результат сбрасывается снова на отрицательный и переборка столбца прерывается
     }
   }
}

Для перебора строк код аналогичный


text:
Q: No puedo llamar a un metodo en otro metodo Estoy haciendo un ejercicio donde primero hay que ordenar los numeros y luego sacar la mediana, el problema es que no se puedo llamar al metodo ordenar, me sale el error cannot find symbol arreglo=symbol(vec).
public class Mediana {

    public static double[] ordenar(double[] vec){
    double num=0;

       for(int i=0;i<vec.length;i++){
           for(int j=1;j<vec.length-i-1;j++){
                if(vec[j]<vec[j+1]){
                    num=vec[j+1];
                    vec[j+1]=vec[j];
                    vec[j]=num;
               }
            }
     }
     return vec;
   }

    public static double mediana(double[] arreglo){
        arreglo=ordenar(vec);
        int medio=arreglo.length/2;
        double mediana=0;
        if(arreglo.length%2==0){
            mediana= (arreglo[medio-1]+arreglo[medio])/2;
        } else{
            mediana=arreglo[medio];
        }
    return mediana;
    }
}


text:
Q: jQueryUI cannot open modal dialog box I am writing an ajax call to a python backend which generates the HTML for a modal dialog box and pops up said dialog box afterward. However, recently I've been having issues here. My code (thus far) is as follows for the JS frontend.
var deletegroup = function(group){
        $.ajax({
                url: "ajax.py/get_orphaned_networks",
                data: {group: group},
                success: function(result){
                        if (result == 0){
                                alert("Group does not contain networks, no networks will be deleted.");
                        } else {
                                $("#dgf_modal").html(result);
                                $("#dgf_modal").css('visibility', 'visible');
                                $("#dgf_modal").dialog({
                                        modal: true,
                                        closeOnEscape: false,
                                        resizable: false,
                                        draggable: false,
                                        title: "Deleting Group",
                                        width: 500,
                                        height: 500,
                                        buttons: {
                                                "Yes" : function(){
                                                        alert("Well, okay then.");
                                                        $("#dgf_modal").dialog("close");
                                                },
                                                "Cancel" : function(){
                                                        $("#dgf_modal").dialog("close");
                                                }
                                        },
                                        close: function(){
                                                $("#dgf_modal").html("");
                                                $("#dgf_modal").css('visibility', 'hidden');
                                                $(this).dialog("destroy");
                                        }
                                });
                                $("#dgf_modal").dialog("open");
                        }
                },
                error: function(){
                        setlongmessage("An error has occurred. Contact your system administrator.");
                        $("#dgf_status").html("<img src='images/error.png' alt='An error occured.'/>");
                        setTimeout(function(){$("#dgf_status").html("");}, 3000);
                }
        });
}

I've got similar code in another section of my application which works just fine. However, with this one I'm getting the following error:

Error: cannot call methods on dialog prior to initialization;
  attempted to call method 'open'
throw new Error( msg );
jquery.js (line 477)

EDIT: I get the same error message if I call dialog("open") or dialog("close") on the div. Same stack trace, the only error that changes is that it attempted to call method 'close' instead of 'open'.
I'm using the latest versions of jQueryUI and jQuery, as I thought that perhaps updating them would resolve this issue. No dice. Perhaps I'm messing up somewhere in this function, but I do know for sure that the ajax call is returning the proper HTML that it should be returning.
Everything else checks out - I do have my div with the ID dgf_modal, and that works fine. Not exactly sure what's messing up on me now though.

A: There is no reason to call open, use the autoOpen option when you are creating the dialog.

A: Well, I've figured it out. It was my AJAX call after all, returning two divs with the id "dgf_modal". Accidentally tossed that into my for loop when I'm automatically generating table cells as opposed to at the end when I actually close off the table.
In short, I'm an idiot.


text:
Q: how to achieve best tcpip socket data-rate performance Packing as much data as possible per tcp packet will obviously decrease the relative weight of overhead. Increasing buffer size increases robustness against peaks of CPU usage.
But what else can be done to achieve highest data rates?
Is increasing the priority of the data reader thread a good idea? If the highest priority was used, could this thread compete for CPU usage with the Network driver and actually harm performance?
Is blocking or non-blocking best in terms of achievable data rates?
At very high data rates, can overflow of the receive buffers be detected as the buffer gets to, say, 90% and trigger a high priority read?
Other techniques for high data-rate over tcpip sockets?

A: One way would be to use busy polling for getting data from NIC. This can improve the data rate by reducing interrupt overhead. This is done in high performance packet processing frameworks such as DPDK.
Another way would be to avoid copying packets from kernel space to userspace. I don't whether this is possible in your case. Avoiding copying packets by mapping kernel memory to userspace memory. Copying data to userspace is one of the most time consuming step in network stacks. Again this is done in DPDK.


text: Q: Docusign tabs do not appear on the sent document We've added a feature to our app where users can set terms of a loan agreement, and then create a DocuSign contract and send it to the people associated with that deal (brokers, borrowers, etc). Locally, everything works fine, but in production the anchor tabs seem to get lost, because the docs are sent out without any of the tabs applied to them. When a user opens the email they are presented with the "free form" signing mode UI where users can apply any tabs they want, which is the fallback behavior from DocuSign if a document is sent without any tabs. All of the other data(signers, loan terms, company info) is correct and present. When I remote debug prod in Visual Studio, stepping through the flow shows that tabs are created and associated with the correct signers and added to the payload that gets sent to the DocuSign API CreateEnvelope method. Has anyone experienced this before, or know why tabs would get lost in production?


text:
Q: Error: Compiler version ^0.8.0 does not satisfy the r semver requirement I am new to solidity and I am running code on Remix.
It doesn't matter what version of compiler I specify, I keep on getting the same error.
Can someone help me out? What does "Compiler version ^0.8.0 does not satisfy the r semver requirement" exactly mean?
Here is my code:
// SPDX-License-Identifier: UNLICENSED

pragma solidity ^ 0.8.0;
contract Storage {
struct People {
    uint256 favoriteNumber;
    string name;
}

mapping(string => uint256) public nameToFavoriteNumber;
People[] public people;

function addPerson(uint _personFavoriteNumber, string memory _personName ) public {
    people.push(People({favoriteNumber: _personFavoriteNumber, name: _personName}));
    nameToFavoriteNumber[_personName] = _personFavoriteNumber;
}

}

A: I had the same issue a couple of times. In Remix, I added a ".0" to the compiler version like so:
pragma solidity ^0.8.4.0;

I ran into this in Virtual Studio code also but I just ignored it and everything worked fine. I hope this helps!

A: It works in Remix as well, but I have worked on contracts that work without adding that ".0" at last, now even they show this error.
pragma solidity ^0.8.8.0;


text:
Q: use jquery in a javascript function? NEWBIE ALERT! (C# guy trying to learn jQuery for a new MVC app).
I modified some code I found on the web (Stephen Walther- http://bit.ly/bWxU3E) and modified it to use jQuery instead of the MSAjax library. It is a cascading dropdown list and some dummy data. Works great. Next, I try to put the function bindDropDownList() into a separate .js file so I can reuse it. Then it crashes because (I think) the function is all jQuery calls and it can only interpret javascript code. It doesn't recognize the jQuery methods of the objects. Am I totally off here, or is there a trick to make this work?
Here is my code snippet that works perfectly. The function bindDropDownList() is first. If I move it into it's own .js file and reference it, it crashes on the first line, targetDropDownList.empty(), with the error "object doesn't support this method".
<script type="text/javascript">
    function bindDropDownList(parentKey, allOptions, targetDropDownList) {
        targetDropDownList.empty();
        for (var i = 0; i < allOptions.length; i++) {
            option = allOptions[i];
            if (option.ParentKey == parentKey) {
                targetDropDownList.append($('<option/>').attr("value", option.Key).text(option.Name));
            }
        }
    }
</script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#StatesDropDown').change(function () {
            var allOptions = $('#StatesDropDown').data('allOptions');
            bindDropDownList(this.value, allOptions, $('#CitiesDropDown'));
        });
        $('#StatesDropDown').data('allOptions', [{ Key: 1, ParentKey: 1, Name: 'hello' }, { Key: 3, ParentKey: 1, Name: 'helloxxxx' }, { Key: 2, ParentKey: 2, Name: 'yelp'}]);
    });
</script>

A: jQuery methods are JavaScript methods you can use them anywhere after they're defined, I think the issue is your external file being included before jQuery.
When using any library make sure it's included before you try and use its functions.  To fix your issue take a look at your <script> order and adjust accordingly, so that your file comes after the jQuery library.

A: I found the answer on another blog! I kept googling with terms like 'jquery in javascript' and various derivations of such to no avail. But then I googled 'jquery external file' and found the answer here: http://www.latentmotion.com/separating-jquery-functions-into-external-files-without-selectors/
In summary, you can't reference a jquery function in an external library file unless you wrap that function in a special jquery code block.
(function($){
    yourFunction = function() {
        $("body").append('See? It works.');
    };
})(jQuery);

That solved it!


text:
Q: Loop breaks even if answer is invalid Can anyone help me figure out what is wrong with this?
while accept1 == ("yes", "Yes", "no", "No"):
    print ("I see.")
    break
else:
    print ("That's not a valid answer!")
    accept1 = input("Do you accept?")

print ("Let's begin!")

It loops back to "Do you accept" once, then even if you put in an invalid answer, it breaks the loop anyways.

A: == checks for equality , so you are trying to check if the string accept1 is equal to the tuple ("yes", "Yes", "no", "No") , this would never be true. Hence you get the output - "That's not a valid answer!" .
You should use in operator to check if accept1 is equal to one of the elements of the tuple.
Other suggestions, you can use .lower() to make the complete string lowercase to check, and use set. Example -
while accept1.lower() not in {"yes", "no"}:

And your loop is wrong (You are trying to loop as long as the answer is valid, when you should be trying to loop till the answer becomes valid), it should be something like -
accept1 = input("Do you accept?")
while accept1.lower() not in {"yes", "no"}:
    print ("That's not a valid answer!")
    accept1 = input("Do you accept?")
print ("I see.")

A: I think what you want to do is this:
answers = set(['Yes', 'No', 'yes', 'no'])

if accept1 in answers :
    print ("I see.")
else:
    print ("That's not a valid answer!")
    accept1 = input("Do you accept?")

print ("Let's begin!")

You want the inputed value to be "yes", "Yes", "no" or "No", right?