text:
Q: hyperdrive effect in canvas across randomly placed circles I'm trying to create a hyperdrive effect, like from Star Wars, where the stars have a motion trail. I've gotten as far as creating the motion trail on a single circle, it still looks like the trail is going down in the y direction and not forwards or positive in the z direction.
Also, how could I do this with (many) randomly placed circles as if they were stars?
My code is on jsfiddle (https://jsfiddle.net/5m7x5zxu/) and below:
var canvas = document.querySelector("canvas");
var context = canvas.getContext("2d");

var xPos = 180;
var yPos = 100;

var motionTrailLength = 16;
var positions = [];

function storeLastPosition(xPos, yPos) {
  // push an item
  positions.push({
    x: xPos,
    y: yPos
  });

  //get rid of first item
  if (positions.length > motionTrailLength) {
    positions.pop();
  }
}
function update() {
  context.clearRect(0, 0, canvas.width, canvas.height);

  for (var i = positions.length-1; i > 0; i--) {
    var ratio = (i - 1) / positions.length;
    drawCircle(positions[i].x, positions[i].y, ratio);
  }

  drawCircle(xPos, yPos, "source");
 var k=2;
  storeLastPosition(xPos, yPos);

  // update position
  if (yPos > 125) {
    positions.pop();
  }
  else{
    yPos += k*1.1;
   }

  requestAnimationFrame(update);
}
update();

function drawCircle(x, y, r) {
  if (r == "source") {
    r = 1;
  } else {
    r*=1.1;
  }

  context.beginPath();
  context.arc(x, y, 3, 0, 2 * Math.PI, true);
  context.fillStyle = "rgba(255, 255, 255, " + parseFloat(1-r) + ")";
  context.fill();
}

A: Canvas feedback and particles.
This type of FX can be done many ways.
You could just use a particle systems and draw stars (as lines) moving away from a central point, as the speed increase you increase the line length. When at low speed the line becomes a circle if you set ctx.lineWidth > 1 and ctx.lineCap = "round"
To add to the FX you can use render feedback as I think you have done by rendering the canvas over its self. If you render it slightly larger you get a zoom FX. If you use ctx.globalCompositeOperation = "lighter" you can increase the stars intensity as you speed up to make up for the overall loss of brightness as stars move faster.
Example
I got carried away so you will have to sift through the code to find what you need.
The particle system uses the Point object and a special array called bubbleArray to stop GC hits from janking the animation.
You can use just an ordinary array if you want. The particles are independent of the bubble array. When they have moved outside the screen they are move to a pool and used again when a new particle is needed. The update function moves them and the draw Function draws them I guess LOL
The function loop is the main loop and adds and draws particles (I have set the particle count to 400 but should handle many more)
The hyper drive is operated via the mouse button. Press for on, let go for off. (It will distort the text if it's being displayed)
The canvas feedback is set via that hyperSpeed variable, the math is a little complex. The sCurce function just limits the value to 0,1 in this case to stop alpha from going over or under 1,0. The hyperZero is just the sCurve return for 1 which is the hyper drives slowest speed.
I have pushed the feedback very close to the limit. In the first few lines of the loop function you can set the top speed if(mouse.button){ if(hyperSpeed < 1.75){ Over this value 1.75 and you will start to get bad FX, at about 2 the whole screen will just go white (I think that was where)
Just play with it and if you have questions ask in the comments.

const ctx = canvas.getContext("2d");

// very simple mouse
const mouse  = {x : 0, y : 0, button : false}
function mouseEvents(e){
 mouse.x = e.pageX;
 mouse.y = e.pageY;
 mouse.button = e.type === "mousedown" ? true : e.type === "mouseup" ? false : mouse.button;
}
["down","up","move"].forEach(name => document.addEventListener("mouse"+name,mouseEvents));

// High performance array pool using buubleArray to separate pool objects and active object.
// This is designed to eliminate GC hits involved with particle systems and
// objects that have short lifetimes but used often.
// Warning this code is not well tested.
const bubbleArray = () => {
    const items = [];
    var count = 0;
    return {
        clear(){  // warning this dereferences all locally held references and can incur Big GC hit. Use it wisely.
            this.items.length = 0;
            count = 0;
        },
        update() {
            var head, tail;
            head = tail = 0;
            while(head < count){
                if(items[head].update() === false) {head += 1 }
                else{
                    if(tail < head){
                        const temp = items[head];
                        items[head] = items[tail];
                        items[tail] = temp;
                    }
                    head += 1;
                    tail += 1;
                }
            }
            return count = tail;
        },
        createCallFunction(name, earlyExit = false){
            name = name.split(" ")[0];
            const keys = Object.keys(this);
            if(Object.keys(this).indexOf(name) > -1){  throw new Error(`Can not create function name '${name}' as it already exists.`) }
            if(!/\W/g.test(name)){
                let func;
                if(earlyExit){
                    func = `var items = this.items; var count = this.getCount(); var i = 0;\nwhile(i < count){ if (items[i++].${name}() === true) { break } }`;
                }else{
                    func = `var items = this.items; var count = this.getCount(); var i = 0;\nwhile(i < count){ items[i++].${name}() }`;
                }
                !this.items && (this.items = items);
                this[name] = new Function(func);
            }else{  throw new Error(`Function name '${name}' contains illegal characters. Use alpha numeric characters.`) }

        },
        callEach(name){var i = 0; while(i < count){ if (items[i++][name]() === true) { break } } },
        each(cb) { var i = 0; while(i < count){ if (cb(items[i], i++) === true) { break } } },
        next() { if (count < items.length) { return items[count ++] } },
        add(item) {
            if(count === items.length){
                items.push(item);
                count ++;
            }else{
                items.push(items[count]);
                items[count++] = item;
            }
            return item;
        },
        getCount() { return count },
    }
}

// Helpers rand float, randI random Int
// doFor iterator
// sCurve curve input -Infinity to Infinity out -1 to 1
// randHSLA creates random colour
// CImage, CImageCtx create image and image with context attached
const randI = (min, max = min + (min = 0)) => (Math.random() * (max - min) + min) | 0;
const rand  = (min = 1, max = min + (min = 0)) => Math.random() * (max - min) + min;
const doFor = (count, cb) => { var i = 0; while (i < count && cb(i++) !== true); }; // the ; after while loop is important don't remove

const sCurve = (v,p) => (2 / (1 + Math.pow(p,-v))) -1;
const randHSLA = (h, h1, s = 100, s1 = 100, l = 50, l1 = 50, a = 1, a1 = 1) => { return `hsla(${randI(h,h1) % 360},${randI(s,s1)}%,${randI(l,l1)}%,${rand(a,a1)})` }
const CImage = (w = 128, h = w) => (c = document.createElement("canvas"),c.width = w,c.height = h, c);
const CImageCtx = (w = 128, h = w) => (c = CImage(w,h), c.ctx = c.getContext("2d"), c);

// create image to hold text
var textImage = CImageCtx(1024, 1024);
var c = textImage.ctx;
c.fillStyle = "#FF0";
c.font = "64px arial black";
c.textAlign = "center";
c.textBaseline = "middle";
const text = "HYPER,SPEED FX,VII,,Battle of Jank,,Hold the mouse,button to increase,speed.".split(",");
text.forEach((line,i) => { c.fillText(line,512,i * 68 + 68) });
const maxLines = text.length * 68 + 68;
function starWarIntro(image,x1,y1,x2,y2,pos){
  var iw = image.width;
  var ih = image.height;
  var hh = (x2 - x1) / (y2 - y1);      // Slope of left edge
  var w2 = iw / 2;                      // half width
  var z1 = w2 - x1;                    // Distance (z) to first line
  var z2 = (z1 / (w2 - x2)) * z1 - z1; // distance (z) between first and last line
  var sk,t3,t3a,z3a,lines, z3, dd = 0, a = 0, as = 2 / (y2 - y1);
  for (var y = y1; y < y2 && dd < maxLines; y++) {      // for each line

      t3 = ((y - y1) * hh) + x1;       // get scan line top left edge
      t3a = (((y+1) - y1) * hh) + x1;  // get scan line bottom left edge
      z3 = (z1 / (w2 - t3)) * z1;      // get Z distance to top of this line
      z3a = (z1 / (w2 - t3a)) * z1;      // get Z distance to bottom of this line
      dd = ((z3 - z1) / z2) * ih;       // get y bitmap coord
      a += as;

      ctx.globalAlpha = a < 1 ? a : 1;
      dd += pos;                         // kludge for this answer to make text move
                                         // does not move text correctly
      lines = ((z3a - z1) / z2) * ih-dd;       // get number of lines to copy
      ctx.drawImage(image, 0, dd , iw, lines, t3, y, w - t3 * 2, 1.5);
  }
}

// canvas settings
var w = canvas.width;
var h = canvas.height;
var cw = w / 2;  // center
var ch = h / 2;
// diagonal distance used to set point alpha (see point update)
var diag = Math.sqrt(w * w + h * h);
// If window size is changed this is called to resize the canvas
// It is not called via the resize event as that can fire to often and
// debounce makes it feel sluggish so is called from main loop.
function resizeCanvas(){
  points.clear();
  canvas.width = innerWidth;
  canvas.height = innerHeight;
  w = canvas.width;
  h = canvas.height;
  cw = w / 2;  // center
  ch = h / 2;
  diag = Math.sqrt(w * w + h * h);

}
// create array of points
const points = bubbleArray();
// create optimised draw function itterator
points.createCallFunction("draw",false);
// spawns a new star
function spawnPoint(pos){
    var p = points.next();
    p = points.add(new  Point())
    if (p === undefined) { p = points.add(new  Point()) }
    p.reset(pos);
}
// point object represents a single star
function Point(pos){  // this function is duplicated as reset
    if(pos){
        this.x = pos.x;
        this.y = pos.y;
        this.dead = false;
    }else{
        this.x = 0;
        this.y = 0;
        this.dead = true;
    }
    this.alpha = 0;
    var x = this.x - cw;
    var y = this.y - ch;
    this.dir = Math.atan2(y,x);
    this.distStart = Math.sqrt(x * x + y * y);
    this.speed = rand(0.01,1);
    this.col = randHSLA(220,280,100,100,50,100);
    this.dx = Math.cos(this.dir) * this.speed;
    this.dy = Math.sin(this.dir) * this.speed;
}
Point.prototype = {
    reset : Point,  // resets the point
    update(){       // moves point and returns false when outside
        this.speed *= hyperSpeed;  // increase speed the more it has moved
        this.x += Math.cos(this.dir) * this.speed;
        this.y += Math.sin(this.dir) * this.speed;
        var x = this.x - cw;
        var y = this.y - ch;
        this.alpha = (Math.sqrt(x * x + y * y) - this.distStart) / (diag * 0.5 - this.distStart);
        if(this.alpha > 1 || this.x < 0 || this.y < 0 || this.x > w || this.h > h){
           this.dead = true;
        }
        return !this.dead;
    },
    draw(){  // draws the point
        ctx.strokeStyle = this.col;
        ctx.globalAlpha = 0.25 + this.alpha *0.75;
        ctx.beginPath();
        ctx.lineTo(this.x - this.dx * this.speed, this.y - this.dy * this.speed);
        ctx.lineTo(this.x, this.y);
        ctx.stroke();

    }
}

const maxStarCount = 400;
const p = {x : 0, y : 0};
var hyperSpeed = 1.001;
const alphaZero = sCurve(1,2);
var startTime;
function loop(time){

    if(startTime === undefined){
        startTime = time;
    }
    if(w !== innerWidth || h !== innerHeight){
       resizeCanvas();
    }
    // if mouse down then go to hyper speed
    if(mouse.button){
        if(hyperSpeed < 1.75){
            hyperSpeed += 0.01;
        }
    }else{
        if(hyperSpeed > 1.01){
            hyperSpeed -= 0.01;
        }else if(hyperSpeed > 1.001){
            hyperSpeed -= 0.001;
        }
    }

    var hs = sCurve(hyperSpeed,2);
    ctx.globalAlpha = 1;
    ctx.setTransform(1,0,0,1,0,0); // reset transform

    //==============================================================
    // UPDATE the line below could be the problem. Remove it and try
    // what is under that
    //==============================================================
    //ctx.fillStyle = `rgba(0,0,0,${1-(hs-alphaZero)*2})`;

    // next two lines are the replacement
    ctx.fillStyle = "Black";
    ctx.globalAlpha = 1-(hs-alphaZero) * 2;
    //==============================================================

    ctx.fillRect(0,0,w,h);
    // the amount to expand canvas feedback
    var sx = (hyperSpeed-1) * cw * 0.1;
    var sy = (hyperSpeed-1) * ch * 0.1;

    // increase alpha as speed increases
    ctx.globalAlpha = (hs-alphaZero)*2;
    ctx.globalCompositeOperation = "lighter";
    // draws feedback twice
    ctx.drawImage(canvas,-sx, -sy, w + sx*2 , h + sy*2)
    ctx.drawImage(canvas,-sx/2, -sy/2, w + sx , h + sy)
    ctx.globalCompositeOperation = "source-over";

    // add stars if count < maxStarCount
    if(points.getCount() < maxStarCount){
        var cent = (hyperSpeed - 1) *0.5; // pulls stars to center as speed increases
        doFor(10,()=>{
            p.x = rand(cw * cent ,w - cw * cent);  // random screen position
            p.y = rand(ch * cent,h - ch * cent);
            spawnPoint(p)

        })
    }
    // as speed increases make lines thicker
    ctx.lineWidth = 2 + hs*2;
    ctx.lineCap = "round";
    points.update();  // update points
    points.draw();     // draw points
    ctx.globalAlpha = 1;

    // scroll the perspective star wars text FX
    var scrollTime = (time - startTime) / 5 - 2312;
    if(scrollTime < 1024){
        starWarIntro(textImage,cw - h * 0.5, h * 0.2, cw - h * 3, h , scrollTime );
    }
 requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
canvas { position : absolute; top : 0px; left : 0px; }
<canvas id="canvas"></canvas>

A: Here's another simple example, based mainly on the same idea as Blindman67, concetric lines moving away from center at different velocities (the farther from center, the faster it moves..) also no recycling pool here.

 "use strict"
var c = document.createElement("canvas");
document.body.append(c);
var ctx = c.getContext("2d");
var w = window.innerWidth;
var h = window.innerHeight;
var ox = w / 2;
var oy = h / 2;
c.width = w; c.height = h;

const stars = 120;
const speed = 0.5;
const trailLength = 90;

ctx.fillStyle = "#000";
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = "#fff"
ctx.fillRect(ox, oy, 1, 1);

init();

function init() {
 var X = [];
 var Y = [];
 for(var i = 0; i < stars; i++) {
  var x = Math.random() * w;
  var y = Math.random() * h;
  X.push( translateX(x) );
  Y.push( translateY(y) );
 }
 drawTrails(X, Y)
}

function translateX(x) {
 return x - ox;
}

function translateY(y) {
 return oy - y;
}

function getDistance(x, y) {
 return Math.sqrt(x * x + y * y);
}

function getLineEquation(x, y) {
 return function(n) {
   return y / x * n;
  }
}

function drawTrails(X, Y) {
 var count = 1;
 ctx.fillStyle = "#000";
 ctx.fillRect(0, 0, w, h);
 function anim() {
  for(var i = 0; i < X.length; i++) {
   var x = X[i];
   var y = Y[i];
   drawNextPoint(x, y, count);
  }
  count+= speed;
  if(count < trailLength) {
   window.requestAnimationFrame(anim);
  }
  else {
   init();
  }
 }
 anim();
}

function drawNextPoint(x, y, step) {
 ctx.fillStyle = "#fff";
 var f = getLineEquation(x, y);
 var coef = Math.abs(x) / 100;
 var dist = getDistance( x, y);
 var sp = speed * dist / 100;
 for(var i = 0; i < sp; i++) {
  var newX = x + Math.sign(x) * (step + i) * coef;
  var newY = translateY( f(newX) );
  ctx.fillRect(newX + ox, newY, 1, 1);
 }

}
body {
 overflow: hidden;
}

canvas {
 position: absolute;
 left: 0;
 top: 0;
}


text:
Q: Create new matrix with ranks of elements of other matrix, MATLAB I have a matrix for example
A = [21 3 14;0 1 5;8 2 4]

and want a new matrix
B =[9 4 8;1 2 6;7 3 5]

I found a method for creating a vector
http://blogs.mathworks.com/loren/2007/08/21/reversal-of-a-sort/#7
but is there a function for matrix?
Thanks

A: Similar to abhineetprasad's solution, but you don't need a key–value structure.
You can use almost the same method for matrices as for vectors. You just need to determine the sort indices for A with respect to the vector-shaped version A(:) and initialize B to the same dimensions as A. Then you can use linear indexing into the matrix B to fill it with the ranks:
% prepare matrix B with the same dimensions as A
B = zeros(size(A));
% determine sort indices of the matrix entries treated as a vector
[~, ind] = sort(A(:));
% use linear indexing by sort indices to fill vector B with ranks
B(ind) = 1 : numel(B);

A: A possible way of doing this would be:

*

*Read the matrix into a vector.

*Use the link you've found to sort the vector.

*Store the vector as Map with vector value as the "key" and vector index as the value.

*Populate the new matrix by looking up the index of the numbers as you read the first matrix again using the map.

redpajama_set_name: RedPajamaStackExchange


text:
Q: A variation to the phrase "hanging over my shoulders" I couldn't find the exact definition of "hanging over someone's shoulders" online. I am not referring to the literal meaning, when, for example, you feel there is a ghost hanging over your shoulders.
How would you explain the idiom "hanging over someone's shoulders", and are there any other variations to the phrase?

A: It depends somewhat on the thing that is hanging over your shoulders, and how it is affecting you.
If you feel that you are being observed constantly, then someone or something is looking over your shoulder:

I can't concentrate with you looking over my shoulder all the time!

If you are uneasy because of some pressure or responsibility being placed upon you, there are a few phrases that would work:

I'm always stressed because of all the work that's been put on my shoulders.
I'd like to go out tonight, but I have an important deadline hanging over my head.

If something is irritating you because of its constant presence, you could say that it's on my back:

My boss is always on my back about getting these reports done.

If you can just barely sense the presence of something or someone, they might be lurking.

There were ghosts lurking in every corner, just out of sight.

A: fall/rest on someone's shoulders means to be someone's responsibility.

All the work of cleaning fell on my shoulders.

But by extension hang can also be used in place of fall/rest.

A: I hear it in the singular, not plural. "Hanging over one's shoulder." When Tom (for example) is hanging over Steve's shoulder, Tom is looking at what Steve is looking at. The implication is that Steve does NOT want this; "hanging over one's shoulder" is usually a negative comment. "Tom, please stop hanging over my shoulder."


text:
Q: jquery update breaks jquery update breaks when jquery, itself update input value!!
i have some input boxes and i wrote some jquery functions like this:
$(document).ready(function() {
   $('#ind2').change( function() {
       $('#ind5').val( parseInt($('#ind2').val()) + parseInt($('#ind1').val())    );
 });
});

 $(document).ready(function() {
       $('#ind5').change( function() {
           $('#ind1').val( parseInt($('#ind7').val()) + parseInt($('#ind5').val())    );
     });
    });

when input "ind2" changes input "ind5" will change so i need second function " $('#ind5').change" call automatically !! but "$('#ind5').change" just calls when user change input "ind5" strightly!!
what must i do?!

A: trigger  the change on #ind5 using trigger
$(document).ready(function() {
   $('#ind2').change( function() {
       $('#ind5').val( parseInt($('#ind2').val()) + parseInt($('#ind1').val())    );
       $("#ind5").trigger('change');
 });
});

A: well, not judging the functionallity of your script (which seems very flawd), you would need to check if the value is the combination of the others and vice verca;
$(document).ready(function() {
   $('#ind5').change( function() {
       if (this.value!==(parseInt($('#ind2').val()) + parseInt($('#ind1').val())){
           $('#ind1').val( parseInt($('#ind7').val()) + parseInt($('#ind5').val())    );
       }
 });
});


text:
Q: Auto-flushing Play! logs into logs/system.out I noticed that Play! logs don't always flush immediately after calling log4j's logger.log().
I created a log4j.properties file in the conf folder, set the root logger to INFO, and am using log4j for printing logs.
I have one action that always emits a log message, yet I need to call it twice before I see anything in the log file - and after I call it twice I see two log lines.
The conclusion is that output redirection into logs/system.out is not automatically flushed.
Is there a configuration that will make Play! auto-flush the logs after each write?

A: Play logger doesn't cache anything. So it's a problem of log4j. If you use a file logger you can define the buffer-size and force log4j to write directly.


text:
Q: Count characters in a pandas column is there a way to explicitly count characters in a pandas column for Strings and group them by their respective word?
df["text"]=[["Hello how are you?"],["I am fine"]]
Then the counter should be
df["count"]= [[0-4 6-8 10-12 14-16 17],[0 2-3 5-8]]

A: As far as I know there is no pandas functionality for what you ask, but you can do:
import re
import pandas as pd

# setup
df = pd.DataFrame(data=[["Hello how are you?"], ["I am fine"]], columns=['text'])

def extract_spans(m):
    """Convert span to required string representation"""
    start, end = m.span()
    return f'{start}-{end - 1}' if end - start > 1 else f'{start}'

# create count column
df['count'] = [' '.join([extract_spans(m) for m in re.finditer(r'([^\w\s_]|\w+)', v)]) for v in df['text'].tolist()]
print(df)

Output
                 text                   count
0  Hello how are you?  0-4 6-8 10-12 14-16 17
1           I am fine               0 2-3 5-8


text:
Q: how to make a logical exclusion within the query? I have 3 tables in our ERP database holding all delivery data (table documents holds one row for each delivery note, documentpos holds all positions on delivery notes, documentserialnumbers holds all serial numbers for delivered items).
I want to show all items with their serial number that have been delivered to the customer and still resides there so far.
The above shown output of the following query however shows, that one item that has been delivered was returned (red marks) later. The return delivery note has the document number 527419 (dark red mark) and refers to the the delivery note 319821 (green) which is listed yellow.
The correct list would consequential show only items that are still on customer's site without the returned items (see below).
How do I have to change the query in order to exclude the returned items from the output?
The upper table shows in the image shows the output of my query, the table below how it should be.
select a.BelID, c.ReferenzBelID, a.itemnumber, a.itemname, c.deliverynotenumber,c.documenttype, c.documentmark, b.serialnumber
from dbo.documentpos a
inner join dbo.documentserialnumbers b on a.BelPosID = b.BelPosID
inner join dbo.documents c on a.BelID = c.BelID
inner join sysdba.customers d on d.account = c.A0Name1
where  d.AccountID = 'customername' and c.documenttype like '%delivery%'
order by a.BelID

A: You may exclude positions, which are referenced by any "return" delivery note, like this (edited)
select a.BelID, c.ReferenzBelID, a.itemnumber, a.itemname, c.deliverynotenumber,c.documenttype, c.documentmark, b.serialnumber
from dbo.documentpos a
inner join dbo.documentserialnumbers b on a.BelPosID = b.BelPosID
inner join dbo.documents c on a.BelID = c.BelID
inner join sysdba.customers d on d.account = c.A0Name1
where  d.AccountID = 'customername' and c.documenttype like '%delivery%'
and not exists (select 1
                from dbo.documents cc
                where cc.documenttype like '%delivery%'
                and c.ReferenzBelID=cc.BelID
                and c.documentmark='VLR')
and not exists (select 1
                from dbo.documents ccc
                join dbo.documentpos aa on aa.BelID = ccc.BelID
                where ccc.ReferenzBelID=c.BelID
                and ccc.documentmark='VLR'
                and a.itemnumber=aa.itemnumber)
order by a.BelID


text:
Q: Packaging a Bundle with a static library I have a static library that includes some xibs.  These will basically be the same across projects.  I'd like to include the xibs as part of the library.  I can include their veiwcontrollers, reference these controllers in the calling project but then there isn't a xib to load.  When I right click the xib in the library project, it can't be part of the target.
I thought about creating a CFPluginBundle but that creates a new project. I'd loose all of my IBOutlet and IBAction references.  What is the best way to reuse xibs that also have outlets and actions to specific controllers?

A: Here more discussion about it: Can you reference Xib files from static libraries on the iPhone?

A: I had the same problem when I wanted to export my project as a library for other developers to use.
I found the perfect solution to my view and it seems it will answer yours too.
There is an xcode plugin that allows you to build your project as a library which includes the resources as well.
https://github.com/kstenerud/iOS-Universal-Framework
I do not know the guys that built this plugin, but it works like a charm

A: I'm not sure what you mean by "include the xibs as part of the library", since static libraries can't have resources--but they also aren't shipped stand-alone, so they don't need to. If you just want code re-use for your own projects, you could keep the xibs where-ever you keep the static library, and just include the xibs in any project that uses the library.
If you go the CFPluginBundle route, you can make new bundle targets in an existing project; there's nothing magic about the templates, they just take care of making dummy files and turning on the right build settings. You can copy those into a new target in your existing project and it will work just fine. That said, I'm not sure what you mean about losing IBOutlet and IBAction references, since that information is part of the xib (and the class you are using in the xib), not the project.


text:
Q: Setting background image to dropbox file doesn't update background Im trying to have my desktop background be an image stored on my dropbox account. My dropbox folder is linked in my home directory. When i set the background to this photo and then change the photo the background doesn't follow. I know the file has changed by opening in Finder.
If I reboot the machine the image changes so it must be cached somewhere?

A: You're right, it is cached. So if you want to change the desktop image, you'll need to change the db file. In Yosemite, that is ~/Library/Application\ Support/Dock/desktoppicture.db
And here's a way to change it using the Terminal:
sqlite3 ~/Library/Application\ Support/Dock/desktoppicture.db "update data set value = '/path/to/your/image.jpg'" && killall Dock

So, if you want to run that after a file have changed (such as modyfing it through dropbox) you could use a file watcher script, such as this Ruby one.

A: The previous method works, but there also is another (a little bit brutal) way.
You need LaunchAgent to monitor the file that is changing and execute an action when it is changed.
Save the following to a file in ~/Library/LaunchAgents/, you can use as filename 'com.yourname.programname.plist'). Replace /full/path/to/desktoppicture
 with the full path to the picture in your Dropbox folder.
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>com.yourname.programname</string>
        <key>Program</key>
        <string>/usr/bin/killall</string>
        <key>ProgramArguments</key>
        <array>
            <string>killall</string>
            <string>Dock</string>
        </array>
        <key>WatchPaths</key>
        <array>
            <string>/full/path/to/your/desktoppicture</string>
        </array>
    </dict>
    </plist>

After you modified and saved the property list, open the Terminal and type:
launchctl load -w ~/Library/LaunchAgents/com.yourname.programname.plist

(replacing yourname.programname with whatever you called the plist file).
At this point, any time that the file is changed, killall Dock will be executed, quitting the Dock app and forcing a Desktop refresh. This is a bit brutal, and could be annoying since the Dock/Desktop refresh takes ~1 second and while it does you cannot use Mission Control and Dashboard, but it should be automatic.
In case you want to uninstall the LaunchAgent, first type:
launchctl unload -w ~/Library/LaunchAgents/com.yourname.programname.plist

(again, renaming the file to match yours), and then remove the plist file from ~/LaunchAgents/


text:
Q: Hide tableview header that contains a search bar under navbar? I have a search bar in the tableview header. I want to offset the position of the search bar that it looks hidden under the nav bar until the user pulls down on the tableview to reveal a search bar.  I have looked everywhere to find this but cannot.  Can someone please point me in the right direction and or show me how do create this effect in iOS 9 and objective-c.  Thank you

A: // search is hidden in TableView by default
For swift
self.TableView.setContentOffset(CGPointMake(0,self.searchController.searchBar.frame.size.height), animated: false)

For Objective c
[[self staffTableView] setContentOffset:[CGPointMake(0, frameHeight)] animated:YES];

When you pullDown it will reveal you searchbar(added in the headerview)
Hope this will help you to solve your problem. it was working for me.

A: Swift 3:
let point = CGPoint(x: 0, y:(self.navigationController?.navigationBar.frame.size.height)!)

self.tableView.setContentOffset(point, animated: true)

This is for regular navigation bar. For search controller:
 Replace navigationController and navigationBar with karthik's y coordinate.


text:
Q: How can I draw the complex number $z_1 = 2e^{{\pi\over6}i -1}$ I'm not sure how to draw the following number in the complex plane:
$$z_1 = 2e^{({\pi\over6}i -1)}$$
My guess would be that you seperate the exponents:
$$z_1 = 2e^{({\pi\over6}i)} e^{-1}$$
To get:
$$z_1 = \frac{\sqrt 3}{e} + \frac{1}{e}i$$
So $ \operatorname{Re}(z_1) =\frac{\sqrt 3}{e}$ and $ \operatorname{Im}(z_1) =\frac{1}{e}$.
Is this correct? This is part of a previous exam question, but my teacher doesn't provide any answers.

A: This is correct.  You get the complex number $z$  with modulus $\frac2e$ and argument $\frac{\pi}6$.


text:
Q: Why is $\frac{p(1-p)}{1−(1−p)^2}=\frac{1-p}{2-p}$? I found this solution in an old exam:

$$\frac{p(1-p)}{1−(1−p)^2}=\frac{1-p}{2-p}$$

Without any further explanation. Could someone explain to me how to do this transition?

A: You have two basic options to solve this.

First off, you can just write out the denominator to get $$1-(1-p)^2=1-(1-2p+p^2) = -p^2 +2p = p(2-p)$$
and then cancel out the $p$ top and bottom.

Or, you can "cleverly" see that $1-(1-p)^2 = 1^2-(1-p)^2$ and use the equality $$a^2-b^2 = (a-b)(a+b)$$
to get basically the same thing, since
$$1-(1-p)^2 = (1-(1-p))(1+(1-p)) = p(2-p)$$

A: By inspection (or by $(1-p)^2=1$), $p=0$ and $p=2$ are roots of the denominator. As the coefficient of the highest power is $-1$, it factors as $p(2-p)$. The rest is up to you.

A: hint: it is $$1-(1-p)^2=(1-(1-p))(1+1-p)$$

A: \begin{align}
\frac{p(1-p)}{1−(1−p)^2}&=\frac{p(1-p)}{(1+1-p)(1-1+p)}\\
&=\frac{p(1-p)}{p(2-p)}\\
&=\frac{1-p}{2-p}.
\end{align}

A: Perhaps one should say that $p=0$ and $p=2$ are excluded, because then not both terms are defined. For example,
$$
\frac{p(1-p)}{1−(1−p)^2}=\frac{0}{0}\neq \frac{1}{2}= \frac{1-p}{2-p}.
$$
For $p\neq 0,2$ however, both terms are defined and we can cancel, i.e.,
$$
\frac{p(1-p)}{1−(1−p)^2}=\frac{p(1-p)}{p(2-p)}=\frac{1-p}{2-p}.
$$


text:
Q: How can I restore a postgresql dump to a SQL Server instance? I've got a production app running on Postgres, and I'm taking nightly dumps to a tar.gz file.  I'd like to restore this dump to a separate SQL Server database instance.  Are there any direct (or indirect) ways to do this in an automated fashion?

A: If all you wanted to do is replay the DML statements that may work just fine assuming you have the tables in the target in place. But if you want the script to create tables and the other objects the vast majority of those statements will fail without you manually going in and updating them to work on SQL Server.  You may find some company that has a tool that tries to do this and in some cases they can be ok for all the easy conversions but will fail on all the complicated stuff.  Overall SQL Server and PostgreSQL are two different beasts when you get into the details so doing this automatically will be hard without writing some conversion tool or trying to buy one that will probably only get you 60 to 80 percent were you want..

A: Yes, you can create a DTS job to import from the dump on timely basis.
http://msdn.microsoft.com/en-us/library/cc917688.aspx


text:
Q: Apply "Has a" method and remove inheritance class A {
    class B {
        public:
        void doSomething();
    };
    class C : public B {};
    class D : public B {};

};

// In B.hpp file
class hello {
    class hi {};
    class world : public hi, public C {};
};

// In main.cpp file
int main() {
    world my_world;
    my_world.doSomething();
}

In this code, I want to remove the inheritance between class B and class C. When I instantiate class world, I should still be able to access doSomthing() method from class world.
Is there a way to implement "Has a" method which is as per my understanding a pointer to the base class?

A: As I mentioned in a comment, the code proposed in the question is incorrect as written. Class members default to being private, so you need to explicitly mark them as public if you want to be able to access them from outside of that class's context. Furthermore, you are missing some scope resolution operators and at least one semicolon. This is the corrected version of your current code. I've also added some code so that the doSomething function has an observable effect—i.e., so that it actually does something.
class A
{
public:
    class B
    {
    public:
        void doSomething() { std::cout << "Hello, world!\n"; };
    };

    class C : public B
    { };

    class D : public B
    { };
};

class hello
{
public:
    class hi
    { };

    class world : public hi, public A::C
    { };
};

int main()
{
    hello::world my_world;
    my_world.doSomething();
}

Inheritance means "is-a", whereas composition means "has-a". What you have now (as shown above) is inheritance, so you're modeling "is-a". If you want "has-a" instead,  So, you want composition. Simply change C to have a member of type B:
class A
{
public:
    class B
    {
    public:
        void doSomething() { std::cout << "Hello, world!\n"; };
    };

    class C
    {
    public:
        B b;
    };

    class D : public B
    { };
};

class hello
{
public:
    class hi
    { };

    class world : public hi, public A::C
    { };
};

int main()
{
    hello::world my_world;
    my_world.b.doSomething();
}

Now, in this code, C has a B. It is named b (but you could name it whatever you wanted).
If you don't want to require that doSomething be accessed from the b member, then you'll need to write a wrapper function. That would even allow you to keep the b member private.
#include <iostream>

class A
{
public:
    class B
    {
    public:
        void doSomething() { std::cout << "Hello, world!\n"; };
    };

    class C
    {
        B b;

    public:
        void doSomething() { b.doSomething(); }
    };

    class D : public B
    { };
};

class hello
{
public:
    class hi
    { };

    class world : public hi, public A::C
    { };
};

int main()
{
    hello::world my_world;
    my_world.doSomething();
}


text:
Q: How do I undo ggplot data error code to plot data? I keep getting the same error when I enter this code:
ggplot(exchangeGBP) + aes(Date, GBP/EUR) + geom_line(color = "deepskyblue")

the error code: Error in FUN(X[[i]], ...) : object 'Date' not found
should I install a package or change the code?

A: The + before aes seems to be the issue
library(ggplot2)
ggplot(exchangeGBP, aes(Date, `GBP/EUR`)) +
         geom_line(color = 'deepskyblue') +
         theme_bw()

data
set.seed(24)
exchangeGBP <- tibble(Date = seq(Sys.Date() - 10,
      length.out = 10, by = '1 day'), `GBP/EUR` = rnorm(10))


text:
Q: unable to compile a lambda expression because the type isn't delegate I'm trying to use lambda expression in C#:
using System;

namespace ConsoleApplication1 {
   public struct Point {
      public int x;
      public int y;

      public Point( int x, int y ) {
         this.x = x;
         this.y = y;
      }
   }

   public interface Mobile {
      Point getPosition();
   }

   public class Program {
      public void mth( Mobile mobile ) {
         Point p = mobile.getPosition();
         Console.WriteLine( "{ " + p.x + ", " + p.y + " }" );
      }

      static void Main( string[] args ) {
         new Program().mth( () => { return new Point( 4, 5 ); } ); <<<<<<<< ERROR
      }
   }
}

Compiler error (in French):

Impossible de convertir expression lambda en type
  'ConsoleApplication1.Mobile', car il ne s'agit pas d'un type délégué

International English Translation:

Unable to convert lambda expression to type
  'ConsoleApplication1.Mobile', because isn't a delegate type

What's the right syntax?

A: You appear to be confusing an interface and a delegate.
An interface is, roughly speaking, a collection of one or more methods. It has to be implemented by a class that provides implementations for each method; you can't build an implementation up from lambda methods.
A delegate is basically a named method signature. You can convert a lambda method to a delegate as long as the signature is correct, or you can create a delegate pointing at a method on a class, say.
I think what you're after to make your code work is to turn your Mobile into a delegate:
// This can represent any function that takes nothing and returns a point.
public delegate Point Mobile();

public class Program {

    // This takes any "Mobile" function, calls it and displays the result.
    public void mth(Mobile getPosition) {
        Point p = getPosition();
        Console.WriteLine("{ " + p.x + ", " + p.y + " }");
    }

    // This calls mth with a lambda that matches the "Mobile" definition.
    static void Main( string[] args ) {
        new Program().mth(() => { return new Point( 4, 5 ); });
    }

    // You could also explicitly create a "Mobile".
    static void Main2( string[] args ) {
        Mobile myMobile = new Mobile(() => { return new Point( 4, 5 ); });
        new Program().mth(myMobile);
    }
}

A:    public class Mobile {
      public Func<Point> GetPosition { get; set; }
   }

   public class Program {
      public void mth( Mobile mobile ) {
         Point p = mobile.GetPosition();
         Console.WriteLine( "{ " + p.x + ", " + p.y + " }" );
      }

      static void Main( string[] args ) {
         new Program().mth( new Mobile { GetPosition = () => { return new Point( 4, 5 ); } } );
      }
   }


text:
Q: Eliminate ${\theta, \varphi}$ from $\tan\theta+\tan\varphi=a$, $\sec\theta+\sec\varphi=b$, $\csc\theta+\csc\varphi=c$ Here is the problem:
Eliminate $\theta, \varphi$ from the equations
$$\tan\theta+\tan\varphi=a$$
$$\sec\theta+\sec\varphi=b$$
$$\csc\theta+\csc\varphi=c$$
What I have so far.
$$\tan \theta=a-\tan\varphi$$
$$\sec \theta=b-\sec\varphi$$
$$\csc \theta=c-\csc\varphi$$
And using
$$\tan \theta \csc\theta =\sec\theta$$ gives us
$$c\tan\varphi+a\csc\varphi-2\sec \varphi=ac-b$$
And also
$$\tan^2\theta+1=\sec^2\theta$$
gives
$$2a\tan\varphi-2b\sec\varphi=a^2-b^2$$
Thus we have two linear relations. But I cannot think of any more properties to use. Things like $\sin^2+\cos^2=1$ give a big mess. So what are the end steps ?
Update: The method used in this question: How to eliminate $\theta$ & $\phi$ from above equations
will work and solves the problem.
Following that method gives me
$$[(b^2-a^2)^2+4a^2]a^2c=4a^2[c(a^2+b^2)-2ab]$$
What a fantastic relation !

A: In the meantime I have found an answer. By request I post it here.
Thanks to @AakashM for pointing out some mistakes in the solution, now corrected.
Write the equations as
$$\sin\theta\cos\varphi+\sin\varphi\cos\theta=
a\cos\theta\cos\varphi$$
$$\cos\theta+\cos\varphi=b\cos\theta\cos\varphi$$
$$\sin\theta+\sin\varphi=c\sin\theta\sin\varphi$$
Now define
$$\alpha=\frac{\theta+\varphi}{2}, \beta=\frac{\theta-\varphi}{2}$$
and so
$$4\sin\alpha\cos\alpha=a(\cos2\beta+\cos2\alpha)$$
$$4\cos\alpha\cos\beta=b(\cos2\beta+\cos2\alpha)$$
$$4\sin\alpha\cos\beta=c(\cos2\beta-\cos2\alpha)$$
Dividing the first and second,
$$\frac{\sin\alpha}{\cos\beta}=\frac{a}{b}$$
so
$$b\sin\alpha=a\cos\beta$$
Further subtracting the first and second,
$$4\cos\alpha(\sin\alpha-\cos\beta)=(a-b)
(\cos2\beta+\cos2\alpha)$$
$$2\cos\alpha(\sin\alpha-\cos\beta)=(a-b)
(\cos^2\beta-\sin^2\alpha)$$
$$2\cos\alpha(\sin\alpha-\cos\beta)=(a-b)
(\cos\beta-\sin\alpha)(\cos\beta+\sin\alpha)$$
So cancelling $\sin\alpha-\cos\beta$
we get
$$2\cos\alpha=(b-a)
(\cos\beta+\sin\alpha)$$
Now multiply by $a$ and convert the $\cos\beta$ to $\sin\alpha$ using the previous formula.
$$2a\cos\alpha=(b-a)
 (a\cos\beta+a\sin\alpha)$$
$$2a\cos\alpha=(b-a)
 (b\sin\alpha+a\sin\alpha)$$
$$2a\cos\alpha=(b^2-a^2)\sin\alpha$$
Finally we take the last equation in the form
$$2\sin\alpha\cos\beta=c(\cos^2\beta+\sin^2\alpha-1)$$
Now multiply by $a^2$ and convert the $\cos\beta$ as before,
$$2ab\sin^2\alpha=c(b^2\sin^2\alpha+a^2\sin^2\alpha-a^2)$$
$$2ab\sin^2\alpha=c((a^2+b^2)\sin^2\alpha-a^2)$$
So $$[c(a^2+b^2)-2ab]\sin^2\alpha=a^2c$$
Now to finish we use
$$(2a\cos\alpha)^2+(2a\sin\alpha)^2=4a^2$$
and substituting a previous equation,
$$((b^2-a^2)\sin\alpha)^2+(2a\sin\alpha)^2=4a^2$$
So
$$[(b^2-a^2)^2+4a^2]\sin^2\alpha=4a^2$$
and multiplying by $[c(a^2+b^2)-2ab]$,
$$[(b^2-a^2)^2+4a^2]a^2c=4a^2[c(a^2+b^2)-2ab]$$
our final relation.

A: Disclosure: This almost seems to be the answer that @Rene Schipperus found (originally by @John Bentin on this post), but has some variations. So I am posting it. Although some lines are exactly as the previous answer, I will include them here for the sake of completeness.

$$\tan\theta+\tan\varphi=a$$
$$\sec\theta+\sec\varphi=b$$
$$\csc\theta+\csc\varphi=c$$
Changing the shape of these equations, $$\sin\theta\cos\varphi+\sin\varphi\cos\theta=a\cos\theta\cos\varphi\tag1$$
$$\cos\theta+\cos\varphi=b\cos\theta\cos\varphi\tag2$$
$$\sin\theta+\sin\varphi=c\sin\theta\sin\varphi\tag3$$
Further moulding,
$$2\sin\left(\frac{\theta+\varphi}2\right)\cos\left(\frac{\theta+\varphi}2\right)=a\cos\theta\cos\varphi\tag4$$
$$2\cos\left(\frac{\theta+\varphi}2\right)\cos\left(\frac{\theta-\varphi}2\right)=b\cos\theta\cos\varphi\tag5$$
$$2\sin\left(\frac{\theta+\varphi}2\right)\cos\left(\frac{\theta-\varphi}2\right)=c\sin\theta\sin\varphi\tag6$$
Dividing (4) by (5),
$$\frac{\sin\left(\frac{\theta+\varphi}2\right)}{\cos\left(\frac{\theta-\varphi}2\right)}=\frac ab\tag7$$
Multiply (6) by (7) and 1/(7) respectively,
$$2\sin^2\left(\frac{\theta+\varphi}2\right)=\frac{ac}b\sin\theta\sin\varphi$$
$$2\cos^2\left(\frac{\theta-\varphi}2\right)=\frac{bc}a\sin\theta\sin\varphi$$
From the last two we get,
$$1-\cos(\theta+\varphi)=\frac{ac}b\sin\theta\sin\varphi\tag8$$
$$1+\cos(\theta-\varphi)=\frac{bc}a\sin\theta\sin\varphi\tag9$$
(9) - (8)
$$\cos(\theta+\varphi)+\cos(\theta-\varphi)=\left(\frac{bc}a-\frac{ac}b\right)\sin\theta\sin\varphi$$
$$2\cos\theta\cos\varphi=\frac{c(b^2-a^2)}{ab}\sin\theta\sin\varphi$$ $$\tan\theta\tan\varphi=\frac{2ab}{c(b^2-a^2)}=\lambda\quad\text{  (say)}$$
Ok, leave it here and let's move back to first few equations.
Dividing (6) by (5),
$$\tan\left(\frac{\theta+\varphi}2\right)=\frac cb\tan\theta\tan\varphi=\frac cb\lambda$$
Now using, $$\tan(\theta+\varphi)=\frac{2\tan\left(\frac{\theta+\varphi}2\right)}{1-\tan^2\left(\frac{\theta+\varphi}2\right)}$$
$$\frac{\tan\theta+\tan\varphi}{1-\tan\theta\tan\varphi}=\frac{2\tan\left(\frac{\theta+\varphi}2\right)}{1-\tan^2\left(\frac{\theta+\varphi}2\right)}$$
$$\frac a{1-\lambda}=\frac{2\dfrac cb\lambda}{1-\left(\dfrac cb\lambda\right)^2}$$
Further simplifications lead to, $$c[(b^2-a^2)^2-4a^2]=4[c(b^2-a^2)-2ab]$$ and finally, $$(b^2-a^2)^2c=4b^2c-8ab$$ which is indeed the answer obtained using the other method.
An alternate form is $$\boldsymbol{(2b-a^2+b^2)(2b+a^2-b^2)c=8ab}$$ which seems better!


text:
Q: How to count cache-misses in mmap-ed memory (using eBPF)? I would like to get timeseries
t0, misses
...
tN, misses

where tN is a timestamp (second-resolution) and misses is a number of times the kernel made disk-IO for my PID to load missing page of the mmap()-ed memory region when process did access to that memory. Ok, maybe connection between disk-IO and memory-access is harder to track, lets assume my program can not do any disk-io with another (than assessing missing mmapped memory) reason. I THINK, I need to track something called node-load-misses in perf world.
Any ideas how eBPF can be used to collect such data? What probes should I use?
Tried to use perf record for similar purpose: I dislike how much data perf records. As I recall the try was like (also I dont remember how I parsed that output.data file):
perf record -p $PID -a -F 10 -e node-loads -e node-load-misses -o output.data
I thought eBPF could give some facility to implement such thing in less overhead way.

A: Loading of mmaped pages which are not present in memory is not hardware event like perf's cache-misses or node-loads or node-load-misses. When your program assess not present memory address, GPFault/pagefault exception is generated by hardware and it is handled in software by Linux kernel codes. For first access to anonymous memory physical page will be allocated and mapped for this virtual address; for access of mmaped file disk I/O will be initiated. There are two kinds of page faults in linux: minor and major, and disk I/O is major page fault.
You should try to use trace-cmd or ftrace or perf trace. Support of fault tracing was planned for perf tool in 2012, and patches were proposed in https://lwn.net/Articles/602658/
There is a tracepoint for page faults from userspace code, and this command prints some events with memory address of page fault:
echo 2^123456%2 | perf trace -e 'exceptions:page_fault_user' bc

With recent perf tool (https://mirrors.edge.kernel.org/pub/linux/kernel/tools/perf/) there is perf trace record which can record both mmap syscalls and page_fault_user into perf.data and perf script will print all events and they can be counted by some awk or python script.
Some useful links on perf and tracing: http://www.brendangregg.com/perf.html http://www.brendangregg.com/ebpf.html https://github.com/iovisor/bpftrace/blob/master/INSTALL.md
And some bcc tools may be used to trace disk I/O, like https://github.com/iovisor/bcc/blob/master/examples/tracing/disksnoop.py or https://github.com/brendangregg/perf-tools/blob/master/examples/iosnoop_example.txt
And for simple time-series stat you can use perf stat -I 1000 command with correct software events
perf stat -e cpu-clock,page-faults,minor-faults,major-faults -I 1000 ./program
...
#           time             counts unit events
     1.000112251             413.59 msec cpu-clock                 #    0.414 CPUs utilized
     1.000112251              5,361      page-faults               #    0.013 M/sec
     1.000112251              5,301      minor-faults              #    0.013 M/sec
     1.000112251                 60      major-faults              #    0.145 K/sec
     2.000490561              16.32 msec cpu-clock                 #    0.016 CPUs utilized
     2.000490561                  1      page-faults               #    0.005 K/sec
     2.000490561                  1      minor-faults              #    0.005 K/sec
     2.000490561                  0      major-faults              #    0.000 K/sec


text:
Q: Retrieving ForeignKey mapped objects in Python with SqlAlchemy I have an existing database that I'm trying to map into SqlAlchemy's ORM. I want it to just figure out the ForiegnKey relations that already exist in the database itself.
Here's the code I have so far:
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base

# connect to database and infer from structure
Base = declarative_base()
engine = create_engine("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
metadata = MetaData(bind=engine)

class Club(Base):
    __table__ = Table('clubs', metadata, autoload=True)
    def __repr__(self):
        return "<Club: %s>" % (self.name,)

class Member(Base):
    __table__ = Table('members', metadata, autoload=True)
    def __repr__(self):
        return "<Member: %s of %d>" % (self.name, self.club_id)

Here's the SQL table dump:
CREATE TABLE `clubs` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(45) collate utf8_bin default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

CREATE TABLE `members` (
  `id` int(11) NOT NULL auto_increment,
  `club_id` int(11) default NULL,
  `name` VARCHAR(100) default NULL,
  PRIMARY KEY  (`id`),
  KEY `fk_members_club_idx` (`club_id`),
  CONSTRAINT `fk_members_club` FOREIGN KEY (`club_id`) REFERENCES `clubs` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

My problem is that in the Member __repr__ function, for example, instead of printing the club_id (which is useless to human), I'd like to print the Club name. Something like member.club.name would be ideal.
I couldn't find out how to do this on the SqlAlchemy docs unless I defined my own tables, not merely reflecting them in my code, which is what I'm doing here.

A: Just change your Member class to look like below:
class Member(Base):
    __table__ = Table('members', metadata, autoload=True)
    club = relationship(Club, backref="members")
    def __repr__(self):
        return "<Member: %s of %s>" % (self.name, self.club.name)

The point being that the reflection (autoload) will not automatically create relationships between classes, so you have to define them explicitly.


text:
Q: Electric field between two displaced, coaxial cylinders? This is not about the classic coax cable homework problem. I'm wondering how to find the electric field between two displaced coaxial cylinders, shown below.

How would it be affected by adding cylinders of a dielectric inside the electrodes (dark gray)?


text:
Q: Export Listview items to excel, getting subitems not a member of listviewItem error I am currently populating a listview with data from a database based on text that a user enters to a search textbox.
<ListView x:Name="listSearchServer" HorizontalAlignment="Center" Height="282" Margin="20,50,33,0" VerticalAlignment="Top" Width="264" BorderThickness="1" BorderBrush="#FFCCCCCC" Grid.ColumnSpan="3"/>

So when I run my SQL and get the data that i need, I add these items to the listview
While reader.Read()

                countvalues = countvalues + 1

                'Populate the SearchServers listview with result from query

                Dim share = reader("ShareName")
                listSearchServer.Items.Add(share)

            End While

Now I have added a button to export the results to excel and I have used the following code that is bringing back an error- "subitems not a member of listviewitems"
Private Sub cmdExportServer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExportServer.Click

    Dim xls As New Excel.Application
    Dim book As Excel.Workbook
    Dim sheet As Excel.Worksheet

    xls.Workbooks.Add()
    book = xls.ActiveWorkbook
    sheet = book.ActiveSheet

    Dim row As Integer = 1
    Dim col As Integer = 1

    For Each item As ListViewItem In listSearchServer.Items

        For i As Integer = 0 To item.SubItems.Count - 1
            sheet.Cells(row, col) = item.SubItems(i).Text
            col = col + 1
        Next
        row += 1
        col = 1
    Next

    xls.Visible = True

    sheet = book.Sheets("Sheet1")

    Me.Close()
End Sub

Is this because I don't have sub items? does anyone know how I could export the data to excel.
EDIT
Dim row As Integer = 1

    For Each item As String In listSearchServer.Items

        sheet.Cells(row, 1) = item
        row = row + 1
    Next

For this example i did not actually need to move across columns, and the "For Each item As ListViewItem" was changed to "as String" and then for each row I assigned the item in the listview to the excel column row and incremented each time which worked fine.
Thanks to @jelly for the help


text:
Q: searching for a "calendar framework" to use Good day all.
I've involved in a nice project where I will code a sort of CRM for a learning centre.
They are already using "excell" to keep track of the courses/professors/rooms and they used to organize events on a "week-day" basis, for example, let's say that the marketing lession is every friday, at 12:00, they have an excell sheet where in the first column, there are the weekdays, then the other columns are the dates of the year which are that day, let's assume friday:
               |       JANUARY         ||      FEBRUARY    ||
    FRIDAY     | 3 | 10 | 17 | 24 | 31 || 7 | 14 | 21 | 28 || ....
8:00 - 10:00   | A | A  | A  | A  |    ||   |    |    |    || ....
10:00 - 12:00  |   |    | B  | B  | B  || B |    |    |    || ....
12:00 - 14:00  | C | C  |    |    |    || C | C  |    |    || ....
...

my question is, given this kind of "view" anyone knows a calendar (plugin, framework, standalone...), written in PHP or javascript (or similar, read jquery or else)?
I would like an help to be pointed in the right direction, just tu prevent to write down the  all calendar and reinvent the wheel.
i've given an eye on some calendar written in jquery and to php-calendar, but i got any luck...
if someone knows the way...
Thanks in advance.
EDIT
I have found this image on shuterstock, which rapresent the way I would like this calendar.
http://www.shutterstock.com/pic-88297315/stock-vector-vector-year-calendar-month-in-a-column-weekdays-aligned-horizontally-rounded-cells-rounded.html

A: You can use arshaw fullCalender JS plugin,  http://arshaw.com/fullcalendar/
It has different views monthly , weekly and daily. you will need weekly view for your website. or you can show all the views at same time
Regards.


text:
Q: iOS-tests with realm.io doesn't work I have a simple realm object like this:
@interface Person : RLMObject
@property NSString *name;
@end

RLM_ARRAY_TYPE(Person)

*

*I already enabled the "Target Membership" for my test project

Now I like to test something with realm.io this way:
#import <XCTest/XCTest.h>
#import "Person.h"

@interface PersonTests : XCTestCase
@end

@implementation PersonTests

- (void)setUp {[super setUp];}
- (void)tearDown {[super tearDown];}
- (void)testFooBar
{
    // !!! the test crashes right here!!!!
    Person *person = [[Person alloc] init];

    person.name = @"foobar";

    RLMRealm *realm = [RLMRealm defaultRealm];

    [realm beginWriteTransaction];
    [realm addObject:person];
    [realm commitWriteTransaction];

    ......
}

... but the test crashes in the first line (Person *person = [[Person alloc] init];) with the following error

*** Terminating app due to uncaught exception 'RLMException', reason: 'objectClass must derive from RLMObject'

Does anyone know what I am doing wrong? I'm thankful for any hint!!

A: I was having the same error, and after 4 hours of delete, clone, clean, re-install pods, repeat... what works for me is:
Podfile
link_with 'MyProject', 'MyProjectTests'

#common pods such as CocoaLumberjack

pod 'Realm', '0.89.0'

target 'MyProjectTests', exclusive: true do
  pod 'Realm/Headers'
end

TestFile
#import <UIKit/UIKit.h>
#import <XCTest/XCTest.h>
#import <Realm/Realm.h>
#import "RealmObjectSubclass.h"

- (void)setUp {
  [super setUp];
  NSString *resourcePath = [NSBundle bundleForClass:[self.class]].resourcePath;
  NSString *testRealPath = [NSString stringWithFormat:@"%@.test", resourcePath];
  [RLMRealm setDefaultRealmPath:testRealPath];
}


text:
Q: Failed build trigger in team city TeamCity Is it possible to Trigger an exe to run on a failed build? Can you do this within Team City?

A: If you specifically want the failed builds, you can set up the dependent build as Eric said, and have that secondary buildscript use the REST API to pull up a list of the failed builds for the actual project.
If the latest build is in that failed builds list, then tell the build script to run the executable. If not, then you're all done!
http://confluence.jetbrains.net/display/TW/REST+API+Plugin

A: I don't think it's possible to trigger an executable to run only on failed TeamCity builds. TeamCity usually allows you to do things either always or only upon successful builds.
It would be possible to trigger an executable to run after this build is finished (failed or successful).
If that would work for you, you could set up a new build configuration that runs the executable. The new build configuration would have a "finish build" trigger. This would cause the executable to be run whenever the other build is completed.

A: You should add another build step with the exe you want to run and set the correct option to execute.execution options


text:
Q: what is Unit Testing MVC4 Response Status Code I have a unit test that test route with too many segments, but I'd like to extend it to test Response Status Code (which should return 404 code).
Is it possible to use that mocked httpContext and check a status code?
HttpContextMock.Object.Response.StatusCode always returns 0 status code (due to mocking just one part of HttpContext I suppose).
[TestMethod]
public void RouteWithTooManySegments()
{
    var routes = new RouteCollection();
    MyApp.RouteConfig.RegisterRoutes(routes);

    var httpContextMock = new Mock<HttpContextBase>();
    var httpResponseMock = new Mock<HttpResponseBase>();

    httpContextMock.Setup(c => c.Request.AppRelativeCurrentExecutionFilePath)
        .Returns("~/dawd/dawdaw/dawdaw/daw");

    RouteData routeData = routes.GetRouteData(httpContextMock.Object);

    Assert.IsNull(routeData);
}

Using ErrorController to return status code "404" in the view and appropriate Response Status Code:
public class ErrorController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View();
    }
}

and Web.Config rules
 <httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
 </httpErrors>

A: The below Unit Test would verify the HttpStatusCode would set to 404. Note it must be set in your Controller's Action as you have in your question. If you expect the Web.config to interact it is more of a web integration test, which is completely a different test.
[TestMethod]
public void RouteWithTooManySegments()
{
    var httpContextStub = new Mock<HttpContextBase>();
    var httpResponseMock = new Mock<HttpResponseBase>();
    var controllerContextStub = new Mock<ControllerContext>();

    httpContextStub.Setup(x => x.Response).Returns(httpResponseMock.Object);
    controllerContextStub.Setup(x => x.HttpContext)
        .Returns(httpContextStub.Object);

    var sut = new ErrorController
        { ControllerContext = controllerContextStub.Object };

    sut.NotFound();

    httpResponseMock.VerifySet(x => x.StatusCode = 404);
}


text:
Q: JTable with checkbox issue-Table is not created at runtime can anyone please help me. I am trying to create a dynamic table with checkboxes. Data are accessed from database. But it is not creating the table at runtime. It retrieves data from database properly. But I am not getting why it is not creating the table in a specified Panel (panTable). Below is the code:
int tasktotr=0;
Object[][] taskcells;
JTable ttable;

public void BuildTable() {
   Statement st;
   ResultSet rs;

   panTable.updateUI();
   String query="";
   try{
       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       conn=DriverManager.getConnection("jdbc:odbc:dsndbPMA","","");
       st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
       query="select * from Task";
       rs=st.executeQuery(query);
       rs.last();
       tasktotr=rs.getRow();
       System.out.println("tasktotr="+tasktotr);
       taskcells=new Object[tasktotr][6];
       if(tasktotr>0){
           int cnt=0;
           rs.beforeFirst();
           for(int c=0;c<6;c++){
               if(c==cnt){
                   int r=0;
                   while(rs.next()){
                       if(c==0)
                           taskcells[r][c]=Boolean.FALSE;
                       else if(c==1)
                           taskcells[r][c]=rs.getString("Priority");
                       else if(c==2)
                           taskcells[r][c]=rs.getString("Subject");
                       else if(c==3)
                           taskcells[r][c]=rs.getString("Status");
                       else if(c==4)
                           taskcells[r][c]=rs.getString("DueDate");
                       else if(c==5)
                           taskcells[r][c]=rs.getString("%Complete");
                       else if(c==6)
                           taskcells[r][c]=rs.getString("Category");
                       r++;
                   }
               }
                rs.beforeFirst();
                cnt++;
           }
           rs.close();
           st.close();
           for(int i=0;i<tasktotr;i++){
               for(int j=0;j<6;j++){
                   System.out.println(taskcells[i][j]);
               }
           }
           TableModel tasktable=new TaskTableModel(tasktotr,7);
           ttable=new JTable(tasktable);

           TableColumnModel columnModel=ttable.getColumnModel();
           TableColumn column;
           for(int i=0;i<ttable.getColumnCount();i++) {
               column = columnModel.getColumn(i);
               if(i==0)
                   column.setPreferredWidth(40);
               if(i==1)
                   column.setPreferredWidth(40);
               if(i==2)
                   column.setPreferredWidth(150);
           }
           ttable.setRowHeight(18);
           ttable.setAutoResizeMode(ttable.AUTO_RESIZE_OFF);
           ttable.getTableHeader().setReorderingAllowed(false);

           JScrollPane scroll=new JScrollPane(ttable);
           scroll.setAutoscrolls(true);
           panTable.add(scroll);
           panTable.updateUI();
           panTable.revalidate();
       }
   }catch(Exception e){
       e.printStackTrace();
       JOptionPane.showMessageDialog(null,e.getMessage(),"Error!!",1);
   }
}

class TaskTableModel extends AbstractTableModel{
    int totrow,totcol;
    public TaskTableModel(int r,int c){
        totrow=r;
        totcol=c;
    }
    @Override
    public int getRowCount() {
        return totrow;
    }
    @Override
    public int getColumnCount() {
        return totcol;
    }

    public Object getValueAt(int r,int c) {
        return taskcells[r][c];
    }

    public String getColumnName(int c){
        if(c==0)
            return "Icon";
        else if(c==1)
            return "Priority";
        else if(c==2)
            return "Subject";
        else if(c==3)
            return "Status";
        else if(c==4)
            return "Due Date";
        else if(c==5)
            return "% Completed";
        else if(c==6)
            return "Category";
        else
            return "";
    }

    public void setValueAt(Object obj,int r,int c){

        taskcells[r][c]=obj;
        fireTableCellUpdated(r, c);
    }

    //Edit only first column.
    public boolean isCellEditable(int r,int c){
        return c==0;
    }

    //used to display checkbox else it will show true/false text instead of checkbox. n
    public Class getColumnClass(int c) {
        return getValueAt(0, c).getClass();
    }

}

A: The reason why it isn't displayed correctly is an ArrayIndexOutOfBoundsException within your getValueAt method. The table taskcells is created with six columns (also only six are filled and displayed in your print loop) but the table model is created with seven columns. If your correct it your code should work (although there might still be an issue within a code part you didn't post here).
Note: You may consider reading the data not column-wise but row-wise from the database, i.e. rearrange the rs and c loops. Then you can even omit the c-loop completely.


text:
Q: Filter not returning results in Angular Material I am trying  to filter results from a table using Material NG but am not getting any results and no errors either.
Here is my code
  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = {};

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: ItemsInterface) => {
      this.dataSource = res;
      this.dataSource = new Array(res);
      console.log(this.dataSource[0]);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource[0].filter = filterValue.trim().toLowerCase();
  }

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (keyup)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>

    <ng-container matColumnDef="name">
       Name
       {{element.name}}
    </ng-container>

    <ng-container matColumnDef="description">
       Description
       {{element.description}}
    </ng-container>

    <ng-container matColumnDef="url">
       URL
       Go to site
    </ng-container>

I'm wondering if it's the format of the dataSource I have. It looks like this.
[
  {
    "name": "Ajax",
    "description": "a technology for asynchronous HTTP requests",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AJAX.md"
  },
  {
    "name": "AMD",
    "description": "a standard defining how to load JavaScript libraries or modules asynchronously",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/AMD.md"
  },
  {
    "name": "AngularJS",
    "description": "a structural framework for dynamic web apps",
    "url": "https://github.com/HugoGiraudel/SJSJ/blob/master/_glossary/ANGULARJS.md"
  }
]

I have made a repo here to reproduce issue.
https://github.com/dhameergovind/NG-Starter.git

A: api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Constants } from '../constants/constants';
import { ItemsInterface } from '../models/data';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

 constructor(private httpClient: HttpClient) {
 }

  getData(): Observable<ItemsInterface[]> {
    return this.httpClient.get<ItemsInterface[]>(Constants.API_ENDPOINT + 'data.json');
  }

}

app.component.ts
import { Component, OnInit, ViewChild , AfterViewInit} from '@angular/core';
import { ApiService } from './services/api.service';
import { ItemsInterface } from './models/data';
import { MatPaginator, MatTableDataSource } from '@angular/material';
export interface SourceDataType {
  name: string;
  description: string;
  markdown: string;
  html: string;
  url: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent implements OnInit , AfterViewInit{
  @ViewChild(MatPaginator, { static: false }) paginator: MatPaginator;
  ELEMENT_DATA: SourceDataType[];
  title = 'NG PWA';
  displayedColumns: string[] = ['name', 'description', 'url'];
  dataSource = new MatTableDataSource<SourceDataType>(this.ELEMENT_DATA);
  public loading = false;
  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.loading = true;
    this.apiService.getData().subscribe((res: SourceDataType[]) => {
      this.dataSource = new MatTableDataSource<SourceDataType>(res);
      this.dataSource.paginator = this.paginator;
      console.log(this.dataSource);
      this.loading = false;
    }, err => {
      this.loading = false;
    });
  }
  ngAfterViewInit() {
    setTimeout(() => this.dataSource.paginator = this.paginator);
  }
  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

app.component.html
<mat-toolbar color="primary">
  <mat-toolbar-row>
    Data
  </mat-toolbar-row>
</mat-toolbar>

  <mat-form-field>
    <mat-label>Filter</mat-label>
    <input matInput (input)="applyFilter($event)" placeholder="Filter">
  </mat-form-field>

    <ng-container matColumnDef="name">
       Name
       {{element.name}}
    </ng-container>

    <ng-container matColumnDef="description">
       Description
       {{element.description}}
    </ng-container>

    <ng-container matColumnDef="url">
       URL
       Go to site
    </ng-container>

<router-outlet></router-outlet>
<ngx-loading [show]="loading" [config]="{ backdropBorderRadius: '3px' }"></ngx-loading>


text:
Q: How can I paste links and transpose at the same time? I have a long list of titles along the top of a sheet, that I want to turn into a vertical list on another sheet but which is linked to the original list.  Basically I want to paste links into another sheet but tranpose it at the same time.
The Paste Special allows me to paste links, or paste the transposed range as formulas or values (not as links), but does not not allow me to do both at the same time as the Paste Links button is greyed out when the transpose option is ticked.  What is the easiest way to achieve the same output?
Input (Sheet1) - a row of numbers:

Desired output (Sheet2, formula view) - a column of links:

A: In C3 of Sheet2, just put this and drag downwards should do :
=OFFSET(Sheet1!$C$3,0,ROW()-3)

Idea : use cell's row numbers as reference 'column shifter'.
Please share if it works/not. ( :


text:
Q: Embed XSD files in one (binary) file Our C++ project uses ~30 XSD files for validation of XML messages.
For deployment we would like to have all XSD files embedded in one file. Additionally it would be nice, if the file would be binary, so the XSD schemas cannot be viewed easily.
Is there a solution for Windows (additional Linux support would be nice, but no requirement) to embed multiple text files in one big binary file and use it for a C++ application?

A: Possible Windows-specific solution is to create resource-only DLL with all your XSDs (or any other files).
Use below links for details.
https://learn.microsoft.com/en-us/cpp/build/creating-a-resource-only-dll

Additionally it would be nice, if the file would be binary, so the XSD
  schemas cannot be viewed easily.

Resources in dll\exe are not encrypted and anybody will be able to read them using resource viewer


text:
Q: cmake external projects command seems to ignore INSTALL_DIR First off, I'm relatively new to cmake. I'm trying to use cmake to build a project with a single external dependency. I specify the INSTALL_DIR for the external project to be CMAKE_INSTALL_PREFIX, so it installs to the same place as the parent project. But when I run make, it ignores it and tries to install to /usr/local/lib.
Here's my CMakeList.txt:
cmake_minimum_required( VERSION 2.8 )
include( ExternalProject )
project( capture )
add_library( capture SHARED capture.cc )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )

ExternalProject_Add( proj_exceptions
    GIT_REPOSITORY /home/user/workspace/exceptions
    INSTALL_DIR ${CMAKE_INSTALL_PREFIX}
)

add_library( exceptions SHARED IMPORTED )
set_property( TARGET exceptions
    PROPERTY IMPORTED_LOCATION ${CMAKE_INSTALL_PREFIX}/lib/libexceptions.so
)
add_dependencies( exceptions proj_exceptions )
include_directories( ${CMAKE_INSTALL_PREFIX}/include )
target_link_libraries( capture exceptions )
install( TARGETS capture DESTINATION lib )
install( FILES capture.h DESTINATION include )

CMakeLists.txt for the external project looks like this:
cmake_minimum_required( VERSION 2.8 )
project( exceptions )
add_library( exceptions SHARED exceptions.cc )
install( TARGETS exceptions DESTINATION lib )
install( FILES exceptions.hh DESTINATION include )

It clones and builds the external project just fine, but it chokes on the install step:
Install the project...
-- Install configuration: ""
-- Installing: /usr/local/lib/libexceptions.so
CMake Error at cmake_install.cmake:42 (file):
  file INSTALL cannot copy file
  "/home/user/workspace/capture/build/proj_exceptions-prefix/src/proj_exceptions-build/libexceptions.so"
  to "/usr/local/lib/libexceptions.so".
Makefile:66: recipe for target 'install' failed

As you can see, the install configuration is empty. Looking through the generated config for the external project, I found this in cmake_install.cmake:
if(NOT DEFINED CMAKE_INSTALL_PREFIX)
  set(CMAKE_INSTALL_PREFIX "/usr/local")
endif()

So, it seems that passing INSTALL_DIR to ExternalProject_Add doesn't set the install prefix. The install step succeeds, if I instead use:
ExternalProject_Add( proj_exceptions
    GIT_REPOSITORY /home/djones/workspace/exceptions
    CMAKE_ARGS "-DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}"
)

So what's the purpose of INSTALL_DIR then?

A: You're right for the purpose of INSTALL_DIR, but you may have missed some steps.
According the cmake 2.8 doc about external project:

Install Step
The INSTALL_DIR is underneath the calling project's
  binary directory. Use INSTALL_DIR to specify a different location.
  Note that in addition to setting INSTALL_DIR, you also have to pass
  -DCMAKE_INSTALL_PREFIX or --prefix to the CMake or configure command. It is not used automatically in the configure step since not all
  projects follow this convention.
# [INSTALL_DIR dir]
You can refer to the install directory in your configure command, for
  example:
CONFIGURE_COMMAND SOURCE_DIR/configure --prefix=INSTALL_DIR

 # [INSTALL_COMMAND cmd...]

CMake-based projects use 'cmake--build' to build the install target.
  Other projects use 'make install'. Use INSTALL_COMMAND to customize
  the install step. Use INSTALL_COMMAND "" to omit the install step. The
  install command executes with the working directory set to
  .

So try to update your cmake command, or use the custom INSTALL_COMMAND feature.


text:
Q: Background fetch is not working on a real device Please help with advice. For some reason, Background fetch on a real iOS device does not work. When running through Xcode (Debug -> Sumulate Background Fetch) everything works correctly. But when I install the app on a real device, this function does not work.
I'll clarify the following:

*

*I do not kill the application, but just minimize it.

*The Background App Refresh setting is enabled both in the settings of the app and in the settings of the entire phone.

*I waited more than a day - nothing happened.

What seems to me to be the reason:

*

*I run the app on the iPhone through TestFlight.

*There is no SIM card installed on the iPhone.

*In my app, the standard name of the AppDelegate file was changed to BaseDelegate, and its location was changed from MyApp/MyApp/AppDelegate.swift to MyApp/MyApp/base/BaseDelegate.swift (the app is correctly configured for the new name and location of this file).
Can it somehow affect?

What I've done:

*

*I turned on the Background fetch mode in the project settings.

*I added the following code to info.plist
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
</array>

*The following code has been added to AppDelegate.swift:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum)
}

func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    var message = UserDefaults.standard.string(forKey: "fetch") ?? "nil"
    message = "\(message) | \(Helper.getStringFromDate(Helper.getCurrentDate()))"
    UserDefaults.standard.set(message, forKey: "fetch")

    // Sending local notification ...

    // Receiving data from the server ...

    completionHandler(.newData)
}

To test the app, I send a local notification, and also save the time in UserDefaults.


text:
Q: How do I resolve import with absolute path? What do I need to setup in brunch-config.js to be able to resolve absolute path from project's root folder? i.e
import { helper } from '/imports/utilities/helper'

The reason being is I have a legacy React app and it imports local files by using relative path. While I'm trying to use brunch, I need to figure out a way to setup brunch so that it understands the path without having to change the code.
I tried to use npm alias but not sure how it works
npm: {
  aliases: {
    '/imports': 'imports/**'
  }
}

A: Found the solution with babel-plugin-module-resolver package.
Since all my codes are under /imports dir, in brunch-config.js I setup an alias based on their documentation:
plugins: {
  babel: {
    plugins: [
      ...,
      ["module-resolver", {
        "root": ["./imports"],
        "alias": {
          "/imports": ([, path]) => `./imports${path}`,
        }
      }]
    ],
    presets: [
      ...
    ],
  }
},

That way, if I do import Screen from '/imports/components/screens' it will resolve the file under ./imports/components/screens
You can set the alias in .babelrc too but you might want to use regex instead.


text:
Q: How to format the condition in a dynamically generated conditionalPanel in Shiny? I am trying to create widgets in Shiny by using for loop. each block contains:

*

*label

*check box

*choices selector

*Two numeric inputs

I want to do condition for showing or hiding the two numeric inputs according to the value of the check box and the value of the choices selector.
In the for loop that I created I added an index for each widget variable.
I am wondering how can I execute the condition of the conditional panel in the for loop knowing that the variables are indexed in their names. Thanks for helping. I share with you the server.R and the UI.R scripts:
 library(shiny)
shinyServer(function(input, output) {

  output$input_value2 <- renderUI({
    fluidRow(

      lapply(1:8, function(i) {

        column(width = 4,
               output[[paste0('b', i)]] <- renderUI({strong(paste0('Variable N ', i))}),
               checkboxInput(label = 'Inclued',paste0('c', i)),
               selectInput(paste0('popDist', i), "Distribution",list("Normal" = "normal","Uniforme" = "uniforme")),

               conditionalPanel(
                 condition = "eval(parse(text=paste0('input.popDist',i)))== 'uniforme'& (eval(parse(text=paste0('input.c',i)))==1",
                 numericInput(paste0('min', i), label = "Min:", value = 1),
                 numericInput(paste0('max', i), label = "Max:", value = 2)
               ),

               conditionalPanel(
                 condition = "eval(parse(text=paste0('input.popDist',i)))== 'uniforme'& (eval(parse(text=paste0('input.c',i)))==1",

                 numericInput(paste0('mean', i), label ="mean:", value = 0),
                 numericInput(paste0('sd', i), label = "st. dev.:", value = 1)

               )
        )
      })
    )
  })
})

    library(shiny)
shinyUI(fluidPage(
  titlePanel("TEST conditional panel"),
  uiOutput("input_value2")
  ))

A: Your first condition should be:
paste0("input.popDist",i,"== 'uniforme'& input.c",i,"==1")

and the second:
paste0("input.popDist",i," == 'normal'& input.c",i,"==1")

so they become, with i=1:
"input.popDist1== 'uniforme'& input.c1==1"

and
"input.popDist1 == 'normal'& input.c1==1"

respectively.
Working example:
library(shiny)
library(shinyjs)
server <- shinyServer(function(input, output) {

  output$input_value2 <- renderUI({
    fluidRow(

      lapply(1:8, function(i) {

        column(width = 4,
               output[[paste0('b', i)]] <- renderUI({strong(paste0('Variable N ', i))}),
               checkboxInput(label = 'Inclued',paste0('c', i)),
               selectInput(paste0('popDist', i), "Distribution",list("Normal" = "normal","Uniforme" = "uniforme")),

               conditionalPanel(
                 condition = paste0("input.popDist",i,"== 'uniforme'& input.c",i,"==1"),
                 numericInput(paste0('min', i), label = "Min:", value = 1),
                 numericInput(paste0('max', i), label = "Max:", value = 2)
               ),

               conditionalPanel(
                 condition = paste0("input.popDist",i," == 'normal'& input.c",i,"==1 "),

                 numericInput(paste0('mean', i), label ="mean:", value = 0),
                 numericInput(paste0('sd', i), label = "st. dev.:", value = 1)

               )
        )
      })
    )
  })

})

library(shiny)
ui <- shinyUI(fluidPage(
  useShinyjs(),
  titlePanel("TEST conditional panel"),
  uiOutput("input_value2")
))

shinyApp(ui,server)


text:
Q: Two approaches on the support of functionals I am writing concerning support of functionals on C*-algebras. I feel there are two different definitions for this notion. Let $A$ be a C*-algebra and $\phi$ be a positive linear functional on $A$. Then one may also  consider $\phi$ as a $w^*$-continuous linear functional on $A^{**}$.
1st (Based on the Takesaki's book Vol I- page 134)
There is a unique projection in $e \in A^{**}$ with $e\phi=e\phi e=\phi$ and $\phi$ is  faithful on $eAe$, such a projection is called the support of $\phi$.
2ed (Based on the Sakai's book- page 31)
There is a largest projection $q\in A^{**}$ with $\phi(q)=0$. Then $1-q$ is called the support of $\phi$.
Example.  Let us consider the functional $\phi:C[0,1]\to \mathbb{C}$ given by $\phi(f)=\int_0^1 f(t)dt$. I think by the 1st approach, the support of $\phi$ is just the constant function $1$. Obviously $\phi$ vanishes on all characteristic functions $\chi_I$, where $I$ is a countable subset in $[0,1]$. These characteristic functions  are all in $C[0,1]^{**}$ and so by the second approach the support of $\phi$ is not $1$.
Do you confirm that these are different too!?

A: The two approaches are the same: $e=1-q$.
Your question assumes that the functional extends like integration against Lebesgue measure; that's not the case (it doesn't even make sense). Below is a proof of the equivalence of the two approaches.
1 $\implies$ 2: Let $K\subset A^{**}$ be the set of projections $$K=\{p\in A^{**}:\ \phi(p)=0\}$$ and let $q$ be the supremum of $K$. So we can choose an increasing net of projections $q_j\in K$ with $q_j\nearrow q$. As every functional of $A$ becomes normal on $A^{**}$, we have $$\phi(q)=\lim\phi(q_j)=0.$$ Note that $1-e\leq q$ (because $\phi(1-e)=0$). Also, since $\phi$ is positive, $$|\phi(qe)|\leq\phi(q)^{1/2}\phi(e)^{1/2}=0.$$ So $\phi(eqe)=\phi(qe)=0$, and as $\phi$ is faithful on $eAe$, $eqe=0$. Then $qe=0$, and it follows that $q=(1-e)q$, and so $q\leq 1-e$. Then $q=1-e$
$$
\
$$
2 $\implies$ 1: let $e=1-q$. The computation above shows that $\phi(qa)=0$ for all $a\in A^{**}$. Thus $$\phi(a)=\phi(aq)+\phi(ae)=\phi(ae).$$ Similarly, $\phi(a)=\phi(ea)$; so $$\phi(a)=\phi(eae)=\phi(ae)=\phi(ea).$$
Finally, if $0=\phi(eae)$, then $\phi(ae)=0$. Subsequently, $\phi(a^ne)=0$ for all $n$, and by linearity and w$^*$-continuity, $\phi(x)=\phi(xe)=0$ for all $x\in W^*(a)$. Let $r$ be any projection in $W^*(A)$; we have $\phi(r)=0$. Then $r\leq q=1-e$. Thus $ere=0$; as $r$ is any projection in $W^*(a)$, $exe=0$ for all $x\in W^*(a)$, and so $eae=0$ and $\phi$ is faithful on $eAe$.


text:
Q: Spring microservice instance is not registering with Eureka running in port other than 8761 application.yml of my microservice (client to Eureka)
spring:
  application:
    name: queue1

eureka:
  client:
    registerWithEureka: true
    fetchRegistry: true
    serviceUrl:
      defaultZone: http://localhost:8762/

server:
  port: 7777

app:
  id: ${random.uuid}

application.yml of Eureka
eureka:
  instance:
    hostname: peer1
  client:
    register-with-eureka: false
    fetch-registry: false
server:
  port: 8762

I am starting Eureka in port 8762 and referring to that in my microservices.
Microservice is failing to register itself with Eureka.
Following is the exception from microservice logs.
2019-03-21 17:02:16.248 ERROR 1804 --- [freshExecutor-0] com.netflix.discovery.DiscoveryClient    : DiscoveryClient_ZUUL_RIBBON/ICB8061.ibsplc.com:zuul_ribbon:8080 - was unable to refresh its cache! status = Cannot execute request on any known server

com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known server
    at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:112) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$6.execute(EurekaHttpClientDecorator.java:137) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.getApplications(EurekaHttpClientDecorator.java:134) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient.getAndStoreFullRegistry(DiscoveryClient.java:1051) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient.fetchRegistry(DiscoveryClient.java:965) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient.refreshRegistry(DiscoveryClient.java:1479) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient$CacheRefreshThread.run(DiscoveryClient.java:1446) [eureka-client-1.9.8.jar:1.9.8]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [na:1.8.0_202]
    at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_202]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_202]

2019-03-21 17:02:16.278 ERROR 1804 --- [tbeatExecutor-0] c.n.d.s.t.d.RedirectingEurekaHttpClient  : Request execution error. endpoint=DefaultEndpoint{ serviceUrl='http://localhost:8762/}

javax.ws.rs.WebApplicationException: com.fasterxml.jackson.databind.exc.MismatchedInputException: Root name 'timestamp' does not match expected ('instance') for type [simple type, class com.netflix.appinfo.InstanceInfo]
 at [Source: (com.sun.jersey.client.apache4.ApacheHttpClient4Handler$HttpClientResponseInputStream); line: 1, column: 2]
    at com.netflix.discovery.provider.DiscoveryJerseyProvider.readFrom(DiscoveryJerseyProvider.java:110) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:634) ~[jersey-client-1.19.1.jar:1.19.1]
    at com.sun.jersey.api.client.ClientResponse.getEntity(ClientResponse.java:586) ~[jersey-client-1.19.1.jar:1.19.1]
    at com.netflix.discovery.shared.transport.jersey.AbstractJerseyEurekaHttpClient.sendHeartBeat(AbstractJerseyEurekaHttpClient.java:105) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.MetricsCollectingEurekaHttpClient.execute(MetricsCollectingEurekaHttpClient.java:73) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.RedirectingEurekaHttpClient.execute(RedirectingEurekaHttpClient.java:89) ~[eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.RetryableEurekaHttpClient.execute(RetryableEurekaHttpClient.java:120) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator$3.execute(EurekaHttpClientDecorator.java:92) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.SessionedEurekaHttpClient.execute(SessionedEurekaHttpClient.java:77) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.shared.transport.decorator.EurekaHttpClientDecorator.sendHeartBeat(EurekaHttpClientDecorator.java:89) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient.renew(DiscoveryClient.java:846) [eureka-client-1.9.8.jar:1.9.8]
    at com.netflix.discovery.DiscoveryClient$HeartbeatThread.run(DiscoveryClient.java:1405) [eureka-client-1.9.8.jar:1.9.8]
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) [na:1.8.0_202]
    at java.util.concurrent.FutureTask.run(Unknown Source) [na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) [na:1.8.0_202]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) [na:1.8.0_202]
    at java.lang.Thread.run(Unknown Source) [na:1.8.0_202]

Now the most important thing is, everything is perfectly fine if I change the Eureka server port and the microservice's Eureka registration port to 8761 !!!! Registration of microservice is succeding in this case.
Did this multiple times before posting the question and it is behaving like this.
Any inputs here would be very much helpful.

A: I had the same issue, it was due to spring security dependencies in the Eureka server project. After adding the @EnableWebSecurity code to the eureka server application fixed for me.
    @EnableWebSecurity
   static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
        }
    }

Spring Boot Verison - 2.3.2.RELEASE
Spring Cloud Version - Hoxton.SR1
https://github.com/spring-cloud/spring-cloud-netflix/issues/2754#issuecomment-372808529


text:
Q: How does Angular's data-binding's interpolation work? This is more about internals of Angular. When I put something in between "{{xyz.abc}}" how does it work? How come that I see the value of that property, not just xyz.abc in between two braces?

A:
{{ }} this is called String Interpolation.

whenever angular detect this pattern in the template, it will execute the expression inside  {{ expression }}.
when Angular change detection system run, it will re Evaluate the expression inside {{ expression }}
this is called One-Way Data-Binding .
you use it when you want to display a dynamic data from typeScript code into your template.
learn more: https://angular.io/guide/displaying-data.


text:
Q: Null Pointer Exception on an EditText in a Fragment I am building a signUp page in which i want a date picker but whenever i click on User Fragment to open Sign up Page then the app crashes, and the error is nullPointerException in EditText. Please Help me to solve it.
Here is the Code of UserFragment.java
public class UserFragment extends Fragment {
public EditText et_Date;
public static final int REQUEST_CODE = 11;
String selectedDate;
private OnFragmentInteractionListener mListener;
public DatePickerDialog.OnDateSetListener setListener;
View view;
public UserFragment() {
}
public static UserFragment newInstance() {
    UserFragment fragment = new UserFragment();
    return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.adduser_fragment, container, false);
    et_Date  = (EditText) view.findViewById(R.id.etdate);
    final FragmentManager fm = ((AppCompatActivity)getActivity()).getSupportFragmentManager();
    et_Date.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            AppCompatDialogFragment newFragment = new DatePickerFragment();
            newFragment.setTargetFragment(UserFragment.this,REQUEST_CODE);
            newFragment.show(fm, "DatePicker");
        }
    });
    return view;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK){
            selectedDate = data.getStringExtra("SelectedDate");
            et_Date.setText(selectedDate);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if(context instanceof OnFragmentInteractionListener){
        mListener= (OnFragmentInteractionListener) context;
    }else{
        throw new RuntimeException(context.toString()+"must implement OnFragmentInterationListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}
public interface OnFragmentInteractionListener {

    public void onFragmentInteraction(Uri uri);
}
}

A: Your editText with id etdate is actually in layout adduser_fragment? This error may be because of view is in another layout(and you forgot that). Sorry for answer, I don't have enough reputation to post comment.


text:
Q: Primary router routes everything through secondary router I have two routers, that I want to represent two subnets. They are configured in this way:
Primary router (from ISP):

*

*LAN: 192.168.0.1 / 24

*DHCP: 192.168.0.10-100

*SSID: 'router1'

Secondary router:

*

*IP address: 192.168.0.101 (also tried with DHCP)

*Gateway: 192.168.0.1

*LAN: 192.168.2.1 / 24

*DHCP: 192.168.2.100-200

*SSID: 'router2'

*cable goes from this router's WAN to primary one's LAN port.

Now, I have two laptops. One connected through WiFi other by cable, but both to Primary router.
WiFi Laptop can access Web fine, I can also get to admin panel of the primary router.
Ethernet laptop can't make it to the web. arp -a table shows only 192.168.2.1 which should be the default gateway of devices in the Secondary Subnet. I also get assigned 192.168.2.113. The problem disappears as soon as I disconnect cable and connect wirelessly.
Why is that so? I'm connected straight to the primary router.

A: Either the router from your ISP is not configured to permit the LAN subnet on router 2 through NAT or you are performing double NAT (NAT on both ISP and router 2), or both.
Double check your ethernet connection as well, if your laptop ethernet is getting an IP from router 2, it is likely not connected to the ISP router.


text:
Q: Javascript Not Working in Modal Window With Render Partial (Yii) I implemented a modal with its content rendered using renderPartial(). However, when I try to call a script inside the modal window (e.g $.blockUI), it doesn't work at all. No errors though.
This is how I rendered the content:
echo CJSON::encode($this->renderPartial($view, array(
    'dataProvider' => $dataProvider,
    'model' => $model,
    'selectedIds' => $selected,
     ), TRUE, TRUE));


text:
Q: Remove elements from a list in R based on a condition I have a list l in R as shown below. I want to remove elements where the only alphanumeric character is 0. How can I do that?
# Create list
l <- list(c('108', '50', '0]'), c('109','58','0','0]'), c('18','0'))
l
[[1]]
[1] "108" "50"  "0]"
[[2]]
[1] "109" "58"  "0"   "0]"
[[3]]
[1] "18" "0"

# What I want:
l
[[1]]
[1] "108" "50"
[[2]]
[1] "109" "58"
[[3]]
[1] "18"

A: We can use grepl to match either 0 or the ] and negate (!) to remove the values from the list elements
lapply(l, function(x) x[!grepl("^0$|\\]", x)])
#[[1]]
#[1] "108" "50"

#[[2]]
#[1] "109" "58"

#[[3]]
#[1] "18"

Or convert to numeric remove the NA elements along with 0
lapply(l, function(x) x[!is.na(as.numeric(x)) & x != 0])

Or use setdiff
lapply(l, setdiff, c("0", "0]"))

A: I believe this is a general purpose way.
l2 <- lapply(l, function(s) {
  s <- gsub('[^[:digit:]]', '', s)
  s[nchar(sub('([^0]*)0([^0]*)', '\\1\\2', s)) != 0]
  })

l2
#[[1]]
#[1] "108" "50"
#
#[[2]]
#[1] "109" "58"
#
#[[3]]
#[1] "18"

A: An even more general solution, that removes potential elements like "&% 00]" (where the only alphanumeric characters are 0)
lapply(l, function(x) x[grep('^[0[:punct:][:blank:]]*$', x, invert = TRUE)])


text:
Q: How to use environment var GODEBUG Could someone please explain me how to use the environment variable GODEBUG ?
Maybe a link to a good tutorial
Google is not very helpful - or I don't know what to search for

A: The GODEBUG environment variable is documented in the runtime package.
Dave Cheney describes how to visualize GC using telemetry from GODEBUG=gctrace=1.