text:
Q: Limit the html content to be displayed in react being displayed by dangerouslysetinnerhtml I have some html content in database and I am trying to dispaly it using dangerouslysetinnerhtml. But I don't want to display the whole content. Lets suppose I have the text content and I want to display only the 100 characters followed by ... .
My content is-

I came across the following line of code which I couldn't understand ,although there are lot of tutorials that gives information related to examples of populate but there is none that explains what exactly it means.Here is a example

A: You can try trunc-html, in our site we make use of this package and it works great, it truncates the input html for the length you want, without breaking the html tree, just use it like this:
const TruncHtml = require('trunc-html');
let html = result.html // or whatever the html comes from
html = TruncHtml(html, 100).html


text:
Q: Stopping and Proceeding a For Loop I have a problem on looping. This is a game of Whack the Mole. First, there is a for loop that is in charge of generating different hole positions for my moles. I want it so that the loop will (1) Generate a number (2) Stop the generating (3) Based on the number that was just generated, run a function for it. Once done running the function, then (4)Start the second round of generating another number......and it goes on for 9 rounds. I have my code here.
var molePosX:Array = [166.90, 494.8, 810.7];
var molePosY:Array = [282.55, 512.45, 730.35];
var moleInUse:Boolean = false;

if (moleInUse == false){
for(var i:uint = 1; i<10; i++){
var randomHole:Number = Math.floor(Math.random()*10)+1; //Generate 10 number
trace(randomHole);
}
}

switch (randomHole){
case 1: trace("1");
moleRun(molePosX[0],molePosY[0]);
break;
case 2: trace("2");
moleRun(molePosX[1],molePosY[0]);
break;
case 3: trace("3");
moleRun(molePosX[2],molePosY[0]);
break;
case 4: trace("4");
moleRun(molePosX[0],molePosY[1]);
break;
case 5: trace("5");
moleRun(molePosX[1],molePosY[1]);
break;
case 6: trace("6");
moleRun(molePosX[2],molePosY[1]);
break;
case 7: trace("7");
moleRun(molePosX[0],molePosY[2]);
break;
case 8: trace("8");
moleRun(molePosX[1],molePosY[2]);
break;
case 9: trace("9");
moleRun(molePosX[2],molePosY[2]);
break;
case 10: trace("10");
break;
}

function moleRun(xPos:Number,yPos:Number){
    moleInUse = true;
    var mole2:Mole = new Mole();
    mole2.x = xPos;
    mole2.y = yPos;
    addChild(mole2);
    moleInUse = false;
}

Thank you ver much!!!

A: You should start the loop with the last broken iteration number. It would be easy to write a separate function for (1) generating the random number. Like:
 // this is a global or instance variable
 var iter:uint = 1;
 // funcation to generate the random number and updating the value of iteration
 function taskNumber1() {
    for(var i:uint = iter; i<10; i++) {
      var randomHole:Number = Math.floor(Math.random()*10)+1; //Generate 10 number
      iter = i;
      break;
   }
   return randomHole;
}

Try it.

A: Sorry, this is not really an answer, but just a suggestion for removing that long switch statement. I added this as an answer as comments don't really format code well...
It looks like you want it to be:
Where index/randomHole = xPos, yPos
1 = 0, 0
2 = 1, 0
3 = 2, 0
4 = 0, 1
5 = 1, 1
6 = 2, 1
7 = 0, 2
8 = 1, 2
9 = 2, 2

You can calculate it out rather then having a long switch statement instead:
x = (index - 1) % 3;
y = Math.floor((index - 1) / 3.0);

or to keep with your variable names:
var xPosIndex:int = (randomHole - 1) % 3;
var yPosIndex:int = Math.floor((randomHole - 1) / 3);
moleRun(molePosX[xPosIndex],molePosY[yPosIndex]);

The hardcoded 3 is the row length, since it looks like each row has 3 values in it (x goes from 0 to 2). An index/randomHole value of 10 would yield x = 0, y = 3 (starting another "row")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unsuccessful Download using DownloadManager in Android 9 I have an xls file in my server which needs to be downloaded in my phone using an apps. I'm using Nokia 5 and Android 9 for testing. My compile sdk version is 29. When I clicked download button, it didn't do anything, and after waiting for a while, a "Download Unsuccessful" notification popped up.
This is my MainActivity.java
public class MainActivity extends AppCompatActivity {

    private static final int PERMISSION_STORAGE_CODE = 1000;
    EditText editUrl;
    Button btnDownload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editUrl = findViewById(R.id.edit_url);
        btnDownload = findViewById(R.id.btn_download);

        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                        String [] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
                        requestPermissions(permissions, PERMISSION_STORAGE_CODE);
                    }
                    else {
                        startDownloading();
                    }
                }
                else {
                    startDownloading();
                }
            }
        });
    }

    private void startDownloading() {
        String url = editUrl.getText().toString().trim();

        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
        request.setTitle("Download");
        request.setDescription("Downloading file...");
        request.allowScanningByMediaScanner();
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ""+System.currentTimeMillis());
        DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch(requestCode) {
            case PERMISSION_STORAGE_CODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    startDownloading();
                else
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

I added network_security_config.xml (domain is blurred for security reason)
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">moneytracker.mauini******.com</domain>
    </domain-config>
</network-security-config>

and added it in manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.main.downloadtest">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:networkSecurityConfig="@xml/network_security_config"
        android:usesCleartextTraffic="true">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

And lastly, the download url is something like this:

http://moneytracker.mauini******.com/uploads/asd.xls

The file is successfully downloaded when that URL is executed in browser.
Am I missing something? Those are all I can get, searching for days. Please help.

A: First, on your code request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, ""+System.currentTimeMillis());. After Environment.DIRECTORY_DOWNLOADS param, you should put correct file name on it. coolfilename.xxx. Or, get its Uri value and put the Uri.getLastPathSegment() as the second parameter. Second, try to put request.setMimeType(param).


text:
Q: Dump debug logs if exception occured I'm writing a java web application. I'm using slf4j & logback for logging. I use debug level to output some information which might be useful to find a bug but generally it's not useful and quite verbose.
I have a place in the application to catch all exceptions and log them. What I would like to do is to capture ALL previous logging output in this thread from the request start and save it all in the separate incident file. So I would have clean logs for system performing without errors and verbose incident log if exception occured.
Is there some ready solution for this problem? May be there's slightly different approach?
Right now I'm saving all debug output into file stored for 7 days but grepping this file is not the easiest task to do when it's required.

A: You can create a custom appender to store all the log messages, and then write to another appender when needed. Call clearLog at the beginning of the request, and writeLog if there's an error.
import java.util.ArrayList;
import java.util.List;

import ch.qos.logback.core.Appender;
import ch.qos.logback.core.AppenderBase;

public class SavingAppender<E> extends AppenderBase<E> {
    private final ThreadLocal<List<E>> events = new ThreadLocal<List<E>>() {
        protected List<E> initialValue() {
            return new ArrayList<>();
        }
    };

    protected void append(E event) {
        events.get().add(event);
    }

    public void clearLog() {
        events.get().clear();
    }

    public void writeLog(Appender<E> other) {
        for(E event:events.get()) {
            other.doAppend(event);
        }
    }
}

Configure all the log messages to go to the appender, and create another appender for the incident logs:
<configuration>
    <appender name="savingAppender" class="SavingAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="outputError" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>error</level>
        </filter>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="incidentAppender" class="ch.qos.logback.core.FileAppender">
        <file>output.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="info">
        <appender-ref ref="savingAppender"/>
        <appender-ref ref="outputError"/>
    </root>

    <logger name="incident">
        <appender-ref ref="incidentAppender"/>
    </logger>
</configuration>

Test class:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;

public class Main {
    public static void main(String[] args) {
        Logger rootLogger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        Appender<ILoggingEvent> savingAppender = ((ch.qos.logback.classic.Logger)rootLogger).getAppender("savingAppender");

        Logger incidentLogger = LoggerFactory.getLogger("incident");
        Appender<ILoggingEvent> incidentAppender = ((ch.qos.logback.classic.Logger)incidentLogger).getAppender("incidentAppender");

        ((SavingAppender<ILoggingEvent>)savingAppender).clearLog();

        LoggerFactory.getLogger(Main.class).error("Error 1...");
        LoggerFactory.getLogger(Main.class).error("Error 2...");
        LoggerFactory.getLogger(Main.class).error("Error 3...");
        LoggerFactory.getLogger(Main.class).info("Info 1...");
        LoggerFactory.getLogger(Main.class).info("Info 2...");
        LoggerFactory.getLogger(Main.class).info("Info 3...");

        ((SavingAppender<ILoggingEvent>)savingAppender).writeLog(incidentAppender);
    }
}


text:
Q: How can I recreate this "wavy" image effect? I'm searching for a way take a an image, or a portion of an image on a webpage and render this or a similar animation effect, where the image is "wavy". Examples:
the "spirit" area:

the robe area:

the robe area:

Preferably I'd like to control the speed and modulation of the waves parametrically.
To me it looks like some sort of displacement map. I thought about either using a fragment shader threejs \ seriously.js or using a canvas element to achieve the same image manipulation, but I'm unsure of the algorithm to use.
What would be a way to achieve this?

A: Oscillators and displacement
You can solve this by using oscillators combined with a grid. Each line in the grid is oscillated and the difference between the lines is used to displace a segment of the image.
The simplest approach, in my opinion, is to create first an oscillator object. It can be very basic, but the point being that an object can be instantiated, and it keeps track of current values locally.
Step 1: The oscillator object
function Osc(speed) {

    var frame = 0;                           // pseudo frame to enable animation

    this.current = function(x) {             // returns current sinus value
        frame += 0.005 * speed;              // value to tweak..
        return Math.sin(frame + x * speed);
    };
}

For example, expand the object to use frequency, amplitude and speed as parameters. If many are to used, also consider a prototypal approach.
If we create a simple grid of five positions, where the three middle vertical lines are being oscillated (edges, being 1. and 5. lines), we will get a result like this (non-tweaked values):

Animated visualization of the oscillated grid-lines:

function Osc(speed) {

  var frame = 0;

  this.current = function(x) {
    frame += 0.005 * speed;
    return Math.sin(frame + x * speed);
  };
}

var canvas = document.querySelector("canvas"),
    ctx = canvas.getContext("2d"),
    w = canvas.width,
    h = canvas.height;

var o1 = new Osc(0.05), // oscillator 1
    o2 = new Osc(0.03), // oscillator 2
    o3 = new Osc(0.06); // oscillator 3

(function loop() {
  ctx.clearRect(0, 0, w, h);
  for (var y = 0; y < h; y++) {
    ctx.fillRect(w * 0.25 + o1.current(y * 0.2) * 10, y, 1, 1);
    ctx.fillRect(w * 0.50 + o2.current(y * 0.2) * 10, y, 1, 1);
    ctx.fillRect(w * 0.75 + o3.current(y * 0.2) * 10, y, 1, 1);
  }
  requestAnimationFrame(loop);
})();
<canvas width=230 height=250></canvas>

Step 2: Use difference between lines in grid for image
The next step is to simply calculate the difference between the generated points for each line.

The math is straight forward, the only thing we need to make sure is that the lines do not overlap as this will create negative widths:
// initial static values representing the grid line positions:
var w = canvas.width, h = canvas.height,
    x0 = 0, x1 = w * 0.25, x2 = w * 0.5, x3 = w * 0.75, x4 = w;

// absolute positions for wavy lines
var lx1 = x1 + o1.current(y*0.2);  // 0.2 is arbitrary and tweak-able
var lx2 = x2 + o2.current(y*0.2);
var lx3 = x3 + o3.current(y*0.2);

// calculate each segment's width
var w0 = lx1;        // - x0
var w1 = lx2 - lx1;
var w2 = lx3 - lx2;
var w3 =  x4 - lx3;

If we now feed these values to drawImage() for destination, using static fixed widths (ie. the grid cell size) for the source, we will get a result like below.
We don't need to iterate the pixels in the bitmap as drawImage() can be hardware-accelerated, does not need to fulfill CORS requirements, and will do the interpolation for us:

var img = new Image();
img.onload = waves;
img.src = "//i.imgur.com/PwzfNTk.png";

function waves() {

  var canvas = document.querySelector("canvas"),
    ctx = canvas.getContext("2d"),
    w = canvas.width,
    h = canvas.height;

  ctx.drawImage(this, 0, 0);

  var o1 = new Osc(0.05), o2 = new Osc(0.03), o3 = new Osc(0.06),
      x0 = 0, x1 = w * 0.25, x2 = w * 0.5, x3 = w * 0.75, x4 = w;

  (function loop() {
    ctx.clearRect(0, 0, w, h);
    for (var y = 0; y < h; y++) {

      // segment positions
      var lx1 = x1 + o1.current(y * 0.2) * 3; // scaled to enhance demo effect
      var lx2 = x2 + o2.current(y * 0.2) * 3;
      var lx3 = x3 + o3.current(y * 0.2) * 3;

      // segment widths
      var w0 = lx1;
      var w1 = lx2 - lx1;
      var w2 = lx3 - lx2;
      var w3 = x4 - lx3;

      // draw image lines ---- source ----   --- destination ---
      ctx.drawImage(img, x0, y, x1     , 1,  0        , y, w0, 1);
      ctx.drawImage(img, x1, y, x2 - x1, 1,  lx1 - 0.5, y, w1, 1);
      ctx.drawImage(img, x2, y, x3 - x2, 1,  lx2 - 1  , y, w2, 1);
      ctx.drawImage(img, x3, y, x4 - x3, 1,  lx3 - 1.5, y, w3, 1);
    }
    requestAnimationFrame(loop);
  })();
}

function Osc(speed) {

  var frame = 0;

  this.current = function(x) {
    frame += 0.002 * speed;
    return Math.sin(frame + x * speed * 10);
  };
}
<canvas width=230 height=300></canvas>

Notice that since we are using fractional values we need to compensate with half a pixel to overlap the previous segment as the end-pixel may be interpolated. Otherwise we will get visible wavy lines in the result. We could use integer values, but that will produce a more "jaggy" animation.
The values of the oscillators will of course need to be tweaked, a grid size defined and so forth.
The next step will be to repeat the oscillators for the horizontal axis, and use the canvas itself as an image source.
Optimization and performance
Using the canvas itself as source caveat
When you draw something from a canvas to itself the browser have to, according to the specs, make a copy of the current content, use that as source for destination region.

When a canvas or CanvasRenderingContext2D object is drawn onto itself,
  the drawing model requires the source to be copied before the image is
  drawn, so it is possible to copy parts of a canvas or scratch bitmap
  onto overlapping parts of itself.

This means that for every drawImage() operation where we use the canvas itself as source, this copy process will happen.
This can possibly take a hit on performance, so to avoid this we can use a second canvas element to which we first copy the finished vertical pass, then use the second canvas as source for the horizontal pass.
LUT and value caching
To increase performance further, cache every value calculation that can be cached. For example, the source width above for each segment (x1-x0 etc.) can be cached to sw variable (or some other name). This is so-called micro-optimization but this is a case where these can matter.
For sinus values, scale etc. it can be an advantage to cache the calculations into a LUT, or look-up-table. The frequencies can be chosen so that the table length match up at some level. I am not showing this here, but something to consider if the browser struggle to keep up in case the grid is of high resolution.
Integer values
Using integer values and turning off image-smoothing is also an option. The result is not so good as with fractional values, but it will give a retro-ish look the animation and perform better.
Sprite-sheet
Dynamically pre-generate frames as sprite-sheet as a last resort is possible. This is more memory hungry and has an initial cost, but will work smoothly almost under any situation. The challenge is to find a looping point and not use too much memory.
Images with alpha-channel
Avoiding images with alpha-channel (as in the demo below) will help as you will need to clear two times extra, one for off-screen canvas, one for main canvas. Otherwise the previous displacement will show in the background.
DEMO OF FINAL RESULT
Here is a complete demo with both vertical and horizontal wavy lines. For simplicity I only use a 4x4 grid.
The result does not look entirely identical to the examples but should give an idea. It's just a matter of increasing the grid resolution and tweaking the parameters. In addition, the examples given in the question are pre-animated with addition effects and layers which is not possible to achieve with just waves/displacement.
Other changes are that now the overlap of each segment is spread over the entire segment by just adding 0.5 at beginning, but also at the end. The horizontal pass also to the width difference inline.
Click Full page when you run the demo below to get a better look at the details.

var img = new Image();
img.onload = waves;
img.src = "//i.imgur.com/nMZoUok.png";

function waves() {
  var canvas = document.querySelector("canvas"),
      ctx = canvas.getContext("2d"),
      w = canvas.width,
      h = canvas.height;

  ctx.drawImage(this, 0, 0);

  var o1 = new Osc(0.05), o2 = new Osc(0.03), o3 = new Osc(0.06),  // osc. for vert
      o4 = new Osc(0.08), o5 = new Osc(0.04), o6 = new Osc(0.067), // osc. for hori

      // source grid lines
      x0 = 0, x1 = w * 0.25, x2 = w * 0.5, x3 = w * 0.75, x4 = w,
      y0 = 0, y1 = h * 0.25, y2 = h * 0.5, y3 = h * 0.75, y4 = h,

      // cache source widths/heights
      sw0 = x1, sw1 = x2 - x1, sw2 = x3 - x2, sw3 = x4 - x3,
      sh0 = y1, sh1 = y2 - y1, sh2 = y3 - y2, sh3 = y4 - y3,

      vcanvas = document.createElement("canvas"),  // off-screen canvas for 2. pass
      vctx = vcanvas.getContext("2d");

  vcanvas.width = w; vcanvas.height = h;           // set to same size as main canvas

  (function loop() {
    ctx.clearRect(0, 0, w, h);

    for (var y = 0; y < h; y++) {

      // segment positions
      var lx1 = x1 + o1.current(y * 0.2) * 2.5,
          lx2 = x2 + o2.current(y * 0.2) * 2,
          lx3 = x3 + o3.current(y * 0.2) * 1.5,

          // segment widths
          w0 = lx1,
          w1 = lx2 - lx1,
          w2 = lx3 - lx2,
          w3 =  x4 - lx3;

      // draw image lines
      ctx.drawImage(img, x0, y, sw0, 1, 0        , y, w0      , 1);
      ctx.drawImage(img, x1, y, sw1, 1, lx1 - 0.5, y, w1 + 0.5, 1);
      ctx.drawImage(img, x2, y, sw2, 1, lx2 - 0.5, y, w2 + 0.5, 1);
      ctx.drawImage(img, x3, y, sw3, 1, lx3 - 0.5, y, w3 + 0.5, 1);
    }

    // pass 1 done, copy to off-screen canvas:
    vctx.clearRect(0, 0, w, h);    // clear off-screen canvas (only if alpha)
    vctx.drawImage(canvas, 0, 0);
    ctx.clearRect(0, 0, w, h);     // clear main (onlyif alpha)

    for (var x = 0; x < w; x++) {
      var ly1 = y1 + o4.current(x * 0.32),
          ly2 = y2 + o5.current(x * 0.3) * 2,
          ly3 = y3 + o6.current(x * 0.4) * 1.5;

      ctx.drawImage(vcanvas, x, y0, 1, sh0, x, 0        , 1, ly1);
      ctx.drawImage(vcanvas, x, y1, 1, sh1, x, ly1 - 0.5, 1, ly2 - ly1 + 0.5);
      ctx.drawImage(vcanvas, x, y2, 1, sh2, x, ly2 - 0.5, 1, ly3 - ly2 + 0.5);
      ctx.drawImage(vcanvas, x, y3, 1, sh3, x, ly3 - 0.5, 1,  y4 - ly3 + 0.5);
    }

    requestAnimationFrame(loop);
  })();
}

function Osc(speed) {

  var frame = 0;

  this.current = function(x) {
    frame += 0.002 * speed;
    return Math.sin(frame + x * speed * 10);
  };
}
html, body {width:100%;height:100%;background:#555;margin:0;overflow:hidden}
canvas {background:url(https://i.imgur.com/KbKlmpk.png);background-size:cover;height:100%;width:auto;min-height:300px}
<canvas width=230 height=300></canvas>


text:
Q: Partitioning requests in code among several servers I have several forum servers (what they are is irrelevant) which stores posts from users and I want to be able to partition requests among these servers. I'm currently leaning towards partitioning them by geographic location. To improve the locality of data, users will be separated into regions e.g. North America, South America and so on.
Is there any design pattern on how to implement the function that maps the partioning property to the server, so that this piece of code has high availability and would not become a single point of failure ?
f( Region ) -> Server IP

A: If you listen to Matt Mullenweg (founder of Wordpress), interviewed by Jason Calacanis in TWiST #26, the only recipe for high-availability that worked was "horizontal expansion" (i.e. "lots and lots of data centers per continent", with a difference between those dedicated for small blogs (low traffic) with less replication across continents, and some dedicated for high-traffic blogs).
So no magic solution except than saying: hardware bing cheaper, have as many data center than you can.


text:
Q: How to keep data sync in android Case : I am running a application in android, now how i do get know whether the server data has been changed as it can be changed from my website.
Mechanism i can think of is:
a) i should call server periodically and check whether the data has been changed recently by maintaining e-tag over there
b) implement push notification and on getting a push notification i will call the server for the data change
Can there be something much than this,
the other part is which one is the better approach(a,b) or both are obsolete?

A: My Opinion is you're asking the wrong question the question is when the user need to know there is new data,if the answer as soon as the data is updated then push would be your way if it's when he is asking for it than go with a.
hope this is useful.

A: Use a pub/sub cloud messaging service like Pusher or Realtime.co
Subscribe a data-updated channel on the Android app and publish a message containing the updated data or the updated data id so the app can retrieve it from your backend.
Realtime.co will even give you an automatic fallback to mobile push notifications using GCM and APNS.
With this approach and using the referred services you'll get a cross-platform solution as a bonus since they have multiple SDKs. If some day you want to build an ios app we can reuse what you already have in place for the Android and Web platforms.


text:
Q: Prevent Flyway Maven Plugin from downloading old slf4j jars When I run the flyway maven plugin it initially downloads the slf4j jars with a version of 1.5.6:
[INFO] ------------------------------------------------------------------------
Downloading: http://repo1.maven.org/maven2/org/slf4j/slf4j-jdk14/1.5.6/slf4j-jdk14-1.5.6.pom
Downloaded: http://repo1.maven.org/maven2/org/slf4j/slf4j-jdk14/1.5.6/slf4j-jdk14-1.5.6.pom (2 KB at 21.3 KB/sec)
Downloading: http://repo1.maven.org/maven2/org/slf4j/slf4j-parent/1.5.6/slf4j-parent-1.5.6.pom
Downloaded: http://repo1.maven.org/maven2/org/slf4j/slf4j-parent/1.5.6/slf4j-parent-1.5.6.pom (8 KB at 154.7 KB/sec)

This plays havoc with my Spring web app as I'm using version 1.7.2 of slf4j there and it gets confused when I restart it.
How can I prevent this? I've tried adding exclusions to my pom.xml:
<groupId>com.googlecode.flyway</groupId>
                <artifactId>flyway-maven-plugin</artifactId>
                <version>2.0.3</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-log4j12</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>slf4j-api</artifactId>
                    </exclusion>
                    <exclusion>
                        <groupId>org.slf4j</groupId>
                        <artifactId>jcl-over-slf4j</artifactId>
                    </exclusion>
                </exclusions>

but this still happens.
UPDATE: what this is causing is the following error when I build with Intellij 12:
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/Users/tom/Library/Caches/IntelliJIdea12/tomcat/Unnamed_incrowdnow/work/Catalina/localhost/_/WEB-INF/lib/slf4j-jdk14-1.5.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/tom/Library/Caches/IntelliJIdea12/tomcat/Unnamed_incrowdnow/work/Catalina/localhost/_/WEB-INF/lib/slf4j-simple-1.7.2.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.JDK14LoggerFactory]
SLF4J: The requested version 1.5.6 by your slf4j binding is not compatible with [1.6, 1.7]
SLF4J: See http://www.slf4j.org/codes.html#version_mismatch for further details.

UPDATE: output of
    mvn dependency:tree -Dverbose -Dincludes=org.slf4j
[INFO] \- com.googlecode.flyway:flyway-maven-plugin:jar:2.0.3:compile
[INFO]    \- org.apache.maven:maven-core:jar:2.2.1:compile
[INFO]       +- org.apache.maven.wagon:wagon-webdav-jackrabbit:jar:1.0-beta-6:runtime
[INFO]       |  +- org.apache.jackrabbit:jackrabbit-webdav:jar:1.5.0:runtime
[INFO]       |  |  \- (org.slf4j:slf4j-api:jar:1.5.3:runtime - omitted for conflict with 1.7.2)
[INFO]       |  \- org.slf4j:slf4j-nop:jar:1.5.3:runtime
[INFO]       |     \- (org.slf4j:slf4j-api:jar:1.5.3:runtime - omitted for conflict with 1.7.2)
[INFO]       +- org.slf4j:slf4j-jdk14:jar:1.5.6:runtime
[INFO]       |  \- (org.slf4j:slf4j-api:jar:1.5.6:runtime - omitted for conflict with 1.7.2)
[INFO]       \- (org.slf4j:jcl-over-slf4j:jar:1.5.6:runtime - omitted for conflict with 1.7.2)

TIA,
Tom

A: Neither the Flyway Maven plugin 2.0.3, nor Flyway Core 2.0.3 depend on slf4j. Check your dependencies. The problem must be coming from somewhere else.

A: I had similar problem and solved it by using flyway-core dependency instead of flyway-maven-plugin dependency.

A: FLyway downloads slf4j dependencies, if your application uses 1.7.x or 1.6.x versions, then you will encounter this issue, since flyway downloads slf4j-nop of 1.5.3 version and slf4j-jdk14 of 1.5.6 version. In eclipse, you can see this under Dependency hierarchy of pom.xml
In order to get rid of this, add all the following exclusiions and you are done
        <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>log4j-over-slf4j</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-nop</artifactId>
            </exclusion>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-jdk14</artifactId>
            </exclusion>
        </exclusions>


text:
Q: how to check an array if each following value is greater than the last i am trying to find a way to validate some numbers in a php array, checking if each value is its greater than the last value.
Here is an example:
$number['num1']=1;
$number['num2']=2;
$number['num3']=3;
$number['num4']=4;

if($number['num1'] > $number['num2'] || $number['num1'] > $number['num3'] ||
$number['num1'] > $number['num4']){

//Some error
}

i can manually check each but is there an easier way, any suggestions?

A: You can achieve this pretty easily with a simple loop and using the PHP array pointer functions next and current:
$array = [1,2,3,4];
$isValid = true;
$current = current($array);
while($next = next($array)) {
    if($next <= $current) {
        $isValid = false;
        break;
    }
    $current = $next;
}

var_dump($isValid);

Example: http://ideone.com/3uHPMq

A: Scopey beat me to it, but here's what I did:
$number['nums'][4] = 4;
$number['nums'][2] = 2;
$number['nums'][1] = 600;
$number['nums'][3] = 3;
// Note, I rearranged the order above just to make sure it
// works no matter what order the values get put in

function isAscending($arr) {
    ksort($arr);

    for ($i=0; $i<count($arr); $i++) {
        if (isset($arr[$i-1])) {
            if ($arr[$i-1] > $arr[$i]) {
                return false;
            }
        }
    }
    return true;
}

var_dump(isAscending($number['nums'])); // false


text:
Q: components used to make a butterworth filter I doing some amateur radio experimentation and want to create a bandpass filter. I believe that a Butterworth filter would be good because it has a flat frequency response in the pass band.
My center frequency is 1000Mhz and the bandwidth is 75 Mhz.
Since the the freq. is relatively high, I think the proper thing to do is use passive components in a ladder-type topology.
Does this seem like the right general path to follow for my design parameters?
Also, I'm going to build a circuit to do some testing. What should I on the lookout for in terms of my passive components (i.e. low ESR caps, etc.)
Thanks.

A: The wavelength at 1GHz is approximately 20cm (\$v\approx\frac{2}{3}c\$) for electrical signals. In order to be able to use a lumped system, you'll need the physical dimensions of the filter to be (preferably much) smaller than that in order to avoid reflections.
As you'll probably don't want to have any power losses in the passband, I guess you'll be going for an LC ladder filter. Design of such filters is quite heavy on the maths unless you use a tool like (eg. Tony Fisher's LC filter calculator). The inductor and capacitor components (as @Mike mentioned) should be able to handle these high frequencies, meaning that at least the Self-Resonant Frequency (SRF) should be high enough. You will find that this also limits the number of component values that you can use. You can avoid this constraint somewhat by connecting components in parallel/series where applicable.
In general you'll want to go for components with a high Q-factor. There are techniques to compensate for lower Q-factors (predistortion), but I could not find an online tool that implements this.
Design of the filter is usually followed by a sensitivity analysis to find out the allowed tolerance on the component values.


text:
Q: ListView Alternate Row Color in Xamarin In my Xamarin app, I'm using foreach loop to get the name and value of available credentials and then Print it on screen using ListView.
e.g.
Name 1
Value 1
Name 2
Value 2
It is working fine. What I want now is to change the style of Name (_attributes.Add(item.Name.ToString());).
e.g.
Name 1
Value
Name 2
Value
View.xml
<ListView
    SeparatorVisibility="None"
    BackgroundColor="#FFFFFF"
    ItemsSource="{Binding Attributes}"
    HasUnevenRows="true">

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>

            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

ViewModel.cs
foreach (var item in _credential.CredentialAttributesValues)
{
    _attributes.Add(item.Name.ToString());
    _attributes.Add(item.Value.ToString());
}

private ObservableCollection<string> _attributes = new ObservableCollection<string>();
public ObservableCollection<string> Attributes
{
    get
    {
        return _attributes;
    }
    set
    {
        this.RaiseAndSetIfChanged(ref _attributes, value);
    }
}

UPDATE
<ViewCell>
    <StackLayout>

    </StackLayout>
</ViewCell>

private ObservableCollection<CredentialPreviewAttribute> _attributes = new ObservableCollection<CredentialPreviewAttribute>();
public ObservableCollection<CredentialPreviewAttribute> Attributes
{
    get
    {
        return _attributes;
    }
    set
    {
        this.RaiseAndSetIfChanged(ref _attributes, value);
    }
}

A: As you have used string datatype it is difficult to understand which string in collection will be name, however if you want to give style according to you index you can follow below link:
https://blog.verslu.is/stackoverflow-answers/alternate-row-color-listview/
or
assuming you have Model named Credential
public class Credential
{
    public string Name { get; set; }
    public string Value { get; set; }
}

and in your ViewModel
private ObservableCollection<Credential> _attributes = new ObservableCollection<Credential>();
public ObservableCollection<Credential> Attributes
{
   get
   {
       return _attributes;
   }
   set
   {
       this.RaiseAndSetIfChanged(ref _attributes, value);
   }
}

and in .xaml
<ListView
    SeparatorVisibility="None"
    BackgroundColor="#FFFFFF"
    ItemsSource="{Binding Attributes}"
    HasUnevenRows="true">

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout>

                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

You can also use single label to achieve the requested view requirement in your question.

      <FormattedString>

      </FormattedString>

A: View.xml
<ListView.ItemTemplate>
    <DataTemplate>
        <ViewCell>

        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>

Style.xaml
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="NameProject.Style.GeneralStyle">

</ResourceDictionary>

Style.cs
public static General SharedInstance { get; } = new General();

App.cs
dictionary.MergedDictionaries.Add(Style.General.SharedInstance);


text:
Q: In the context of Quantum mechanics, what is $(-1)^{\left(\frac{-1}{2}\right)}$ really, $i$ or $-i$? I was doing a Quantum Mechanics problem and came across the quantity $(-1)^{(-{1\over2})}$ within an infinite square well wavefuntion of $\Psi(x,t)=\Psi_1+e^{i\phi}\Psi_2$  and asked to analyze its mathematical behavior when $\phi=0,\pi,\pi/2$, and $\pi/2$ in my $\Psi_2$ presented the problem. I can't find any resources in my textbook or online about this quantity, except for this post, which didn't totally address my concern. How should complex numbers be treated in such a situation? It seems almost dependent on an order of operation, but there are two possible results: $i$ and $-i$.
$$(-1)^{(-{1\over2})} = {(-1)^{{(-1)^{({1\over2})}}}} = \left({1\over-1}\right)^{({1\over2})} = \left({1\cdot(-1)\over(-1)\cdot(-1)}\right)^{({1\over2})} = (-1)^{({1\over2})} = i$$
or omission of the num & denom multiplication of $(-1)$ could result in the same output as below:
$$(-1)^{(-{1\over2})} = {(-1)^{{({1\over2})^{(-1)}}}} = (i)^{(-1)} = \left({1\over i}\right) = \left({1\cdot i\over i\cdot i}\right) = \left({i \over -1}\right) = \left({i\cdot(-1)\over(-1)\cdot(-1)}\right) = -i$$
As the other post mentioned, online calculators favor the second result, but I couldn't glean whether there was a reason for that bias. Between these two (or something else), is there a more correct or conventional result, especially in Quantum Mechanics? I know that square roots yield both positive and negative results, but I beleive that only applies to real numbers, and I haven't yet learned enough complex analysis to know how they're treated in complex spaces.
Any help would be appreciated!


text:
Q: Returning unique_ptr variable returns an error I came across a weird problem.  I get an error message in setGetDog() method when written this way:
class Dog
{
    public:
    void bark() { std::cout << "Bark!" << std::endl; }
};

class test
{
    public:
    std::unique_ptr<Dog> setGetDog()
    {
        if (!dog_)
        {
            dog_ = std::make_unique<Dog>();
        }
        return dog_;
    }

    private:
    std::unique_ptr<Dog> dog_;
};

int main()
{
    auto testClass = std::make_unique<test>();
    auto dog = testClass->setGetDog();
}

Error is like this:
error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = Dog; _Dp = std::default_delete<Dog>]'

But when I change the implementation to:
    std::unique_ptr<Dog> setGetDog()
    {
        return std::make_unique<Dog>();
    }

It works just fine.
What is the matter with dog_?
I do not understand why the error states that it is deleted when in fact test is still alive when the method was called (and so dog_ as well).
I know I can write this some other way but I'm specifically curious on why behavior is like this on this implementation.
Can anyone please enlighten me?

A: There are a few different types of value categories/situations that objects have that affects how there are returned from a function.  Lets look at the rvalue category first.  When you do
std::unique_ptr<Dog> setGetDog()
{
    return std::make_unique<Dog>();
}

std::make_unique<Dog>() returns by value making the return object an rvalue.  That means that when the compiler returns the object it will implicitly move it. (the compiler can also elide the copy but that doesn't matter for this discussion)  Since the object is moved you don't have any issues since std::unique_ptr is movable.
The second case is when you have an lvalue, but it is a function local object.  If you had
std::unique_ptr<Dog> setGetDog()
{
    auto ptr = std::make_unique<Dog>();
    return ptr;
}

Here ptr is an lvalue but it is going away so we can call it an xvalue(expiring value).  With xvalues, when you return them the compiler tries to move it, since moving it is a safe operation in this case.  If the move operation does not exist/is not viable, then the compiler falls back to copying.  Since std::unique_ptr is movable, it gets moved without error.
The last case is when you have a plain lvalue like you have with
class test
{
    public:
    std::unique_ptr<Dog> setGetDog()
    {
        if (!dog_)
        {
            dog_ = std::make_unique<Dog>();
        }
        return dog_;
    }

    private:
    std::unique_ptr<Dog> dog_;
};

Here, dog_ is a member of the class, not a object local to the function.  This means the only thing the compiler can do is try and make a copy.  Since you can't copy a unique_ptr, you get an error.  You would need return std::move(dog_); for it to compile, but if you did that dog_ in the class would be empty.

A: When you just return the unique_ptr then return value optimization can be applied. This is because the unique_ptr can actually be constructed at the address of the unique_ptr instance in the calling function. The compiler allows this as no copying is occurring.
When you add the if, the function may or may not be trying to return an existing instance. It's a runtime decision. An existing instance wont have the opportunity to be constructed where the calling function wants it and so must be copied.
unique_ptr has a deleted copy constructor to preserve the unique part of its contract, so the code does not compile.
Depending on your needs you may want to use a shared_ptr, use std::move (mistake probably, it empties the unique_ptr inside your class) or use value semantics to copy the actual object and not the pointer to it.


text:
Q: Why adding hostnames to /etc/hosts entries change the website viewed Ippsec does a lot of hackthebox boxes walkthroughs and in many of them he edits the /etc/hosts file.
Sometimes he adds multiple hostnames to the same ip address and when he browses those hostnames he gets different webpages. Shouldn't all hostnames return the same webpage? Because my understanding(may be very wrong) is that the /etc/hosts file only links ip addresses to hostnames and so there is no need to do a DNS lookup. Can anybody help me?
Thanks!

A: Web servers see the host header (IE the website name) that the browser is attempting to contact. The host header is sent regardless of how the IP was resolved. A single web server can host multiple sites on a single IP and thus uses the host header to determine which site/content to respond with.


text:
Q: combining columns into one row by comma delimiter and them grouping up to sum other column in R programming I want to transpose data in such a way that column becomes single rows
   col1    Col2                    Col3 Col4       Col5
 1 344230. masalas & spices        4    14           2
 2 344231. hair care               4    14           1
 3 344231. otc                     4    14           1
 4 344231. personal hygiene        4    14           1
 5 344232. detergents              4    14           2
 6 344233. biscuits                4    14           2
 7 344233. chocolates & sweets     4    14           1
 8 344233. dry fruits              4    14           2

Output will be like
col1   Col2                                    Col5
344230 masalas & spices                        2
344231 hair care,otc,personal hygine           1+1+1=3
344232 detergent                               2
344233 biscuits,choclates&sweets,dry fruits    2+1+ 2=5

A:   library(dplyr)
  df %>%
  group_by(col1) %>%
  mutate(Col5 = sum(Col5),
         Col2=paste(Col2,collapse=',')) %>%
  slice(1)

    col1                                 Col2  Col3  Col4  Col5
   <dbl>                                <chr> <int> <int> <int>
1 344230                       masalas&spices     4    14     2
2 344231         haircare,otc,personalhygiene     4    14     3
3 344232                           detergents     4    14     2
4 344233 biscuits,chocolates&sweets,dryfruits     4    14     5

If you don't need Col3 and Col4 you could replace mutate by summarise and skip the slice(1).
Data:
df <-  read.table(text = "
col1    Col2                    Col3 Col4       Col5
 1 344230. masalas&spices        4    14           2
 2 344231. haircare               4    14           1
 3 344231. otc                     4    14           1
 4 344231. personalhygiene        4    14           1
 5 344232. detergents              4    14           2
 6 344233. biscuits                4    14           2
 7 344233. chocolates&sweets     4    14           1
 8 344233. dryfruits              4    14           2    ", h = T)


text:
Q: How do you find out what Exception caused the CDI Transaction Rollback? We are using CDI with CMT (container managed transactions) to connect to the database in the web app and mark methods called from the front-end that require a transaction with:
@Transactional(value=TxType.REQUIRES_NEW)

This will create a new CDI transaction, however now if an exception occurs doing this code block or any other code block called from this method it will throw the error message:
javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
...
Caused by: javax.transaction.TransactionalException: Managed bean with Transactional annotation and TxType of REQUIRES_NEW encountered exception during commit javax.transaction.RollbackException: Transaction marked for rollback.
...
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.

Is there anyway to get CDI to re-throw the nested error so that you can easily debug what the real cause of the rollback was?
(Running on Java-EE7, Glassfish 4.0, JSF 2.2.2)

A: It seems the easiest way to do this is by using a CDI Interceptor to catch the exceptions.  We can define the CDI Interceptor as follows:
@InterceptorBinding
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface TransactionDebugger {
}

Once we have defined the CDI Interceptor, we need to create class that is executed when the Interceptor annotation is used.  We define an @AroundInvoke so that our code is called before the code in the method we annotate.  invocationContext.proceed() will call the method we annotate and give us the result (if any) it returned.  So we can put a try, catch (Exception) around this call to catch any kind of Exception that is thrown.  Then we can log this exception using the logger (log4j used here), and re-throw the Exception so that any upstream code is also informed of it.
Re-throwing the Exception will also allow us to use CMT (Container Managed Transactions) as then ultimately the container will catch the Exception and throw a transaction RollbackException.  However, you could easily use UserTransactions with this also and perform a manual rollback when an exception is caught instead of re-throwing it.
@Interceptor
@TransactionDebugger
public class TransactionInterceptor {
    private Logger logger = LogManager.getLogger();

    @AroundInvoke
    public Object runInTransaction(InvocationContext invocationContext) throws Exception {
        Object result = null;
        try {
            result = invocationContext.proceed();
        } catch (Exception e) {
            logger.error("Error encountered during Transaction.", e);
            throw e;
        }
        return result;
    }
}

Next we must include our new Interceptor in our beans.xml (generally located in src/META-INF), since Interceptors are not enabled by default in CDI.  This must be done in ALL projects where the annotation is used, not just the project where the annotation is defined.  This is because CDI initializes Interceptors on a per project basis:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                           http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" bean-discovery-mode="all">
    <interceptors>
        <class>package.database.TransactionInterceptor</class>
    </interceptors>
</beans>

Finally, we must annotate the methods that we call with our new CDI Interceptor.  Here we annotate them with @Transactional to start a transaction, and @TransactionDebugger to catch any Exception that occurs within the transaction:
@Transactional @TransactionDebugger
public void init() {
    ...
}

This will now log ANY error that occurs while executing the init() code.  The logging granularity can be changed by changing the try, catch from Exception to a sub-class of Exception in the Interceptor implementation class TransactionInterceptor.

A: The TransactionalException is thrown at the commit time, i.e. after your code has been fully executed. Since the transaction is marked for rollback, commit cannot take place and the exception is thrown.
However, the transaction was marked for rollback sometime during the execution. I assume you do not mark it for rollback manually, therefore an exception must have been thrown. The exception is either a RuntimeException or it is annotated with @ApplicationException(rollback = true). Since you don't get this exception, the exception must have been caught somewhere. Are you sure you do not catch exceptions thrown from a business method in your code?
To answer the question... No, I don't think it is possible to rethrow the original exception, because it is thrown at different time and place.


text:
Q: How do I add the values in an array, then output to a calculation function? I'm new to Javascript. My question is - how would I add up values in an array like this:
var pizza = {
    Hawaiianvalue: 9.50,
    Cheesevalue: 9.50,
    Veggievalue: 9.50,
    Supremevalue: 9.50,
    Pepperonivalue: 9.50,
    MeatLoversvalue: 15.50,
    Chicken: 15.50,
    Prawnvalue: 15.50
};

and then output those values to a function similar to this:
function calculateTotalPrice(e){
var calc = (Hawaiianvalue + Cheesevalue + Veggievalue + Supremevalue + Pepperonivalue
    + MeatLoversvalue + Chickenvalue + Prawnvalue);
output1.value = calc; }

?
Thanks in advance :)

A: Iterate object using for...in loop

var pizza = {
  Hawaiianvalue: 9.50,
  Cheesevalue: 9.50,
  Veggievalue: 9.50,
  Supremevalue: 9.50,
  Pepperonivalue: 9.50,
  MeatLoversvalue: 15.50,
  Chicken: 15.50,
  Prawnvalue: 15.50
};

function calculateTotalPrice(e) {
  var calc = 0;
  for (var key in pizza) {
    if (pizza.hasOwnProperty(key))
      calc += pizza[key];
  };
  console.log(calc);
  return calc;
}

calculateTotalPrice();


text:
Q: ui5: move selected rows from table1 to table2 in another view i've a requirement where i've to select (checkboxes) rows from table1 (in view1) to and paste them in table 2 (in view 2). is this possible without call any odata service in table2? please let me know the approach on how to do it. JavaScript way or does ui5 api allows doing this in a better way?

A: Short answer is No, it isn't possible.
SAPUI5 doesn't provide any out-of-box solution/APIs for the kind of 'copy paste' mechanism on a table that you are looking for.
However, if you are really looking for 'dragging and dropping' UI controls, have a look at jQuery UI especially the Draggable and Droppable sections. But beware that as you are integrating it with SAPUI5 controls, you would find unexpected results. ( You MAY not be able to do it at all )
But, if all that you are looking for is to move the data of one table to another, you can try the following,

*

*Assuming that you have bound an OData model to Table1, upon completion of checkbox selection, get all the selected data from the OData model

*Use this data to then bind it to Table2 in another view. At this point I can say Yes, it is possible to bind the same data to Table2 without calling another OData service

You can then fine-tune it accordingly.


text:
Q: reference and pointer used for polymorphism? I studying c++.I am having problem in under standing run time polymorphism ?
why do we need to use reference / pointer when same work can done by creating object of class?
`for eg:
class A{
private:
    int p;
public:
    A(){}   //ctor
    void Print(){}
    void display(){}
    void showrecord(){}
}
class B:public A
{
Private:
     int q;
public:
    B(){}    //ctor
    void Print(){}
    void displayrecord(){}
}

now in  above case i can access any method of B class by using its object  and A class method b using scope resolution then why to use pointer and assign object to it?

A: Lets say you've 3 different cars. And you've different mechanisms of driving them. The driver needn't know about the underlying engines but only the protocol of how to drive a car i.e. press this pedal for acceleration, press that pedal for brakes, etc.
Now from the driver's perspective, it doesn't matter if its Honda, Ford or Buick. From his viewpoint, it is just a car. Likewise, if you've shed, where cars are parked, you call them a car shed. It houses cars and isn't bothered about what make each one is. So
std::vector<Car*> v;
v.push_back(new Ferrari());
v.push_back(new Honda());
v.push_back(new Ford());

why do we need to use reference / pointer when same work can done by creating object of class?

Without a pointer or reference, you cannot create a collection of objects that have some commonality, but different in some specific sense. This is circumvented in some strict OOP languages like Java, C#, etc. by making all objects derive from a base class called Object. C++ is a multi-paradigm language and the programmer is free to make such decisions as appropriate to his/her project. A way to do it in C++ is via pointers of the base class. This idiom is called run-time polymorphism.
for (const auto &this_car : v)
     this_car->drive();

Here irrespective of the actual make, the vector v will be able to hold the car, as long as the base class car is part of the type. Likewise, drive will be different for each make, but that isn't required to be known for the function which calls it.
EDIT:
Thanks to nijansen for pointing out that this post doesn't actually answer the question: why pointers or references (dynamic types) are required for run-time polymorphism? it only says they've to used to achieve it but doesn't explain why can't we use ordinary (static type) variables.
C++ is designed in such a way that an object's type may or may not be known completely at compile-time with just the type in hand. In Circle c; we know c is of type Circle; whereas in Shape *p = make_shape(); we really do not know what object p is pointing to; p's own type is Shape* but its pointed-to object's concrete type is unknown. All we know is that it is pointing to some object which derives from Shape. Please do not confuse yourself with dynamic or automatic memory allocation; this is the same for automatic variables too E.g. Shape *p = &c;. Here too p in isolation the compiler doesn't know what concrete type the object is of, which p is pointing to.
Had we written p as a static (non-pointer, non-reference) type Shape p = make_shape(); or Shape p = c; what really happens in slicing i.e. p will be of the concrete type Shape and since it's not a pointer, it'll copy (Shape) part of Circle object c to it, which is mostly undesirable.
Without knowing the underlying type, how do we call the right concrete type's functions? C++ provides virtual functions to do the job. This is why runtime polymorphism is always explained with virtual methods in C++; while in languages like Java and C# all methods are virtual and all object types are references/pointers. In a way the answer to your question is, the language is designed such that one needs reference/pointer variables for runtime polymorphism.

A: To give you a general example,
Please excuse the pseduocode. Will add a Cpp Code in some time, bit rusty now
Super Class
Class Animal
{

}

Sub Classes
Class Dog : public Animal
{

}

Class Cat : public Animal
{

}

Another class,
class Vet
{
    void checkAnimal(recieve Animal)
    {

    }
}

Now consider this usage,
vetObject.checkAnimal(dogObject);
vetObject.checkAnimal(catObject);

If it weren't for polymorphism your Vet Class would have been something like this,
class Vet
{
    void checkAnimal(recieve Cat)
    {

    }

    void checkAnimal(recieve Dog)
    {

    }

     ....  and so on
}

A: Thereby you can do some generic processess to every object. For example you have Chicken : Animal class and you have Cow : Animal class , and they have common function doSlaughter(), and you have SlaughterHouseJob class. When you want to process slaughterHouseJob.doSlaughterAnimals() method, you can simply write this code:
for(Animal animal:animals){
    animal.doSlaughter(); //It can be chicken or Cow or other animals. Simply one function for all jobs
}


text:
Q: Awstats tool : issue with missing icons and histogram bars on main page of Awstats - probably an issue of path defined into Apache I meet difficulties to make appear with awstats tool (CGI script), icons and associated histogram bars, on one of my website (dubbed here website.com).
The issue is pretty tricky since I am using different RewriteCond and RewriteRules to get http://www.website.com, http://website.com, https://www.website.com redirections to https://website.com target.
Moreover, the task is more complex because I have a Zope server after Apache.
So, to summarize, here below all these rewritecond and rewriterules which produce what is expected, i.e all redirections to https://website.com and access by password to the awstats tool. Everything is working fine except the fact that icons and histograms are  missing in main page of awstats once this latter is loaded:
<VirtualHost *:443>

    # Test local
    ServerAdmin admin@website.com
    ServerName website.com
    ServerAlias www.website.com

    # LOG
    CustomLog /var/log/apache2/access.log combined

    # ACTIVATE SSL
    SSLEngine On
    SSLCertificateFile /etc/letsencrypt/live/website.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/website.com/privkey.pem
    SSLCertificateChainFile /etc/letsencrypt/live/website.com/chain.pem

    RewriteEngine On
    # www to non www for HTTPS
    # checking for the same thing again
    RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
    # some people might argue second redirect here is excessive since you already arrived at correct host, but I'd leave this for you to sort out
    RewriteRule ^/(.*) https://website.com/$1 [R=301,L]
    # your /cgi-bin checks can be merged into one regex
    RewriteCond %{REQUEST_URI} !^/cgi-bin/(search|awstats) [NC]
    RewriteRule ^/(.*)  https://localhost:8443/++vh++https:%{SERVER_NAME}:443/++/$1 [P,L]

    SSLProxyEngine On
    RequestHeader set Front-End-Https "On"
    #CacheDisable *

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/

    Alias /awstatsclasses "/usr/share/awstats/lib/"
    Alias /awstats-icon "/usr/share/awstats/icon/"
    Alias /awstatscss "/usr/share/fdoc/awstats/examples/css"

<Files "awstats.pl">
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        SetHandler cgi-script
        Satisfy any
        Order deny,allow
        Deny from all
        AuthType Basic
        AuthName "Advanced Web Statistics"
        AuthUserFile /etc/apache2/awstats-users.pwd
        Require valid-user
</Files>

<Directory "/usr/share/awstats/icon">
        AllowOverride None
        Order allow,deny
        Allow from all
</Directory>

<Directory "/usr/lib/cgi-bin/">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
        SSLRequireSSL
</Directory>

</VirtualHost>

I am not an expert about the CGI scripts and their alias. All the icons are located into /usr/share/awstats/icon/ directory.
Where is my error?
UPDATE 1 :
0) I realized that Alias /awstatsclasses "/usr/share/awstats/lib/" and
    Alias /awstatscss "/usr/share/doc/awstats/examples/css" don't seem to be necessary,   but for Alias /awstats-icon "/usr/share/awstats/icon/", this is necessary.
However, this is an issue of CSS but I think the most important file is the directory of icons.
1) I have found and installed the package awstats_7.6 for Debian 10 Buster.
Now, all files (plugin, lib, lang etc ...) are located into /usr/share/awstats/
For the moment, I have further informations from Apache2 logs. When I reload the awstats page (reachable from https://website.com/cgi-bin/awstats.pl) , I get into access.log :
    100.87.10.76 - - [02/Apr/2020:01:20:06 +0200] "GET /awstats-icon/browser/notavailable.png HTTP/1.1" 404 434 "https://website.com/cgi-bin/awstats.pl?framename=mainright" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:74.0) Gecko/20100101 Firefox/74.0"
    100.87.10.76 - - [02/Apr/2020:01:20:06 +0200] "GET /awstats-icon/other/hx.png HTTP/1.1" 404 434 "https://website.com/cgi-bin/awstats.pl?framename=mainright" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:74.0) Gecko/20100101 Firefox/74.0"
    100.87.10.76 - - [02/Apr/2020:01:20:06 +0200] "GET /awstats-icon/other/he.png HTTP/1.1" 404 434 "https://website.com/cgi-bin/awstats.pl?framename=mainright" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:74.0) Gecko/20100101 Firefox/74.0"
    ... etc

I have put etc to mean all the list of icons missing.
2) Moreover, I have this message at the top once I load awstats main page :

Conclusion : I don't know anymore what to try. However, from the 1) part above, I have explicitely indicated in Apache2 config file :
ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
Alias /awstats-icon "/usr/share/awstats/icon"

with permissions :
drwxr-xr-x 9 www-data www-data 4096 Apr  2 16:25 /usr/share/awstats/icon/

3) Finally, I think  the most interesting information comes from the error.log of Apache2 :
[Thu Apr 02 01:37:04.344047 2020] [proxy:debug] [pid 19209] proxy_util.c(2578): [client 100.87.10.76:40246] AH00947: connected /++vh++https:website.com:443/++/awstats-icon/other/hh.png to localhost:8443, referer: https://website.com/cgi-bin/awstats.pl?framename=mainright
[Thu Apr 02 01:37:04.600404 2020] [proxy:debug] [pid 19209] proxy_util.c(2316): AH00942: HTTPS: has acquired connection for (*)

This shows  the conflicts between the path of Virtualhost from Zope and the path of CGI scripts from Apache2, especially with the first line :
/++vh++https:website.com:443/++/awstats-icon/other/hh.png to localhost:8443, referer: https://website.com/cgi-bin/awstats.pl?framename=mainright

What do you think about all these clues ?
UPDATE 2: Following the suggestion of @Tom Hundt, I generate a deeper analysis into log rewrite. Below is what I get when I load the awstats main page.
[Sun Apr 05 16:17:01.057073 2020] [rewrite:trace3] [pid 25288] mod_rewrite.c(483): [client 31.11.12.101:51422] 31.11.12.101 - - [website.com/sid#7fa0b5d01d98][rid#7fa0ba0930a0/initial] applying pattern '^/(.*)' to uri '/awstats-icon/other/hx.png', referer: https://website.com/cgi-bin/awstats.pl?framename=mainright
[Sun Apr 05 16:17:01.057093 2020] [rewrite:trace3] [pid 25288] mod_rewrite.c(483): [client 31.11.12.101:51422] 31.11.12.101 - - [website.com/sid#7fa0b5d01d98][rid#7fa0ba0930a0/initial] applying pattern '^/(.*)' to uri '/awstats-icon/other/hx.png', referer: https://website.com/cgi-bin/awstats.pl?framename=mainright
[Sun Apr 05 16:17:01.057107 2020] [rewrite:trace2] [pid 25288] mod_rewrite.c(483): [client 31.11.12.101:51422] 31.11.12.101 - - [website.com/sid#7fa0b5d01d98][rid#7fa0ba0930a0/initial] rewrite '/awstats-icon/other/hx.png' -> 'https://localhost:8443/++vh++https:website.com:443/++/awstats-icon/other/hx.png', referer: https://website.com/cgi-bin/awstats.pl?framename=mainright
[Sun Apr 05 16:17:01.057120 2020] [rewrite:trace2] [pid 25288] mod_rewrite.c(483): [client 31.11.12.101:51422] 31.11.12.101 - - [website.com/sid#7fa0b5d01d98][rid#7fa0ba0930a0/initial] forcing proxy-throughput with https://localhost:8443/++vh++https:website.com:443/++/awstats-icon/other/hx.png, referer: https://website.com/cgi-bin/awstats.pl?framename=mainright
[Sun Apr 05 16:17:01.057131 2020] [rewrite:trace1] [pid 25288] mod_rewrite.c(483): [client 31.11.12.101:51422] 31.11.12.101 - - [website.com/sid#7fa0b5d01d98][rid#7fa0ba0930a0/initial] go-ahead with proxy request proxy:https://localhost:8443/++vh++https:website.com:443/++/awstats-icon/other/hx.png [OK], referer: https://website.com/cgi-bin/awstats.pl?framename=mainright

It seems an interesting line is :
[Sun Apr 05 16:17:01.057073 2020] [rewrite:trace3] [pid 25288] mod_rewrite.c(483): [client 31.11.12.101:51422] 31.11.12.101 - - [website.com/sid#7fa0b5d01d98][rid#7fa0ba0930a0/initial] applying pattern '^/(.*)' to uri '/awstats-icon/other/hx.png', referer: https://website.com/cgi-bin/awstats.pl?framename=mainright

It is indicated that pattern '^/(.*)' is applied to to uri '/awstats-icon/other/hx.png'.
So I conclude that my isssue since the beginning comes from the rewrite rules I apply on URL with cgi-bin directory, i.e when I do :
RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^/(.*) https://website.com/$1 [R=301,L]
RewriteCond %{REQUEST_URI} !^/cgi-bin/(search|awstats) [NC]
RewriteRule ^/(.*)  RewriteRule ^/(.*)  https://localhost:8443/++vh++https:%{SERVER_NAME}:443/++/$1 [P,L]

Do you agree ?

A: Your current config prevents proxying for /cgi-bin/ with the RewriteCond here:
RewriteCond %{REQUEST_URI} !^/cgi-bin/(search|awstats) [NC]
RewriteRule ^/(.*)  https://localhost:8443/++vh++https:%{SERVER_NAME}:443/++/$1 [P,L]

You need also short-circuit for /awstats* so they aren't proxied to that zope nonsense.
Multiple conditions are AND'ed by default so it's easy:
RewriteCond %{REQUEST_URI} !^/awstats [NC]
RewriteCond %{REQUEST_URI} !^/cgi-bin/(search|awstats) [NC]
RewriteRule ^/(.*)  https://localhost:8443/++vh++https:%{SERVER_NAME}:443/++/$1 [P,L]

A: I think you forgot the quotes, if this doesn't fix your issue check for apache error log
Alias "/awstatsclasses" "/usr/share/awstats/lib/"
Alias "/awstats-icon" "/usr/share/awstats/icon/"
Alias "/awstatscss" "/usr/share/doc/awstats/examples/css"

A: Suggestion: Turn on logging for mod_rewrite temporarily.
In http.conf put:
LogLevel alert rewrite:trace3

and then (optionally) in your shell you can do
tail -f error_log|fgrep '[rewrite:'

to help figure out what is happening.


text:
Q: Looking for simple example to write text into a NSImage using Cocoa     NSImage *myNewIconImage=[[NSImage imageNamed:@"FanImage"] copy];
    [myNewIconImage lockFocus];
    [@"15" drawAtPoint:NSZeroPoint withAttributes:nil];
    [myNewIconImage unlockFocus];

    [myNewIconImage setTemplate:YES];
    [[NSApplication sharedApplication]] setApplicationIconImage:myNewIconImage];

I am looking for a way to simply write a String onto this image.... and coming up very short. This does not worker me.

A: The following code will place a mutable attributed string on an NSImage:
NSImageView *imageView = [[NSImageView alloc] initWithFrame:NSMakeRect( 0, 0, _wndW, _wndH )];
[[window contentView] addSubview:imageView];
NSImage *image = [NSImage imageNamed:@"myImage.jpg"];
[image lockFocus];
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
[attr setObject:[NSFont fontWithName:@"Lucida Grande" size:36] forKey:NSFontAttributeName];
[attr setObject: [NSNumber numberWithFloat: 10.0] forKey: NSStrokeWidthAttributeName];
[attr setObject:[NSColor whiteColor] forKey:NSForegroundColorAttributeName];
NSString *myStr = @"Welcome to Cocoa";
NSMutableAttributedString *s = [[NSMutableAttributedString alloc] initWithString: myStr attributes:attr];
[s drawAtPoint:NSMakePoint(130,130)];
[image unlockFocus];
[imageView setImage:image];


text:
Q: Ornstein-Uhlenbeck and Stationarity I'm taking a Statistical Mechanics course and we just started discussing the Ornstein-Uhlenbeck process. I'm confused by what seems to be two contradictory facts about this process. For one, it is Gaussian, Markov, and Stationary. Stationary, as I currently understand it, means the moments of its distribution do not vary with time and, specifically, the autocorrelation function doesn't vary with time. On the other hand, Doob's theorem shows that any Markov and Gaussian process has a correlation function which is proportional to $e^{-t}$. But this would suggest the correlation function does vary with time, meaning it isn't stationary.
What false assumption am I making that leads to this contradiction?

A: The correlation function is proportional to $e^{-\gamma\tau} = e^{-\gamma|t-t'|}$, see e.g. this paper for a more verbose definition than the MathWorld page. And this is indeed stationary under a translation $t \mapsto t + dt$ of the time.


text:
Q: Resuming AVPlayer after phone call There appears to be many solutions on SO addressing this yet none of those solutions have worked for me. I'm currently using Swift 5. I have a AVPlayer playing an animation (that loops) in my ViewController. When a call comes in through CallKit, regardless of whether I answer or decline the call, the animation played by the AVPlayer does not resume after the call has been dealt with. The interruption handler seems to be called before an interruption but usually doesn't get called after the interruption.
        override func viewDidLoad() {
            super.viewDidLoad()
            prepareBGVideo()
            ...
            NotificationCenter.default.addObserver(
                self,
                selector: #selector(applicationWillEnterForeground(notification:)),
                name: UIApplication.willEnterForegroundNotification,
                object: nil)
            ...
        }

       func prepareBGVideo() {
            guard let path = Bundle.main.path(forResource: "animation", ofType:"mp4") else {
                print("video not found")
                return
            }

            let item = AVPlayerItem(url: URL(fileURLWithPath: path))
            avPlayer = AVPlayer(playerItem: item)

            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(loopVideoBG),
                                                   name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                                   object: item)
            NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil)
            avPlayerLayer = AVPlayerLayer(player: avPlayer)
            avPlayerLayer.backgroundColor = UIColor.black.cgColor
            avPlayer.volume = 0
            avPlayer.actionAtItemEnd = .none
            avPlayer.play()

            view.backgroundColor = .clear
            avPlayerLayer.frame = view.layer.bounds
            view.layer.insertSublayer(avPlayerLayer, at: 0)
            avPlayerLayer.videoGravity = isIPAD ? AVLayerVideoGravity.resize : AVLayerVideoGravity.resizeAspectFill // Changed from AVLayerVideoGravity.resizeAspect to AVLayerVideoGravity.resize so that video fits iPad screen

            NotificationCenter.default.addObserver(self,
                                                   selector: #selector(willEnterForeground),
                                                   name: UIApplication.willEnterForegroundNotification,
                                                   object: nil)
        }

        @objc func handleInterruption(notification: Notification) {
            guard let info = notification.userInfo,
                let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
                let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
                    return
            }
            if type == .began {
                // Interruption began, take appropriate actions (save state, update user interface)
                self.avPlayer.pause()
            } else if type == .ended {
                guard let optionsValue =
                    info[AVAudioSessionInterruptionOptionKey] as? UInt else {
                        return
                }
                let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
                if options.contains(.shouldResume) {
                    // Interruption Ended - playback should resume
                    self.avPlayer.play()
                }
            }
        }

        /// Resume video while app wake up from background
        @objc func willEnterForeground() {
            avPlayer.seek(to: CMTime.zero)
            JPUtility.shared.performOperation(0.1) {
                self.avPlayer.play()
            }
        }

        @objc func loopVideoBG() {
            avPlayer.seek(to: CMTime.zero)
            avPlayer.play()
        }

Here are all the solutions that I have tried:

*

*Waiting two seconds before calling self.avPlayer.play() in if options.contains(.shouldResume){}

*Setting AVAudioSession.sharedInstance().setActive to false when interruption begins and then setting it ot true when interruption ends. The issue with this approach is that the if interruption == .ended {} block doesn't always get invoked so setting setActive had no effect.

*Setting AVAudioSession playback category to AVAudioSessionCategoryOptions.MixWithOthers. My animation doesn't have audio anyway.

I have seen mentions of resuming playback in applicationDidBecomeActive(_:) but some advised against this. Would this be considered good practice?
Is there a way to ensure that the else if type == .ended {} block gets executed? Or perhaps a workaround that works more reliably than observing AVAudioSession.interruptionNotification?

A: I solved this but creating a shared VideoPlayer class that contained references to all the screen that had animations.
import Foundation
import UIKit
import AVKit

    class VideoPlayer: NSObject {

        static var shared: VideoPlayer = VideoPlayer()

        var avPlayer: AVPlayer!
        var avPlayerLayer: AVPlayerLayer!

        weak var vcForConnect:ConnectVC?
        weak var vcForList:ListVC?

        override init() {
            super.init()
            guard let path = Bundle.main.path(forResource: "animation", ofType:"mp4") else {
                print("video not found")
                return
            }
            avPlayer = AVPlayer(url: URL(fileURLWithPath: path))
            avPlayerLayer = AVPlayerLayer(player: avPlayer)
            avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
            avPlayer.volume = 0
            avPlayer.actionAtItemEnd = .none
            loopVideo(videoPlayer: avPlayer)
            avPlayer.play()
            NotificationCenter.default.addObserver(self, selector: #selector(handleInterruption(notification:)), name: AVAudioSession.interruptionNotification, object: nil)

        }

        deinit {
            avPlayer.pause()
        }

        @objc func handleInterruption(notification: Notification) {
            guard let info = notification.userInfo,
                let typeValue = info[AVAudioSessionInterruptionTypeKey] as? UInt,
                let type = AVAudioSession.InterruptionType(rawValue: typeValue) else {
                    return
            }
            if type == .began {
                // Interruption began, take appropriate actions (save state, update user interface)
                self.avPlayer.pause()
            } else if type == .ended {
                guard let optionsValue =
                    info[AVAudioSessionInterruptionOptionKey] as? UInt else {
                        return
                }
                let options = AVAudioSession.InterruptionOptions(rawValue: optionsValue)
                if options.contains(.shouldResume) {
                    // Interruption Ended - playback should resume
                    self.avPlayer.play()
                }
            }
        }

        func resumeAllAnimations() {
            self.avPlayer.play()
            if vcForList?.avPlayer != nil {
                vcForList?.avPlayer.play()
            }
            if vcForConnect?.avPlayer != nil {
                vcForConnect?.avPlayer.play()
            }
            if vcForConnect?.avPlayerBG != nil {
                vcForConnect?.avPlayerBG.play()
            }
        }
        ...
    }

I then resume the animations by calling resumeAllAnimations() in applicationDidBecomeActive(_:) in AppDelegate.swift like so:
func applicationDidBecomeActive(_ application: UIApplication) {
        VideoPlayer.shared.resumeAllAnimations()
        ...
}


text:
Q: Control truetype font tracking in fontforge I'm designing a font intended to be used mainly as a subtitle font. It's a sans-serif font not unlike Helvetica.
The em size is 2000 (I know it "should" be 2048 for a truetype font), the ascent/descent are 1600/400. Most glyphs don't go higher than 1450 though, with the exception of accented Latin characters.
There lies the issue: when my font includes accented Latin characters, the tracking (line -of-text intradistance, but correct me if I got the term "tracking" wrong) skyrockets. I can't seem to find a way to control that.
As my intended design goes, I don't mind if I have a descender (e.g. "g") above and an accented capital Latin letter below and they almost touch. It's something that does not happen very often, anyway.
How can I control tracking? It seems it's auto-calculated.

A: After a lot of search, I found the answer lies in the OS/2 tables, in the Metrics tab. I understand that there were many involved in specifying Truetype, so all details are scattered in a font file.
I will leave the question unanswered for a while, in case someone supplies pointers to more complete information.
Actually, the minimum/maximum heights defined in the font determine the font tracking, and the OS/2 tables can be used to increase that, never to decrease it.


text:
Q: How can I get a cumulative product with Snowflake? I want to calculate the cumulative product across rows in Snowflake.
Basically I have monthly rates that multiplied accumulate across time.
(Some databases have the product() SQL function for that).

A: A trick suggested by Sterling Paramore: Add logs, and then exponentiate it:
with data as (select $1 x from values (1),(2),(3),(4),(5))

select x
    , sum(x) over(order by x) sum
    , exp(sum(ln(x)) over(order by x)) mult
from data

A: If a built-in function doesn't exist, it's usually possible to roll something custom using a User-Defined Table Function.
In this case:
CREATE OR REPLACE FUNCTION CUMULATIVE_PRODUCT(VALUE double)
    RETURNS TABLE (PRODUCT double)
    LANGUAGE JAVASCRIPT
    AS '{
        initialize: function(argumentInfo, context) {
           this.cumulativeProduct = 1;
        },
        processRow: function f(row, rowWriter, context){
           this.cumulativeProduct = this.cumulativeProduct*row.VALUE;
           rowWriter.writeRow({PRODUCT: this.cumulativeProduct});
        }
    }';

Example table:
create temp table sample_numbers as (
select 1 as index, 5.1::double as current_value
    union all
select 2 as index, 4.3::double as current_value
    union all
select 3 as index, 3.7::double as current_value
    union all
select 4 as index, 3.9::double as current_value
)

invoking the UDTF:
select index,current_value,PRODUCT as cumulative_product
from sample_numbers,table(CUMULATIVE_PRODUCT(current_value) over ())

Note the empty over() clause which forces Snowflake to do a single sequential run over the data instead of splitting it into parallel chunks


text:
Q: Flexbox layout keeps overlapping footer in mobile view I'm attempting to use a flexbox column layout with header and footer. While the browser is maximized, the layout looks clean. When you resize the window (like viewing on a phone) I'm trying to get the blocks to stack, but the main content overlaps the left column and the right column overlaps the footer.

.wrap {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  -ms-flex-direction: column;
  flex-direction: column;
  height: calc(100vh - 80px);
  width: 70%;
  margin: 0 auto;
  text-align: center;
}
header {
  padding: 20px;
  background: #222930;
  color: #E9E9E9;
  height: 125px;
}
footer {
  padding: 20px;
  background: #222930;
  color: white;
  bottom: 0;
  text-align: center;
}
main {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-flex: 1;
  -webkit-flex-grow: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
  background: #222930;
}
main .content {
  -webkit-box-flex: 1;
  -webkit-flex-grow: 1;
  -ms-flex-positive: 1;
  flex-grow: 1;
  background: #222930;
  color: #E9E9E9;
}
main .left {
  width: 160px;
  background: #222930;
  -webkit-box-ordinal-group: 0;
  -webkit-order: -1;
  -ms-flex-order: -1;
  order: -1;
  color: #E9E9E9;
}
main .right {
  width: 160px;
  background: #222930;
  color: white;
}
@media (max-width: 640px) {
  main {
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
  }
  main .left,
  main .right {
    width: auto;
    height: 50px;
  }
}

  header

content

left

right

  footer

I have more content on the page, but I didn't see it necessary to paste it. If anyone is curious what I am experiencing, here is a visual of it maxed:

And this is what it looks like on a phone:

Like I said, I'm trying to get the blocks to stack on top of each other, or even make the menu turn in to a drop down when scaled down, but the footer still overlaps.
Some suggestions would be great, not sure what I'm missing here. First time I'm trying a flexbox approach..

A: It looks like you have a fixed height on your flex container:
.wrap {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 80px);    /* fixed height */
    width: 70%;
    margin: 0 auto;
    text-align: center;
}

Instead of height try min-height, which will allow the container to grow.

A: Adding flex-shrink: 0; to the main works for me.
I've made a quick pen of the issue/fix, http://codepen.io/anon/pen/eZXJop.
I believe the problem stems from setting a height on the .wrap element. So it may be better to do that differently, I think you could likely achieve the same without using calc(); too.


text:
Q: Custom Field Validator Client Side on Yii2 I have some trouble when i try to add a custom Validator rule for my input.
This is my code.
MODEL
class Category extends \yii\db\ActiveRecord{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'cat';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cat_cod','cat_deep','cat_father'], 'required'],
            //other rules
            [['cat_cod'], 'test'],

        ];
    }
    public function test($attribute){
        $cat_cod = $this->$attribute;
        if($cat_cod == 'test'){
            $this->addError($attribute,"Error Test");
        }
    }

So, this is only a test, but it works fine when i submit my form, but it doesn't work in client side validaton.
if cat_cod is empty:

if i write test in the input field

In the 2 image when i write test doesn't validate on client side
UPDATE
Afte Yupik Comment, server side validation works fine, so if i want to add client side validation i must implement an AjaxValidation.
So i've activated ajax validation in only one field like this
$form->field($model, 'cat_cod',['enableAjaxValidation' => true])->textInput();

Now in my controller how can i handle this? Documentation is not very clear.
This is What i've try
if($model->load(Yii::$app->request->post()) && $model->validate()){
        if (Yii::$app->request->isAjax ) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
   //something else

A: Because this is server side validator. To add client side validator use whenClient to check whether rule should be applied.
Read more docs


text:
Q: Tangent line problem with implicit differentiation Given:
$[\tan^{-1}(x)]^2+[\cot^{-1}(y)]^2=1$
Find the tangent line equation to the graph at the point $(1,0)$ by implicit differentiation
I found the derivative:
$\dfrac{dy}{dx}=\dfrac{4\tan^{-1}(x)\cdot \cot^{-1}(y)}{(y^2+1)(x^2+1)}$
I may have done my derivative wrong, but my main concern is at some point $0$ will be plugged into $\cot$ inverse, resulting in division by zero.
I need help with this scenario.

A: $\displaystyle \frac{2\tan^{-1} x}{1+x^{2}} \, dx-\frac{2\cot^{-1} y}{1+y^{2}} \, dy=0$
$\displaystyle \frac{dy}{dx}=\frac{(1+y^{2})\tan^{-1} x}{(1+x^{2})\cot^{-1} y}$
Note that $(1,0)$ doesn't lie on the graph.
The graph can be parametrized as $(x,y)=(\tan \cos t,\cot \sin t)$


text:
Q: Browser Client with no Peers is Pulling the updated data from Other Browser Clients with a Peer I referred the following link for setting up the gun server instance in hello.js and browser client in index.html.
https://[github.com/amark/gun/wiki/getting-started-(v0.3.x)]
While creating the hello.js i excluded the following code

var Gun = require('gun');
var gun = Gun();

with the following lines of code

// Our GUN setup from the last example.
var Gun = require('gun');
var gun = Gun({web: server});

while merging the snippets for hello.js
I registered the server instance in localhost as peer in the index.html.First I invoked the index.html in 2 browser windows after starting the hello.js based gun server instance.I could observe the updates issued from each browser being reflected in both windows.Now I created a copy of index.html and removed the peer.The peer Array is now empty.But when I opened up this modified browser client I was able to see all the data from the server set up in the localhost in the console.How is this possible?How can a browser client with no peer get the data from other clients which has registered the peer.
Thanks in advance
TEST

A: I am guessing it was already saved to localStorage in the browser by a previous browser tab, and that they are both in the same session.
If you open it in an incognito browser tab (or another browser), do you still see the data?


text:
Q: Add Data to a new row in excel file using PHP I have the following code that adds data from my form to an excel spreadsheet. However, when a new user fills out the form it overwrites the data on the first row, how would I make sure that new form submissions populate a new row in this file "datacollection.xlsx"
<?php

$name = $_POST['name'];
$email = $_POST['email'];
$title = $_POST['title'];
$company = $_POST['company'];

$fp=fopen(".datacollection.xlsx","w");
fputcsv($fp, array($name, $email, $title, $company), ';');
fclose($fp);

?>

Help is appreciated!

A: use a+ instead of w mode of fopen(), so that it places the file pointer at the end of the file. Like:
...
$fp=fopen(".datacollection.xlsx","a+"); //use a+ instead of w
fputcsv($fp, array($name, $email, $title, $company), ';');
...


text:
Q: Geodatabase disappears I have an old ArcGIS 10.1 in my laptop. While I'm trying to create a geodatabase it gets created, but doesn't let me create new featureclass and/or feature dataset. I get the error:" failed to connect to database. bad login user."
Is there something I'm missing here?
I'm the admin on my laptop, and SQLExpress(V.2012), which has been installed by me. Though I don't know if I'm logging in as SQLEXPRESS' admin. I don't remember the credentials, I have definitely left it as default though.

This was long back, I think I gave up. Just then I installed and was working through instructions hence was not sure if everything got installed correctly.

A: I'm sure you've moved on since the question was asked but I wanted to pass along a doc on what might be happening here for users who land here.
Error:  Failed to connect to database. Bad login user. Success when creating a geodatabase using ArcSDE workgroup license.
The gist of it is there was a bug at 10.1 (NIM083155) where the SDE Workgroup license string was not being entered into the registry key.  When this failure occurs, the database is dropped.


text:
Q: Programmatically adding captions to Google+ image share in Android I have the following code in Android that programmatically adds a set of photos to a post that will be shared on Google+:
private void shareToGooglePlus() {
  // Launch the Google+ share dialog with attribution to your app.
  PlusShare.Builder share = new PlusShare.Builder(this);

  for (String imageFilename : imageList) {
    Uri imageUri = Uri.fromFile(new File(imageFilename));
    share.addStream(imageUri);
  }

  share.setText("My images");
  share.setType("image/jpeg");

  startActivityForResult(share.getIntent(), 0);
}

Since I have a bunch of different images, I would like to add captions to each to describe what is in each picture.  However, I can't seem to find a way to do that in with PlusShare.Builder.  Does anyone know if it is possible and how to do it?
Thanx in advance.

A: That can't be done with PlusShare - the text refers to the primary post only.


text:
Q: Is this even ubuntu grub menu? I'm trying to use Ubuntu 20.04 alongside windows 10 (both in different storage devices).
However I'm having this black screen since I have this Nvidia GTX 1650 SUPER, but I'm unable to configurate the nomodeset.
Each time I try to get to the grub menu, it brings me to this menu (that I'm not sure if this is the grub menu, since I found no image in the internet that looks like this one)

And there is also a code you can edit if you see where it says boot options, but also by pressing G6 you can see this.

The other problem is that when I'm in this menu, I can barely move between options or edit because when I press a key it do it like 5 times, and idk what to do to fix this.
Thanks for clearing my doubts about the CD/DVD/USB boot menu.
However, my real problem is with booting Ubuntu from the HDD.
This is everything I get each time:

UPDATE: I was able to boot from my HDD after using the repair boot with a Live USB Ubuntu.
For more information: http://ubuntuhandbook.org/index.php/2016/11/install-boot-repair-ppa-fix-boot-problems/

A: It looks like you booted to the USB. See if Ubuntu is at the top of your boot options. If it is, your boot loader must be broken.

A: This is the live usb/cd menu. If you have "tried ubuntu" and kliked it just click on install ubuntu.
Caveat : if windows is installed you might need to release some disk space first to allow ubuntu to install. UNLESS you go vanilla and wipe all discs and go ubuntu only.
You'll never look back...