text:
Q: Some reputation which yields "escalate (BUMP) the question!"
Possible Duplicate:
Please add a way to 'bump' questions back to the front page.

In a crowded tags listing, its a matter of minutes that your question is buried under number of comments.
Essentially, there must be a role designed for the users to have the ability to BUMP the questions so it is raised back to top marked with "bump +1 [2, 3......]" in order to draw the crowd's attention. Besides their own questions, the user with this role may also be able to uplift other member's questions.

A: This seems like you're asking for users to have the ability to bump questions for very subjective reasons, possibly without putting more effort into the question.
There are already mechanisms in place to get attention to a question. If you edit the question (and, one would hope, improve it), or consider answering it, it brings it to the rop of the list. You can also place a bounty to get attention to the question.
You could also bring the question up in chat, and ask what to do to the question to get more answers.

A: We already have this in multiple incarnations:

*

*You can edit (or suggest an edit) to the question. Considering how incredibly rare it is to come across a post that is perfect and cannot be improved in any possible way, this is often the best and easiest solution. Any time that a question is edited, it is automatically "bumped" to the top of the list.

*You can set a bounty on the question. This does require a trivial amount of reputation, and it does entail you giving up some of your own hard-earned reputation, but if the question is about something that is really important to you, neither of these should be insurmountable burdens. The bounty system was explicitly designed to "bump" questions so that they're seen by more people, and thus [hopefully] answered more quickly. They even appear under the special "featured" tab, where they'll remain for much longer and are very unlikely to get "bumped off" by other questions.

*You can answer the question. This isn't always a workable solution, particularly for questions which you don't know the answer. And we strongly discourage users from posting answers to questions that don't actually, well, answer the question. But if you can contribute something useful, this is an appropriate way of "bumping" the question back up to the top of the list.

*The Community user already bumps old questions in need of attention. I don't believe that the exact algorithm has been published, but this does work for questions that have been around for a while but haven't received any answers.
And it's been proposed that we give high-rep users' questions more time on the front page. You can show your support for that proposal by voting for it, if you wish.


text:
Q: PHP Pear -- 'MDB2\Driver\mysql.php' missing I've inherited a huge project, and I'm having a real time just trying to get the damned thing on its legs. Every time I run the project, amongst all the Strict Standards and Depreciated notices is one error:
Failed opening 'MDB2\Driver\mysql.php' for inclusion
From what I've read, DBMS drivers stopped being included in default Pear installations over five years ago... So how I can fix this so that either it doesn't use mysql.php anymore, or that my Pear installation DOES have it?
According to the Pear website, I just need to type: pear install MDB2_Driver_mysql but I'm wondering if it wouldn't just be better to change the code?
Thanks!

A: You say the project is huge, so I would suggest you don't rewrite it to use a different DB access library as that could push out your release date quite a bit and instead just install the required MDB2 driver.
To install the mysql driver, just do:
# pear install --alldeps MDB2_Driver_mysql

(and maybe consider using the mysqli driver instead)
If you do decide to migrate the project to use a different library, I'd suggest Doctrine as it is one of the mature DB libraries out there.

A: It sounds like you are trying to run PHP code written for an older version on a version of PHP that does not like some of the code.
Also see this for some insight on what you actually have to have installed on the PC running wamp in order to actually access a DB2 database. Are you sure you have all of this installed before you try to install via PECL?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Famous Engine Physics Collisions I am building a site which requires a physics engine.
Having worked with a number of SPA apps i feel pretty confident with.
Unfortunately I am having trouble applying collision detection & walls to a physics simulation that famous has created.
You can see the editable example here.
https://staging.famous.org/examples/index.html?block=gravity3d&detail=false&header=false

What I would like to know is it possible to add collisions to the particles? I have tried this but it appears the collisions are not setup correctly. I was hoping someone has managed to do it successfully.
Thanks!

var FamousEngine = famous.core.FamousEngine;

var Camera = famous.components.Camera;

var DOMElement = famous.domRenderables.DOMElement;
var Gravity3D = famous.physics.Gravity3D;
var Gravity1D = famous.physics.Gravity1D;
var MountPoint = famous.components.MountPoint;
var PhysicsEngine = famous.physics.PhysicsEngine;
var Physics = famous.physics;
var Wall = famous.physics.Wall;
var Position = famous.components.Position;
var Size = famous.components.Size;
var Sphere = famous.physics.Sphere;
var Vec3 = famous.math.Vec3;
var Collision = famous.physics.Collision;

function Demo() {
  this.scene = FamousEngine.createScene('#socialInteractive');

  this.camera = new Camera(this.scene);
  this.camera.setDepth(1000);

  this.simulation = new PhysicsEngine();
  this.items = [];

  this.collision = new Collision();

  var Wall = famous.physics.Wall;
  var rightWall = new Wall({
    direction: Wall.LEFT
  }); // bodies coming from the left will collide with the wall
  rightWall.setPosition(1000, 0, 0);

  var ceiling = new Wall({
    normal: [0, 1, 0],
    distance: 300,
    restitution: 0
  });
  var floor = new Wall({
    normal: [0, -1, 0],
    distance: 300,
    restitution: 0
  });
  var left = new Wall({
    normal: [1, 0, 0],
    distance: 350,
    restitution: 0
  });
  var right = new Wall({
    normal: [-1, 0, 0],
    distance: 350,
    restitution: 0
  });
  var node = this.scene.addChild();
  var position = new Position(node);
  // this.simulation.attach([right, left, floor, ceiling])
  // this.items.push([ceiling,position]);

  for (var i = 0; i < 10; i++) {
    var node = this.scene.addChild();
    var size = new Size(node).setMode(1, 1);
    var position = new Position(node);
    if (i === 0) {
      createLogo.call(this, node, size, position);
    }
    if (i !== 0) {
      node.id = i;
      createSatellites.call(this, node, size, position);
    }
  }
  FamousEngine.requestUpdateOnNextTick(this);
  console.log(this.collision)
  for (var i = 0; i < this.collision.length; i++) {
    this.simulation.attach(collision, balls, balls[i]);
  }
  this.simulation.addConstraint(this.collision);
}

Demo.prototype.onUpdate = function(time) {
  this.simulation.update(time);
  this.collision.update(time, 60);
  if (this.items.length > 0) {
    for (var i = 0; i < this.items.length; i++) {
      var itemPosition = this.simulation.getTransform(this.items[i][0]).position;
      this.items[i][1].set(itemPosition[0], itemPosition[1], 0);
    }
  }
  FamousEngine.requestUpdateOnNextTick(this);
};

function createLogo(node, size, position) {
  size.setAbsolute(50, 50);
  var mp = new MountPoint(node).set(0.5, 0.5);
  var el = new DOMElement(node, {
    tagName: 'img',
    attributes: {
      src: './images/famous-logo.svg'
    }
  });
  var sphere = new Sphere({
    radius: 100,
    mass: 10000,
    restrictions: ['xy'],
    position: new Vec3(window.innerWidth / 2, window.innerHeight / 2, 5)
  });

  this.gravity = new Gravity3D(sphere);
  this.simulation.add(sphere, this.gravity);
  this.items.push([sphere, position]);

}

function createSatellites(node, size, position, i) {
  size.setAbsolute(20, 20);
  var radius = 200;
  var x = Math.floor(Math.random() * radius * 2) - radius;
  var y = (Math.round(Math.random()) * 2 - 1) * Math.sqrt(radius * radius - x * x);
  var color = 'rgb(' + Math.abs(x) + ',' + Math.abs(Math.round(y)) + ',' + (255 - node.id) + ')';
  var el = new DOMElement(node, {
    properties: {
      'background-color': color,
      'border-radius': '50%'
    }
  });
  var satellite = new Sphere({
    radius: 20,
    mass: 5,
    position: new Vec3(x + window.innerWidth / 2, y + window.innerHeight / 2, 0)
  });
  satellite.setVelocity(-y / Math.PI, -x / Math.PI / 2, y / 2);
  this.gravity.addTarget(satellite);
  this.simulation.add(satellite);
  this.items.push([satellite, position]);
  this.collision.addTarget(satellite);

}

// Boilerplate
FamousEngine.init();

// App Code
var demo = new Demo();

A: Thanks for your help Talves, I think i found a solution that works with physics Spring instead of gravity3d. This also has the 4 walls included which seems to work well.

var famous = famous;
var FamousEngine = famous.core.FamousEngine;

var Camera = famous.components.Camera;

var DOMElement = famous.domRenderables.DOMElement;
var Gravity3D = famous.physics.Gravity3D;
var MountPoint = famous.components.MountPoint;
var PhysicsEngine = famous.physics.PhysicsEngine;
var Position = famous.components.Position;
var Size = famous.components.Size;
var Wall = famous.physics.Wall;
var Sphere = famous.physics.Sphere;
var Vec3 = famous.math.Vec3;
var math = famous.math;
var physics = famous.physics;
var collision = famous.physics.Collision;
var gestures = famous.components.GestureHandler;
var Spring = famous.physics.Spring;
console.log(famous)
var anchor = new Vec3(window.innerWidth / 2, window.innerHeight / 2, 0);

//Create Walls
var rightWall = new Wall({
  direction: Wall.LEFT
}).setPosition(window.innerWidth - 20, 0, 0);
var leftWall = new Wall({
  direction: Wall.RIGHT
}).setPosition(window.innerWidth + 20, 0, 0);
var topWall = new Wall({
  direction: Wall.DOWN
}).setPosition(0, 20, 0);
var bottomWall = new Wall({
  direction: Wall.UP
}).setPosition(0, window.innerHeight - 20, 0);

function Demo() {
  this.scene = FamousEngine.createScene('body');

  this.camera = new Camera(this.scene);
  this.camera.setDepth(1000);

  this.collision = new collision([rightWall, leftWall, topWall, bottomWall]);

  this.simulation = new PhysicsEngine();
  this.simulation.setOrigin(0.5, 0.5);
  this.simulation.addConstraint(this.collision);

  this.items = [];
  this.walls = [];

  //Create Items
  for (var i = 0; i < 30; i++) {
    var node = this.scene.addChild();
    node.setMountPoint(0.5, 0.5);
    var size = new Size(node).setMode(1, 1);
    var position = new Position(node);
    if (i === 0) {
      createLogo.call(this, node, size, position);
    }
    if (i !== 0) {
      node.id = i;
      createSatellites.call(this, node, size, position);
    }
  }

  //Create Walls
  var node = this.scene.addChild();
  createWalls(node);

  FamousEngine.requestUpdateOnNextTick(this);

  Demo.prototype.onUpdate = function(time) {
    this.simulation.update(time);

    //Postition walls
    var wallPosition = topWall.getPosition();
    node.setPosition(wallPosition.x, wallPosition.y);

    //Position elements
    if (this.items.length > 0) {
      for (var i = 0; i < this.items.length; i++) {
        var itemPosition = this.simulation.getTransform(this.items[i][0]).position;
        this.items[i][1].set(itemPosition[0], itemPosition[1], 0);
      }
    }

    FamousEngine.requestUpdateOnNextTick(this);
  };
}

function createWalls(wallNode) {
  wallNode.setSizeMode('absolute', 'absolute', 'absolute').setAbsoluteSize(window.innerWidth, 10, 0);
  var wallDOMElement = new DOMElement(wallNode, {
    tagName: 'div'
  }).setProperty('background-color', 'lightblue');
}

function createLogo(node, size, position) {
  size.setAbsolute(50, 50);
  var mp = new MountPoint(node).set(0.5, 0.5);
  var el = new DOMElement(node, {
    tagName: 'img',
    attributes: {
      src: './images/famous_logo.png'
    }
  });
  var sphere = new Sphere({
    radius: 100,
    mass: 10000,
    restrictions: ['xy'],
    position: new Vec3(window.innerWidth / 2, window.innerHeight / 2, 5)
  });

  // this.gravity = new Gravity3D(sphere);
  // this.simulation.add(sphere, this.gravity);
  this.simulation.add(sphere);
  this.items.push([sphere, position]);
}

function createSatellites(node, size, position, i) {
  size.setAbsolute(50, 50);
  var radius = 100;
  var x = Math.floor(Math.random() * radius * 2) - radius;
  var y = (Math.round(Math.random()) * 2 - 1) * Math.sqrt(radius * radius - x * x);
  var color = 'rgb(' + Math.abs(x) + ',' + Math.abs(Math.round(y)) + ',' + (255 - node.id) + ')';
  var el = new DOMElement(node, {
    properties: {
      'background-color': color,
      'border-radius': '50%'
    }
  });
  var satellite = new Sphere({
    radius: 25,
    mass: 10,
    position: new Vec3(x + window.innerWidth / 2, y + window.innerHeight / 2, 0)
  });

  // Attach the box to the anchor with a `Spring` force
  var spring = new Spring(null, satellite, {
    stiffness: 95,
    period: 0.6,
    dampingRatio: 1.0,
    anchor: anchor
  });

  //console.log(color);
  // satellite.setVelocity(-y / Math.PI, -x / Math.PI / 2, y / 2);
  satellite.setVelocity(0.5, 0.5, 0);
  // this.gravity.addTarget(satellite);
  this.simulation.add(satellite, spring);
  this.items.push([satellite, position]);
  this.collision.addTarget(satellite);

}

// Boilerplate
FamousEngine.init();

// App Code
var demo = new Demo();
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Famous :: Seed Project</title>
        <link rel="icon" href="favicon.ico?v=1" type="image/x-icon">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            html, body {
                width: 100%;
                height: 100%;
                margin: 0px;
                padding: 0px;
            }
            body {
                position: absolute;
                -webkit-transform-style: preserve-3d;
                transform-style: preserve-3d;
                -webkit-font-smoothing: antialiased;
                -webkit-tap-highlight-color: transparent;
                -webkit-perspective: 0;
                perspective: none;
                overflow: hidden;
            }
        </style>
    </head>
    <body>
        <script src="http://code.famo.us/famous/0.6.2/famous.min.js"></script>
    </body>
</html>


text:
Q: c# class design for fields with inheritance I have a C# class that I want to reuse for different scenarios. Depending on the scenario, the values of some of the fields will need to change. I was thinking of building an abstract base class and then inheriting. The constructors of the descendent classes would have new field values in them. Something like this:
public abstract Class MyBaseClass
{
   protected string var1;
   protected string var2;
   protected string var3;
   public MyBaseClass()
   {
      var1 = string.empty;
      var2 = string.empty;
      var3 = string.empty;
   }
   public bool myfunc()
   {
       //code to do something with var1...var3
   }
}
  public class myderivedclass: MyBaseClass
 {
    public myderivedclass()
    {
     //constructor for derived class
     base.var1 = "whatever";
     base.var2 = "something";
     base.var3 = "somethingelse";
    }
 }

 public class myotherderivedclass: MyBaseClass
 {
    public myotherderivedclass()
    {
     //constructor for derived class
     base.var1 = "new";
     base.var2 = "newer";
     base.var3 = "newest";
    }
 }

I would then instantiate myderivedclass or myotherderivedclass and call functions like myfunc to do the work.
Is there a better way to handle these changes in fields or is this a good approach?
Thank-you.

A: I don't know if protected fields are actually considered a bad practice, but in my opinion it's a code smell. Fields are usually an implementation detail, and derived classes shouldn't rely on implementation details of their base class.
A cleaner approach would be to change var1, var2 and var3 to virtual properties, and override them in derived classes.
public abstract Class MyBaseClass
{
   protected virtual string var1 { get { return ""; } }
   protected virtual string var2 { get { return ""; } }
   protected virtual string var3 { get { return ""; } }

   public bool myfunc()
   {
       //code to do something with var1...var3
   }
}

 public class myderivedclass: MyBaseClass
 {
     protected override string var1 { get { return "whatever"; } }
     protected override string var2 { get { return "something"; } }
     protected override string var3 { get { return "somethingelse"; } }
 }

A: If the difference is only in the initial values this is not a good approach. It's better to introduce a new constructor in the base class that accepts parameters. Then in the child classes just pass different values.
public abstract class MyBaseClass
{
    private string var1;
    private string var2;
    private string var3;

    public MyBaseClass(string var1, string var2, string var3)
    {
        this.var1 = var1;
        this.var2 = var2;
        this.var3 = var3;
    }

    public bool Myfunc()
    {
        //code to do something with var1...var3
    }
}

public class DerivedClass : MyBaseClass
{
    public DerivedClass()
        : base("var1value", "var2value", "var3value")
    {
        //constructor for derived class
    }
}

public class OtherDerivedClass : MyBaseClass
{
    public OtherDerivedClass()
        : base("new", "newer", "newest")
    {
        //constructor for derived class
    }
}

Moreover, protected fields are not very good practice. If you need to access this members in child classes it's better to introduce protected properties.
public abstract class MyBaseClass
{
    protected string Var1 { get; private set; }
    protected string Var2 { get; private set; }
    protected string Var3 { get; private set; }

    public MyBaseClass(string var1, string var2, string var3)
    {
        this.Var1 = var1;
        this.Var2 = var2;
        this.Var3 = var3;
    }

    public bool Myfunc()
    {
        //code to do something with var1...var3
    }
}

[ ... ]

public class DerivedClass : MyBaseClass
{
    public DerivedClass()
        : base("var1value", "var2value", "var3value")
    {
        // constructor for derived class
        // can acces protected members here
    }
}

[ ... ]

A: Another way to accomplish your goal this is using an interface. It acts like an abstract class, but with only method signatures. Whatever is in the interface must be in the inherited class.
For instance:
public interface IMyBaseClass
{
     // Properties for classes
     string MyVar1 {get;set;}
     string MyVar2 {get;set;}
     string MyVar3 {get;set;}

     // Method to be implemented
     bool MyFunc();
}

And your inherited class would look like this:
public class MyInheritedClass :IMyBaseClass
{
    public string MyVar1 {get;set;}
    public string MyVar2 {get;set;}
    public string MyVar3 {get;set;}

    public MyInheritedClass()
    {
         this.MyVar1 = "whatever";
         this.MyVar2 = "something";
         this.MyVar3 = "something else";
    }

    public bool MyFunc()
    {
       // do some code here
    }
}

Notice I didn't have to write override on the properties, because if your class is inheriting from an Interface, then you can implement your own implementation per class. Just like an abstract class, an interface cannot be used as an object.


text:
Q: special characters in name field for search We are creating a quick find search field.
The html is like so:
<form>
                    <fieldset class="search">
                    <input class="contact-propid" type="text" name="" value="" placeholder="enter property id">
                    <button class="btn" title="Search"></button>

                    </fieldset>
                </form>

the expected search term is like : p-442749379
And the dest url looks like:
thissite.com/listing.php?id=p-442749379
Now this quick search is in the header of all pages..
And I see if I add : name="listing.php?id=" in the input class , it nearly gets me to where I want to go ...
Except the browser converts the ? and = and doesnt render these in the browser correctly
fiddle http://jsfiddle.net/ozzy/EdKpM/
oh and it puts a ? before listing

A: <form action="listing.php" method="GET">
     <input type="text" name="id" placeholder="enter property id">
     <input type="submit" value="Search">
</form>

Set an action and method on the <form> and a name on the <input> element and it'll do what you want.


text:
Q: iOS "widget" style interface I am trying to come up with a good way to design an app with a "plug-in" or "widget" style interface (where plug-ins are simply UIViews for example, that can be added as a subview on a UIScrollView). Essentially, something like the iOS Notification Center where I can have lets say 3 "widgets" all of different heights but they fit perfectly based on the previous "widgets" height, maybe even be able to re-order widgets. Where is a good place to start?
----------------
|  ----------  | <- UIScrollView
|  | widget |  |
|  |   1    |  |
|  ----------  |
|  ----------  |
|  | widget | <- UIViews
|  |  ...   |  |
|  |   2    |  |
|  ----------  |
|  ----------  |
|  | widget <- UILabel (for example)
|  |   3    |  |
|  ----------  |
----------------

A: Sounds like making it a UITableViewController and having each widget be a UITableViewCell would be a good idea. This would make editing and rearranging simple and easy


text:
Q: node.js + object key value appending In my node application i am running 2 sequelize queries and getting 2 object array as output. Now i have to append 1 key value from 2nd object array to the first.
Consider the following are the 2 object array:
1st
[{"id_0":56,
  "id_1":67,
  "staterank":32},
{"id_0":87,
  "id_1":97,
  "staterank":5}
]

2nd array:
[{"id_0":56,
  "id_1":67,
  "countryrank":140},
{"id_0":87,
  "id_1":97,
  "countryrank":400}
]

The array needed by me:
[{"id_0":56,
  "id_1":67,
  "staterank":32
  "countryrank":140},
{"id_0":87,
  "id_1":97,
  "staterank":5
  "countryrank":400}
]

I tried for the following code:
2ndarray.forEach(function(countryelem){
            1sttarray.forEach(function(stelem){
                    console.log("countryelem=" + util.inspect(countryelem));
                stelem.countryrank = countryelem.country_rank;
                })
            })

But i am receiving coumtrycode as "1" which is the last entry in 2nd array.Please help me to solve this..Thanks in advance..


text:
Q: insmod error: inserting './hello.ko': -1 Invalid module format" I have just made my first driver module, the hello world module following LDD3. However unfortunately encountered this error:
insmod: error inserting './hello.ko': -1 Invalid module format.

I am doing this on Ubuntu 11.04, and my environment:
$ uname -r
2.6.38-8-generic

I get the kernel source like this:
sudo apt-cache search linux-source
linux-source - Linux kernel source with Ubuntu patches
linux-source-2.6.38 - Linux kernel source for version 2.6.38 with Ubuntu patches
$sudo apt-get install linux-source-2.6.38

my /usr/src:
$ls /usr/src/
linux-headers-2.6.38-8          linux-source-2.6.38          vboxguest-5.0.10
linux-headers-2.6.38-8-generic  linux-source-2.6.38.tar.bz2

and then I compile the kernel
$sudo cp /boot/config-2.6.38-8-generic ./.config
$sudo make menuconfig -- load the .config file
$make
$make modules

and then I compile my kernel module
$make -C /usr/src/linux-source-2.6.38/linux-source-2.6.38 M=`pwd` modules

with Makefile:
obj-m := hello.o

and then finally when I insert the module:
$sudo insmod hello_world.ko
insmod: error inserting 'hello_world.ko': -1 Invalid module format

what I found in dmesg:
hello: disagrees about version of symbol module_layout

So what's the problem?
I have also noticed that the linux-header is -2.26.38-generic and source code version is -2.26.38, is this the problem? but I have really not found a linux-source-2.26.38-generic package on web.
status update:
I have found that the file /lib/moduels/$(name -r)/build/Makefile indicate my running kernel version:
VERSION = 2
PATCHLEVEL = 6
SUBLEVEL = 38
EXTRAVERSION = .2

So I download the linux-2.6.38.2 and compile, but still the same error.
I have also found that there is a line in /boot/config-$(uname -r):
CONFIG_VERSION_SIGNATURE="Ubuntu 2.6.38-8.42-generic 2.6.38.2"

Does any one know what is this mean? I don't see it in the config file of the kernel i am building.

A: Kernel from which you build your kernel module and to which you are inserting module should be of same version. If you do not want to take care of this thing you can use following Makefile.
obj−m += hello−world.o

all:
 make −C /lib/modules/$(shell uname −r)/build M=$(PWD) modules
clean:
 make −C /lib/modules/$(shell uname −r)/build M=$(PWD) clean

Now you can build and try to insert module.
I suggest you to become root if possible before this line

$sudo cp /boot/config-2.6.38-8-generic ./.config

$su
#cp /boot/config-2.6.38-8-generic ./.config
#insmod hello_world.ko

Alternatively you can also use following make file
TARGET  := hello-world
WARN    := -W -Wall -Wstrict-prototypes -Wmissing-prototypes
INCLUDE := -isystem /lib/modules/`uname -r`/build/include
CFLAGS  := -O2 -DMODULE -D__KERNEL__ ${WARN} ${INCLUDE}
CC      := gcc-3.0

${TARGET}.o: ${TARGET}.c

.PHONY: clean

clean:
    rm -rf ${TARGET}.o

A: Try using cross compile. Please look at the code below for the make file. Be mindful of the indentation else you may end up with error such as  missing separator. Stop
obj-m += hello_.o #this name should be the name of your .c file. I am just using hello for example
I suggest the best approach is via cross compilation
Create a variable to hold the directory name where the linux kernel directory resides In my example, change the value "PATH_TO_LINUX_KERNEL_DIRECTORY" to a real path value
  Example ~/linux
 You really need to do this so that the make file will know where to find arm-linux-gnueabi- Without this, you are likely to run into issues arm-linux-gnueabi-
KDIR := PATH_TO_LINUX_KERNEL_DIRECTORY

all:
    make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- -C $(KDIR) M=$(shell pwd) modules

clean:
    make -C $(KDIR) M=$(shell pwd) clean

A: You did everything correctly but did not booted your system with the kernel you compiled so the first step is you should boot with it.
If you are using Ubuntu you can hold shift button at the time of booting and you will be given a list of compiled kernel in your system from there select   linux-source-2.6.38 and then try to build your module and install it with your way ,than you won't find any problem.
GoodLuck.


text:
Q: Frisch-Waugh Theorem for different regressions I'm stuck on the question when the residual vectors of different regressions are numerically equal according to the above mentioned theorem.
Let \begin{equation}
y=Xb+e=X_{1}b_1+X_{2}b_2+e \label{eq:1}
\end{equation} where $b_1, b_2$ are the OLS estimates of the "true" $\beta_1, \beta_2$, respectively.
By pre-multiplying \ref{eq:1}  by $M_1=X_1(X'_1X_1)^{-1}X'_1$ we obtain
\begin{equation}M_{1}y=M_{1}X_{2}b_2+M_{1}e \leftrightarrow \tilde{y}=\tilde{X_2}b_2+e\end{equation}
Thus, the residuals of the regression of $\tilde{y}$ on $\tilde{X_2}$ are the same.
Considering the model $\tilde{y}=X_{1}b_1+X_{2}b_2+residual$, is it possible to say that $residual$ must equal $e$, because premultiplying this model by $M_1$ one obtains $\tilde{y}=\tilde{X_2}b_2+M_1*residual$, where $M_1*residual$ must be $e$ because we are regressing $\tilde{y}$ on $\tilde{X_2}$?
Pretty sure I'm making a mistake here.
If this was true, then by the same reasoning, one would obtain that the residuals from $\tilde{y}$ on $X_2$ were also $e$, which is wrong I guess.
Thanks in advance!


text:
Q: Regarding Guideline 1.3 - Safety - Kids Category App Rejection My iOS App is in the Kids category and i am using below firebase pods for Pushotification and Chat functionality.

pod 'FirebaseMessaging', '~> 4.1'
pod 'FirebaseDatabase', '~> 6.1'
pod 'FirebaseAuth', '~> 6.6'

I am getting rejection of my App in AppStore because of Guideline 1.3 - Safety - Kids Category
Suggest me is this because of firebase SDK i am using?
Below is the rejection statement from Apple.

Guideline 1.3 - Safety - Kids Category
We continue to find that your Kids Category app includes analytics,
advertising and collects, transmits, or has the ability to share
personal information or device information with third parties.
Your app includes the following feature(s), contrary to guideline 1.3
of the App Store Review Guidelines:
Third-party analytics or third-party advertising with the ability to
collect, transmit or share identifiable information, including, for
example, IDFA.
Next Steps
To resolve this issue, please remove this functionality or revise your
app so that no personally identifiable information or device
information is sent to third parties.

A: Yes. As written here: "To resolve this issue, please remove this functionality or revise your app so that no personally identifiable information or device information is sent to third parties."
It is not about the Firebase


text:
Q: Unbiased estimator for a sample. Let $X_i, i=1,2,...,n$; a random sample of a distribution $U(0, \theta)$. Prove that $\frac{n+1}{n}X_{(n)}$ is an unbiased estimator of $\theta$.
So what I did is :
$\mathbb{E}\big(\frac{n+1}{n}X_{(n)}\big)=\frac{n+1}{n}\mathbb{E}(X_{(n)})$
And the part that I don't understand is why do $X_{(n)}=\max\{X_1,\ldots, X_n\}$? Because from there it's easy to find the probability density function and its expected value.
I'm following this question/answers for that:
https://math.stackexchange.com/q/744517 and this pdf: https://mcs.utm.utoronto.ca/~nosedal/sta260/sta260-chap9.pdf

A: It's a standard terminology. The maximum of $n$ random variables, $X_1, X_2, \cdots, X_n$ is denoted by $X_{(n)}$. Likewise, the minimum is denoted by $X_{(1)}$. In general, the $k$th maximum random variable is denoted by $X_{(n-k+1)}$.

A: $X_{(i)}$ denotes the $i$-th order statistics, the $i$-th smallest numbers among $X_1, \ldots, X_n$.
$X_{(n)}$ means the $n$-th smallest numbers, which is the biggest number.


text:
Q: rails form submission with remote => true -- js file renders but does not execute There is a similar question here and here but neither has the answer I'm looking for. I've also done a lot of searching for "rails format.js render" without being able to solve this.
In Rails 4, I have a validated form as follows:
<%= form_for(@message, :remote => true) do |form| %>
// don't want to call the js on submit here because
// I don't want it to execute if the form did not validate

I'm calling the js in the controller:
def create
    @message = Message.new(params[:message])
      if @message.valid?
        NotificationsMailer.new_message(@message).deliver
        respond_to do |format|
          format.js { render "submit" }
        end
      else
        render :new
      end
  end

I have "submit.js.erb" in the "messages" folder:
alert('js was called!');

When I submit the form, Terminal verifies the file DOES render:
Rendered messages/submit.js.erb (0.5ms)

...but on the screen, nothing happens. No alert, and no executed javascript. I've also tried creating "submit.html.erb" and wrapping my javscript in a script tag, and the same thing happens - the file loads, but the script does not execute.
Why? What do I need to do to tell Rails to execute the js?
Edit:  After visiting Kelvo's resources and trying many things, the answer seemed to be adding this to the application.js...
 $.ajaxSetup({
    'beforeSend': function (xhr) {xhr.setRequestHeader('Content-Type', 'application/javascript');}
 });

It also turned out that a manual line break and indentation (since it was not wrapping in my IDE) in my actual "submit.js.erb" was causing it to fail to execute, so there were really two problems.

A: This may be due to the fact that the returned content is not being evaluated. The browser does receive the file but does not know what to do with it, you have to include some JavaScript to handle the response as explained here :

You probably don't want to just sit there with a filled out <form>, though. You probably want to do something upon a successful submission. To do that, bind to the ajax:success event. On failure, use ajax:error. Check it out:

in your case you might try out
$(document).ready(function(){
  $("#new_message").on("ajax:success", function (e, data, status, xhr){
     eval(xhr.responseText);
  });
});

in order to evaluate the js code.
you can read more on events fired during "data-remote" requests here
EDIT : forgot to mention, this script has to be included on the HTML file containing the form. Maybe just add it under your form.

A: This may be due to, returned content also including your default layout.
Try this:
format.js {render layout: 'no_layout', action: 'submit'}
Hope this helps...


text:
Q: find the position of a text link in the powerpoint presentation I want to know if there is a way to get the position where a hyperlink is set. In the case of the Shapes they have top and left values, and I can select hyperlinks with Slides(i).Hyperlinks but I cannot find the way to find the position of the hyperlinks that I find in the presentation as I can do with the shapes. Is there a way to do it?

A: You need to look at each hyperlink's type to determine whether it's a hyperlinked shape or a hyperlink applied to text. You already know how to deal with the shapes, but if it's text, you have to walk up the parent chain to find the textrange the hyperlink's applied to.  The textrange's BoundLeft, BoundTop, BoundWidth and BoundHeight properties will tell you where the text is.
Note: if you do this in PPT 2007 with no service packs, PPT will disappear.  Poof.  Gone.
Dim oHl As Hyperlink
Dim oSl As Slide
Dim oRng As TextRange
Set oSl = ActivePresentation.Slides(1)

For Each oHl In oSl.Hyperlinks
    With oHl
        If .Type = msoHyperlinkRange Then
            Debug.Print TypeName(.Parent)
            Debug.Print TypeName(.Parent.Parent)
            Debug.Print TypeName(.Parent.Parent.Parent)
            Debug.Print TypeName(.Parent.Parent.Parent.Parent)
            Set oRng = .Parent.Parent
            Debug.Print oRng.Text
            Debug.Print oRng.BoundLeft
            Debug.Print oRng.BoundTop
        Else
            ' it's a hyperlinked shape

        End If
    End With
Next


text:
Q: java.lang.NoSuchMethodError: No static method getDrawable(Landroid/content/Context;I) Am Integrating Socialize SDK into my app.I also updated my Android Studio to 2.3.3. My Activity's super.onCreate(savedInstanceState) gives me an error. The same question has been raised here'java.lang.NoSuchMethodError: No static method getDrawable(Landroid/content/Context;I)Landroid/graphics/drawable/Drawable;'. But that doesn't help me as I dont have any jar files under my libs folder.
--------- beginning of crash
    06-12 16:07:41.954 16968-16968/com.jeyashri.kitchen.jeyashriskitchen E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.jeyashri.kitchen.jeyashriskitchen, PID: 16968
                                                                                java.lang.NoSuchMethodError: No static method getDrawable(Landroid/content/Context;I)Landroid/graphics/drawable/Drawable; in class Landroid/support/v4/content/ContextCompat; or its super classes (declaration of 'android.support.v4.content.ContextCompat' appears in /data/app/com.jeyashri.kitchen.jeyashriskitchen-1/base.apk:classes8.dex)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:201)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:189)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.checkVectorDrawableSetup(AppCompatDrawableManager.java:710)
                                                                                at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:194)
                                                                                at android.support.v7.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:81)
                                                                                at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:129)
                                                                                at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
                                                                                at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
                                                                                at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
                                                                                at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:31)
                                                                                at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:31)
                                                                                at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)
                                                                                at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
                                                                                at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
                                                                                at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:70)
                                                                                at com.jeyashri.kitchen.jeyashriskitchen.Activity.MainActivity.onCreate(MainActivity.java:60)
                                                                                at android.app.Activity.performCreate(Activity.java:6679)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Below id my gradle file.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.jeyashri.kitchen.jeyashriskitchen"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            java.srcDirs = ['src/main/java', 'src/main/java/com.jeyashri.kitchen.jeyashrikitchen.Fragments', 'src/main/java/Fragements']
        }
    }
}

android {
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //compile 'com.android.support:appcompat-v7:25.3.1'
    //compile 'com.android.support:design:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.socialize:facebook:3.1.6'
    compile 'com.socialize:ioc:3.1.6'
    compile 'com.socialize:loopy:3.1.7'
    compile 'com.socialize:library:3.1.7'
    compile 'com.google.android.gms:play-services-ads:8.4.0'
    compile 'com.google.apis:google-api-services-youtube:v3-rev176-1.22.0'
    //compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:design:26.0.0-alpha1'
}

This Problem occurs only when I add the below file in the gradle.. Else the app runs without crash.
    compile 'com.socialize:facebook:3.1.6'
    compile 'com.socialize:ioc:3.1.6'
    compile 'com.socialize:loopy:3.1.7'
    compile 'com.socialize:library:3.1.7'

A: Upgrade your gms:play-services version .
Don't
compile 'com.google.android.gms:play-services-ads:8.4.0'

Do
compile 'com.google.android.gms:play-services-ads:10.2.1'


text:
Q: Changing button colors and sending a prop to child component on click with vue.js I'm new with vue.js and trying to make a component work as a follows:
I have four buttons and after I click on one button I wanna change all four buttons colours and send a prop to a child component to inform it the button I choose.
My work as following:
<template>
  <v-app>
    <v-toolbar app>
      <v-toolbar-title class="headline text-uppercase">
        <v-flex>
          <v-btn class="mx-2" icon large>
            <v-icon dark @click="reloadPage" >home</v-icon>
          </v-btn>
          <v-btn class="ma-2" :ref="ModelA" :modelProps="modelA" @click="chooseModel(0)" rounded flat text > MODEL A </v-btn>
          <v-btn class="ma-2" :ref="ModelB" :modelProps="modelB" @click="chooseModel(1)" rounded flat text > MODEL B </v-btn>
          <v-btn class="ma-2" :ref="ModelC" :modelProps="modelC" @click="chooseModel(2)" rounded flat text > MODEL C </v-btn>
          <v-btn class="ma-2" :ref="ModelD" :modelProps="modelD" @click="chooseModel(3)" rounded flat text > MODEL D </v-btn>
        </v-flex>
      </v-toolbar-title>
      <v-spacer></v-spacer>
    </v-toolbar>

    <v-content>
      <childComponent/>
    </v-content>
  </v-app>
</template>

<script>
import childComponent from './components/childComponent'

export default {
  name: 'App',
  components: {
    childComponent
  },
  data () {
    return {

    }
  },
  methods: {

    chooseModel:function(model){

      switch(model){
        case 0:
          this.$refs["ModelA"][0].color = "rgb(0, 100, 0)";
          this.$refs["ModelB"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelC"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelD"][0].color = "rgb(100, 0, 0)";
          break;

        case 1:
          this.$refs["ModelA"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelB"][0].color = "rgb(0, 100, 0)";
          this.$refs["ModelC"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelD"][0].color = "rgb(100, 0, 0)";
          break;

        case 3:
          this.$refs["ModelA"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelB"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelC"][0].color = "rgb(0, 100, 0)";
          this.$refs["ModelD"][0].color = "rgb(100, 0, 0)";
          break;

        case 4:
          this.$refs["ModelA"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelB"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelC"][0].color = "rgb(100, 0, 0)";
          this.$refs["ModelD"][0].color = "rgb(0, 100, 0)";
          break;
      }
    }

  }
}
</script>

Why this is not working and What should I do?

A: First, ref is not a native HTML attribute so you can not bind it. However, it's a custom attribute that vue compiles, so you can use as a normal one.
Also the $refs['modelA'] will have the reference for the Vue element, Vue.js wraps the native HTML elements as well.
Finally. you can store the choosen model in the vue data, and pass it as a prop to the child component.
I created a jsfiddle for you.
https://jsfiddle.net/z3qv1dtp/
Also, I recommend you use Vue data to store the button configuration and pass them as props to each button instead of mutating the Vue element directly.
https://jsfiddle.net/z3qv1dtp/1/


text:
Q: selenium geckodriver error with firefox While launching firefox browserin eclipse i am getting an error as mentioned below Usage:

E:\new gecko\geckodriver.exe [OPTIONS]
    E:\new gecko\geckodriver.exe: Unknown option --port=30415
    Exception in thread "main" org.openqa.selenium.WebDriverException: org.apache.http.conn.HttpHostConnectException: Connect to localhost:30415 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
    Build info: version: 'unknown', revision: '5234b32', time: '2017-03-10 09:00:17 -0800'
    System info: host: 'KIREETI-PC', ip: '192.168.43.138', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_111'
    Driver info: driver.version: FirefoxDriver
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:91)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:604)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:244)
        at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:131)
        at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:218)
        at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:125)
        at org.openqa.selenium.firefox.FirefoxDriver.(FirefoxDriver.java:121)
        at sriram.main(sriram.java:17)
    Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:30415 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
        at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:158)
        at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
        at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
        at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
        at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
        at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
        at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
        at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
        at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:142)
        at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:88)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:296)
        at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:113)
        at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:141)
        at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
        ... 7 more
    Caused by: java.net.ConnectException: Connection refused: connect
        at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
        at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
        at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
        at java.net.PlainSocketImpl.connect(Unknown Source)
        at java.net.SocksSocketImpl.connect(Unknown Source)
        at java.net.Socket.connect(Unknown Source)
        at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:74)
        at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
        ... 22 more

A: Instead of using driver of specific browser, you can use "Webdrivermanager" plugin in maven, so it will resolve most of problems related to browser and its instance.
Even this help me lot to overcome browser related problems.

A: I tried using all the latest versions of driver executable file(geckodriver.exe), Selenium server standalone jar (3.14.0) and Firefox browser. I was not facing any issues.


text:
Q: Deleting a TFS branch using git-tfs I have a feature branch in TFS that I've used locally with git-tfs using git tfs branch --init. (Normally I just use local git branches, but in this case I wanted to create a build with my changes, so a TFS feature branch seemed appropriate)
I've now finished with that feature branch, and I'd like to delete it from TFS and from git. I know how to delete it from TFS - it's the git side that's problematic.
I tried using git tfs branch --delete Features/FeatureBranch, which didn't complain, but subsequently every time I try to do a checkin, it fails with the following error:
D:\dev\git [31753]PS>git tfs checkintool
Unable to locate a remote for <http://tfs:8080/tfs/DefaultCollection>$/Project/Features/FeatureBranch
You may be able to resolve this problem.
- Try using `git tfs bootstrap` to auto-init TFS remotes.
- Try setting a legacy-url for an existing remote.

Is there a way to remove these branches, so that I can go back to using git tfs checkintool normally?
I am using git-tfs 0.19.2.0 and git 1.8.5.2.msysgit.0


text:
Q: Self referencing loop detected EF / Json I am using Entity Framework (code first) and I have mapped all my entities and disabled lazy loading.
This works fine, but as soon as I try to do some Ajax work I start to get issues.
The first issue is with my User class. This looks like this:
public partial class User : IdentityUser
{
    public string CompanyId { get; set; }
    public string CreatedById { get; set; }
    public string ModifiedById { get; set; }
    public System.DateTime DateCreated { get; set; }
    public Nullable<System.DateTime> DateModified { get; set; }
    public System.DateTime LastLoginDate { get; set; }
    public string Title { get; set; }
    public string Forename { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string JobTitle { get; set; }
    public string Telephone { get; set; }
    public string Mobile { get; set; }
    public string Photo { get; set; }
    public string LinkedIn { get; set; }
    public string Twitter { get; set; }
    public string Facebook { get; set; }
    public string Google { get; set; }
    public string Bio { get; set; }
    public string CompanyName { get; set; }
    public string CredentialId { get; set; }
    public bool IsLockedOut { get; set; }
    public bool IsApproved { get; set; }
    public bool CanEditOwn { get; set; }
    public bool CanEdit { get; set; }
    public bool CanDownload { get; set; }
    public bool RequiresApproval { get; set; }
    public bool CanApprove { get; set; }
    public bool CanSync { get; set; }
    public bool AgreedTerms { get; set; }
    public bool Deleted { get; set; }

    public Company Company { get; set; }
    public User CreatedBy { get; set; }
    public User ModifiedBy { get; set; }
    public ICollection<Asset> Assets { get; set; }
    public ICollection<Category> Categories { get; set; }
    public ICollection<Collection> Collections { get; set; }
    public ICollection<Comment> Comments { get; set; }
    public ICollection<LocalIntegration> LocalIntegrations { get; set; }
    public ICollection<Page> Pages { get; set; }
    public ICollection<Rating> Ratings { get; set; }
    public ICollection<Theme> Themes { get; set; }
    public ICollection<Group> MemberOf { get; set; }
    public ICollection<Category> ForbiddenCategories { get; set; }
    public ICollection<Page> ForbiddenPages { get; set; }
}

Now, because Lazy loading is disabled, I use Eager loading instead and if I have a look at this when I called this method:
    //
    // AJAX: /Users/Get
    public JsonResult Get()
    {
        try
        {
            using (var uow = new UnitOfWork<SkipstoneContext>())
            {
                var service = new UserService(uow, User.Identity.GetUserId(), this.CompanyId);
                var u = service.GetAll("MemberOf");

                return new JsonResult { Data = new { success = true, users = u } }; // Return our users
            }
        }
        catch (Exception ex)
        {
            return new JsonResult { Data = new { success = false, error = ex.Message } };
        }
    }

I can clearly see that only the Members navigation property is populated. The rest are null as expected.
If I try to pass u to my JsonResult, this is where the problem arises.
I get the error:

Self referencing loop detected for property 'CreatedBy' with type 'System.Data.Entity.DynamicProxies.User_E9B58CAAA82234358C2DE2AF8788D33803C4440F800EA8E015BE49C58B010EDF'. Path 'users[0]'.

In another post, I read that this happens because Json.Net tries to serialise and populate all navigation properties.
So, I created a new project and in that I created 2 models:
public class User
{
    public User()
    {
        this.Id = Guid.NewGuid().ToString();
    }

    public string Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string CreatedById { get; set; }

    public ICollection<Post> Posts { get; set; }
    public User CreatedBy { get; set; }
}

public class Post
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public string CreatedById { get; set; }

    public User CreatedBy { get; set; }
}

I would expect that running that, there would be a self referencing error because not only does User have many Post, it also has a User that created it.
So the method looks like this:
public JsonResult Get()
{
    try
    {
        var user = new User()
        {
            UserName = "moo",
            Email = "moo@moo.co.uk"
        };

        return new JsonResult { Data = new { sucess = true, user = user } };
    }
    catch (Exception ex)
    {
        return new JsonResult { Data = new { sucess = true, error = ex.Message } };
    }
}

again, this is identical (to my eyes) to the first project.
Anyway, when I run this, the project runs fine.
Can someone explain to me why this is happening and what I can do to solve it?

A: I assume that your navigation properties are actually marked virtual, otherwise EF won't try to lazy load them...
Just having a navigation property of the same type nested within an object's virtual properties does not make it self-referencing. When properties are null, empty collections, or when the JSON serializer can "find a way out" after walking through all of the entity's properties, then it is not self-referencing. Self-referencing means that I walk from User to Posts, then back to the same user, its posts again, and so on, infinitely.
To solve this, don't try to serialize entities. Instead, convert them first to viewmodels, then serialize the viewmodels.
public class UserViewModel
{
    public string Id { get; set; }
    public string UserName { get; set; }
    public string Email { get; set; }
    public string CreatedById { get; set; }
    public ICollection<PostViewModel> Posts { get; set; }
    public string CreatedByUserName { get; set; } // end self-referencing
}

public class PostViewModel
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Message { get; set; }
    public string CreatedById { get; set; }
    public string CreatedByUserName { get; set; } // end self-referencing
}

public JsonResult Get()
{
    try
    {
        using (var uow = new UnitOfWork<SkipstoneContext>())
        {
            var service = new UserService(uow, User.Identity.GetUserId(), this.CompanyId);
            var u = service.GetAll("MemberOf");
            var vm = Mapper.Map<UserViewModel[]>(u);
            return new JsonResult { Data = new { success = true, users = vm } }; // Return our users
        }
    }
    catch (Exception ex)
    {
        return new JsonResult { Data = new { success = false, error = ex.Message } };
    }
}


text:
Q: Адаптивная таблица с HTML-тегами в ячейках 1. Желаемое поведение
Положим, имеется такая таблица:

Хотелось бы, чтобы на устройствах с небольшой шириной экрана она выглядела следующим образом:

То есть слева — thead, справа — tbody.
я не знаю, как можно получить желаемое поведение, если в ячейках таблицы соседствуют ссылки и текст.
2. Цель
Адаптивные таблицы как на изображении выше. Необязательно задействовать плагин, о котором идёт речь ниже, и flexbox вообще. Подойдут любые решения для статических сайтов (где, как известно, используются только HTML/CSS/JavaScript).
3. Плагин responsive-tables
я нашёл плагин для адаптивных таблиц, использующий flexbox. Если в ячейке таблицы только ссылка или только текст, то получаю желаемое поведение. Проблемы возникают, когда в ячейке таблицы соседствуют ссылки и текст: таблица на устройствах с небольшим экраном выглядит вот таким уродливым образом (обратите внимание на запятые между ссылками):

Если ширина экрана ещё меньше, пользователю сайта содержимое ячейки не видно полностью:

4. MCVE

<!DOCTYPE html>

<title>KiraTitle</title>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-responsive-tables/css/responsive-tables.min.css">

            KiraFirstColumn
            KiraSecondColumn

            Kira — the greatest of all time, KiraText
            Kira — the greatest of all time, KiraText

Так отображается MCVE на устройствах с небольшой шириной экрана:

Если текст полностью заключён в ссылку, то он нормально переносится на следующую строку. Когда же в ячейке есть ссылка и текст, перенос осуществляется не так, как хотелось бы.
5. Не помогло
5.1. Свойства flex
Сначала почитал общие руководства пo flexbox. Попробовал, например, flex-wrap: wrap:

и flex-direction: column:

Читал о позиционировании flex элементов (flex items), пробовал свойства align-items, justify-content, но желаемого поведения получить не смог.
5.2. Манипуляции с flex контейнером
Последняя ячейка в таблице из MCVE представляет собой flex container:

Гуглил на английском и русском:

*

*Можно ли кастомно переопределить автоматические назначенные flex-элементы контейнера?

*Возможно ли объединить (merge, combine) элементы в контейнере?

*Как устранить разрыв между flex-элементами, в моём случае  и #text?

*Возможно ли задать элементам внутри контейнера что-то вроде display: inline?

Ответов применительно к моему случаю не нашёл. В каком направлении копать дальше, пока не понимаю.
6. Комментарии к возможным ответам

*

*Да, я понимаю, что вместо flexbox можно использовать display: block или display: grid. Пожалуйста, не пишите про это, если не знаете, как можно получить описанное в разделе 1 желаемое поведение при помощи данных технологий.

*Решение, работающее для ячейки с каким-то конкретными параметрами, но не работающее для прочих ячеек со ссылками и текстом — не лучший вариант.

A: Совсем забыл про этот вопрос. Скорее всего, задача уже решена, но может кто-то найдёт для себя что-то полезное разобравшись в коде:

let mediaQueryList = window.matchMedia("(max-width: 1000px), screen and (orientation: portrait)");

function fResizeCells(selector = "body", type = "reset") {
  let arr = [...document.querySelectorAll(selector)];
  let aRow = [...document.querySelectorAll(".good")];
  switch (type) {
    case "max":
      let nMax = Math.max(...arr.map((el) => el.clientWidth));
      arr.forEach((el) => (el.style.minWidth = `${nMax}px`));
      break;
    case "col":
      let nCol = aRow[0].children.length;
      for (let i = 0; i < nCol; i++) {
        let m = Math.max(...aRow.map((oRow) => oRow.children[i].clientWidth));
        aRow.forEach((oRow) => (oRow.children[i].style.minWidth = oRow.children[i].style.minWidth = `${m}px`));
      }
      break;
    default:
      arr.forEach((el) => (el.style.minWidth = el.style.maxWidth = ``));
      break;
  }
}

function screenTest(ev) {
  if (ev.matches) {
    fResizeCells(".char"); fResizeCells(".title", "max");
  } else {
    fResizeCells(".title"); fResizeCells(".char", "col");
  }
}
mediaQueryList.addListener(screenTest);
screenTest(mediaQueryList);
body { margin: 0; }

.table {
  margin: 0 auto;
  display: flex;
  flex-flow: column nowrap;
  padding: 5px;
  background-color: #f3efd6;
  color: #758e8b;
  font-family: sans-serif;
}

.good {
  display: flex;
  flex-flow: row nowrap;
  background-image: linear-gradient(#0002, #0000 10%, #0001 90%);
  box-shadow: 0 0 0 1px #758e8b;
}
.good:not(:last-child) { margin-bottom: 5px; }

.char {
  display: flex;
  flex-flow: column nowrap;
  box-shadow: inset 0 0 0 0px #758e8b;
}

.name {
  flex-basis: 50px;
  flex-grow: 2;
}

.author {
  flex-basis: 50px;
  flex-grow: 3;
}

.theme {
  flex-basis: 50px;
  flex-grow: 1;
}

.price-min {
  flex-basis: 50px;
  flex-grow: 2;
}

.title {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  padding: 0.5em;
  min-height: 2.5em;
  font-weight: bold;
  text-align: center;
  box-shadow: inset 0 0 0 1px #758e8b;
}

.cont {
  display: flex;
  flex-flow: row wrap;
  justify-content: start;
  align-items: center;
  padding: 0.5em;
  flex: 1;
  box-shadow: inset 0 0 0 1px #758e8b;
}
.author .cont {
  flex-flow: column nowrap;
  justify-content: center;
  align-items: start;
}

.good p { margin: 0; }

.im {
  font-family: Georgia, "Times New Roman", Times, serif;
  font-weight: bold;
  font-style: italic;
  color: #b78670;
}

.nw {
  white-space: nowrap;
  text-align: center;
}

img {
  display: block;
  width: 192px;
  height: 260px;
  object-fit: none;
  object-position: -303px -122px;
  box-shadow: 0 0 25px 0px #0007;
}

@media (max-width: 1000px),
screen and (orientation: portrait) {
  .good {
    display: flex;
    flex-flow: column nowrap;
  }
  .char {
    display: flex;
    flex-flow: row nowrap;
    box-shadow: inset 0 0 0 1px #758e8b;
  }
  .name, .author, .theme, .price-min {
    flex-basis: auto;
    flex-grow: 0;
  }
  .title {
    justify-content: start;
    align-items: start;
    min-height: max-content;
    box-shadow: inset 0 0 0 0px #758e8b;
  }
  .price-min .title {
    text-align: left;
  }
  .cont {
    box-shadow: inset 0 0 0 0px #758e8b;
  }
  .author .cont {
    flex-flow: column nowrap;
    align-items: start;
  }
}

No.

1999999

Название

Вымершие животные

Обложка

Автор

Дмитрий Лукашанец

Тематика

Как динозавры так и остальные

Версия

B

Минимальная
цена

999 800,50 RUB

No.

1999999

Название

Вымершие животные

Обложка

Автор

Kira — the greatest of all time, KiraText

Kira — the greatest of all time, KiraText

Тематика

Как динозавры так и остальные

Версия

B

Минимальная
цена

800

A: Если я не совсем верно понимаю задачу, то, пожалуйста, поправьте. Почему бы не реализовать адаптивность таблицы только с помощью CSS и дополнительного атрибута? Вот пример:

table {
  border-collapse: collapse; padding: 5px;
  background-color: #f3efd6; color: #758e8b; font-family: sans-serif;
}

table th, table td {
  padding: 10px; border: 2px solid #758e8b;
}

table td:nth-child(2), table td:nth-child(4) {
  font-family: Georgia, "Times New Roman", Times, serif; font-weight: bold; font-style: italic; color: #b78670;
}

img {
  display: block; width: 192px; height: 260px; object-fit: none; object-position: -303px -122px; box-shadow: 0 0 25px 0px #0007;
}

@media screen and (max-width: 760px) {
  table thead {
    position: absolute; overflow: hidden; width: 0px; height: 0px;
  }
  table th {
    border: none;
  }
  table th, table td {
    border: 1px solid #758e8b;
  }
  table tr {
    display: grid; grid-template-columns: repeat(1, 1fr);
    margin: 5px 5px 10px 5px;
    border: 1px solid #758e8b; border-bottom: 2px solid #758e8b;
  }
  table td {
    display: grid; grid-template-columns: repeat(2, 1fr);
    text-align: left;
  }
  table td::before {
    content: attr(data)":";
    font-weight: bold; font-style: normal; color: #758e8b;
  }
  table td:last-child {
    border-bottom: 0;
  }
}

      No.
      Название
      Обложка
      Автор
      Тематика
      Версия
      Минимальная цена

      1999999
      Вымершие животные

      Дмитрий Лукашанец
      Как динозавры так и остальные
      В
      999 800,50 RUB

      1999999
      Вымершие животные

Kira — the greatest of all time, KiraTextKira — the greatest of all time, KiraText

      Как динозавры так и остальные
      В
      800


text:
Q: Prove that for any $A \neq 0$ there is a matrix $B$ such that $A + B$ and $B$ have no eigenvalues in common. I am not sure how to begin thinking about this problem.  Could anyone provide a push in the right direction, or an explanation of what are the first things that go through their head when solving this?
Let $A \neq 0$ be an $n \times n$ complex matrix. Prove there is a matrix $B$ such that $A + B$ and $B$ have no eigenvalues in common.

A: If $A$ is a  a multiple of $I_n$, then we may take $B=A$.
So suppose that $A$ is not a multiple of $I_n$.
Clearly the problem is invariant by conjugation (i.e. for any
invertible matrix $P$, $(A,B)$ satisfies the conditions iff $(P^{-1}AP,P^{-1}BP)$ does).
Lemma. If $A$ is not a multiple of $I_n$, then there is a conjugate
of $A$ whose lower leftmost coefficient is nonzero.
Proof of lemma.  We can assume that $A$ is in Jordan normal form.
Since $A$ is not a multiple of $I_n$, either $A$ has at least two distinct eigenvalues or the form must have a one at
a nondiagonal position.
In the first case, suppose $Ae_{k}=\lambda_k e_k$ and $Ae_{l}=\lambda_le_l$ with $\lambda_k \neq \lambda_l$. In the initial basis $(e_1,\ldots,e_n)$, replace $e_l$ with $e_k+e_l$, and then reordering so that $e_k$ is put first and $e_k+e_l$ is put last, we are done.
In the second case, suppose there is a $1$ at the intersection of the $i$-th column with the $j$-th row, with $i\neq j$. Reordering the initial basis $(e_1,\ldots,e_n)$ so that $e_i$ is put first and $e_j$ is put last,we are done.
So we can assume without loss of generality that $A$ has a nonzero
lower leftmost coefficient (let us call it $a$) :
$$
A=\left(\begin{array}{cccc}
\ldots & \ldots & \ldots & \ldots \\
\ldots & \ldots & \ldots & \ldots \\
\ldots & \ldots & \ldots & \ldots \\
a & \ldots & \ldots & \ldots \\
\end{array}\right)
$$
Now, consider the matrix all of whose terms are zero except on a pushed diagonal :
$$
B=\left(\begin{array}{cccc}
0 & b_1 & 0 & 0 \\
0 & 0 & \ddots & 0 \\
0 & 0 & 0 & b_{n-1} \\
0 & 0 & 0 & 0 \\
\end{array}\right)
$$
Then $B$ is nilpotent : its only eigenvalue is $0$.
On the other hand, the determinant of $A+B$ is a polynomial in $b_1,\ldots,b_{n-1}$,
and the coefficient in $b_1\ldots b_{n-1}$ is exactly $a$, which is a nonzero
coefficient. So the polynomial is nonzero, and for a suitable choice
of $(b_1,\ldots,b_{n-1})$ its value will be nonzero. Then $A+B$ will be
invertible, solving your problem.


text:
Q: Make modification and decide where to put an element before his creation - using angularjs with directives I'm trying to detect the creation of an element (an new added element) and do an action on this element (modification) and decide where to put it.
The element is added by an anguler biding items and I use a new directive:
My page HTML:

    <input type="text" ng-model="url" ng-keyup="$event.keyCode == 13 ? addItem(url) : null" class="form-control" id="myinputurl" autofocus="autofocus" autocomplete="on" placeholder="Type URL">

My section

      <content-item ng-repeat="item in items" itemActive="{{item.active}}" type="section"></content-item>

My list

      <content-item ng-repeat="item in items" itemActive="{{item.active}}" type="list"></content-item>

Add the item in a items scope:
 $scope.addItem = function(myurl) {

var lastChildId = $("ul li").length;
var vall = lastChildId + 1;
var idItem = "item" + vall;

angular.forEach($scope.items, function(p) {
  p.active = false; //set them all to false
});

//var trustedUrl = trustSrc(myurl);

$scope.items.push({
  id: idItem,
  item: ' Test for StackOverFlow ',
  active: true
});

}
My directive:
     app.directive('contentItem', function() {
  return {
    restrict: "EA",
    scope: false,
    template: function(elem, attr) {

      var template = 'ErrorFail';

      var type = attr.type;

      if (type === "section") {
        if (attr.itemActive) {
          template = '{{item.itemm}}';

        }
      } else {
        template = '
{{item.itemm}}
';

      }
    return template;
    }

  }
});

Can someone help me please ?? This is Plunker Link


text:
Q: Geoserver: how to filter a layer related to another layer? I have the following problem:
I have 2 vector layers from PostGIS datastores: "firepoints" and "threats". The corresponding tables "firepoints" and "threats" have IDs and other attributes. They are related via a foreign key "id_firepoint" in "threats" table. One threat can have multiple firepoints, but one firepoint can have only one threat.
What I need to do is to filter WMS layers in Openlayers using CQL filters: first I want to filter the "firepoints" layer using some attribute ("satellite", for example) and then apply the derived IDs to filter "threats" layer using the "id_firepoint" attribute.
The problem is that I don't know how to derive the list of IDs of filtered "firepoints".
I have tried using the Cross-layer filtering with "querylayer" module, but I don't think that I understood how to use it correctly.
This is the filter that I try to apply to the "GSS:threats" layer:

id_firepoint IN queryCollection('GSS:firepoints','id','satellite =
  AQUA')

Is there any way to filter a layer related to another layer using dynamically changing attributes?


text:
Q: how to filter users by assigned license using ms-graph I'm trying this request:
https://graph.microsoft.com/v1.0/users?
$filter=assignedLicenses/any(d:d/skuid eq 28d45cd1-ad8b-15cd-a9e1-52e6a5c24328)

But I get this error:
BadRequest - ')' or ',' expected at position 71 in 'assignedLicenses/any(d: d/skuid eq 28d45cd1-ad8b-15cd-a9e1-52e6a5c24328'.
Am I doing anything wrong? is this query possible?

A: Just an update that this is now a supported API call.  The correct syntax is:
https://graph.microsoft.com/v1.0/users?$filter=assignedLicenses/any(x:x/skuId eq e578b273-6db4-4691-bba0-8d691f4da603)

e578b273-6db4-4691-bba0-8d691f4da603 is Faculty A3 SKU in this example

A: In general, only those properties where the documentation says "supports $filter" can be filtered.
E.g. on the user object, accountEnabled can be filtered.
Since the assignedLicenses property doesn't say it, and the assignedLicense resource type doesn't have it documented on the skuId property, I don't think you can perform that query.

A: I tried something similar on "beta" version of GRAPH API. I need to filter by assignedPlan.
https://graph.microsoft.com/beta/users?&$filter=assignedPlans/any(d:d/service eq 'SharePoint')
and this is the error message which I got:
{
"error": {
    "code": "Request_UnsupportedQuery",
    "message": "Complex query on property assignedPlans is not supported.",
    "innerError": {
        "request-id": "c3fad564-e61d-4066-8bef-548afghtyu",
        "date": "2018-12-10T16:43:36"
    }
}
}

So i guess that there is no option to prefilter users by assignedLicenses or Plan.
At least not yet...

A: You can try this one
GET https://graph.microsoft.com/v1.0/users?$filter=assignedLicenses/any(s:s/skuId eq 28d45cd1-ad8b-15cd-a9e1-52e6a5c24328)

For more reference: https://learn.microsoft.com/en-us/graph/query-parameters#filter-using-lambda-operators


text:
Q: Verification of a function using chain rule and verifying it using sympy, How to plot this function without getting errors? I am trying to verify my results using sympy in the context of a plot. My question to myself is as follows: Use the chain rule to find these derivatives. Verify your results with sympy. I am getting this error message for my code.
# Use the chain rule to find these deriviatives. Verify your results with sympy.
# ℎ()=(sin^)^  for ,∈ℕ

x, k, m = symbols("x k m")
def h(x):
  return (sin(x**k))**m
def dhdx(x):
  return diff(h(x), x)

x = np.linspace(-2,2,100)
plt.plot(x,h(x),label='h(x)')
plt.plot(x,dhdx(x),label='dhdx(x)')
plt.legend()
plt.show()

And this is the error im getting:
/usr/local/lib/python3.7/dist-packages/sympy/core/cache.py in wrapper(*args, **kwargs)
     71             try:
---> 72                 retval = cfunc(*args, **kwargs)
     73             except TypeError:

TypeError: unhashable type: 'numpy.ndarray'

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
7 frames
TypeError: unhashable type: 'numpy.ndarray'

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/sympy/functions/elementary/trigonometric.py in eval(cls, arg)
    303             return arg._eval_func(cls)
    304
--> 305         if arg.could_extract_minus_sign():
    306             return -cls(-arg)
    307

AttributeError: 'ImmutableDenseNDimArray' object has no attribute 'could_extract_minus_sign'


text:
Q: Configure endpoints for Facebook Realtime Updates in MVC I want to implement Realtime Updates for my Facebook MVC application. I created it from template in Visual Studio.
I'm following Facebook documentation and this blog post.
Template has already some boilerplate code for UserRealtimeUpdateController. How to configure endpoints to listen to subscriptions, and what should I put as my callback, when I create new Realtime Update Subscription?

A: Endpoints are defined in WebApiConfig class in App_Start folder.
public static void Register(HttpConfiguration config)
{
   config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
   );
}

So, by default the callback URL should be something like:
http://yourservername.com/api/userrealtimeupdate


text:
Q: Error "you cannot call a method on a null-valued expression" when running script as scheduled task This script runs fine in PowerShell. However, when I run it with Task Scheduler it fails with

You cannot call a method on a null-valued expression on PowerShell script.

$ErrorActionPreference = "SilentlyContinue"
$global:reports
$global:strdate
$global:ReportName
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=DWPROD;Database=DP_DW;Integrated Security=True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = " Select
   email = 'user@example.com'
  ,username='example\user'
  ,password='password'
  ,ReportName = 'LaborAnalysis Kronos Daily'
  ,ReportFileName = 'LaborAnalysisDaily-'
  ,ReportDate = CONVERT(varchar,getdate()-2,101)
  ,Sharepoint = 'http://intranet.shccs.com/shcsites/toolbox/D  Labor/Daily Reports/'"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$reportinfo = $DataSet.Tables[0]
$SqlConnection.Close()

#ARRAY TO SAVE Report Criteria
$a = 0
foreach ($reportparam in $reportinfo.Rows)
{
  $ReportName = $reportparam['ReportName']
  $ReportFileName = $reportparam['ReportFileName']
  $ReportDate = $reportparam['ReportDate']
  $Sharepoint = $reportparam['Sharepoint']

  #Write-Host $ReportName + $ReportDate
  Write-Host $ReportDate
  #Write-Host $Sharepoint
  #Write-Host (Get-date).AddDays(-1)
  #Write-Host $(get-date -f yyyy-MM-dd)
  #--------------------------------------------------------------
  # report parameters
  #--------------------------------------------------------------
  $inputParams = @{
    "prmRptDate" = '11/16/2016'
  }
  #--------------------------------------------------------------
  # add assembly
  #--------------------------------------------------------------
  Add-Type -AssemblyName "Microsoft.ReportViewer.WinForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
  #Add-Type -AssemblyName -Path 'C:\Scripts\itextsharp.dll'
  #[System.Reflection.Assembly]::LoadFrom('\\itextsharp.dll') | Out-Null
  #--------------------------------------------------------------
  # display calculated month end date
  #--------------------------------------------------------------
  $startTime = Get-Date
  Write-Host ("=" * 80)
  Write-Host "Generating Reports"
  Write-Host "Start Time: $startTime"
  Write-Host ("=" * 80)

  #--------------------------------------------------------------
  # create timestamped folder
  # where we will save our report
  #--------------------------------------------------------------
  $dt = Get-Date -Format "yyyy-MMM-dd hhmmtt"
  $rptdt = Get-Date -Format "yyyy-mm-dd"
  $baseFolder = "C:Scripts"
  Remove-Item "C:\Scripts\Labor\*"

  $rv = New-Object Microsoft.Reporting.WinForms.ReportViewer
  #--------------------------------------------------------------
  # report Server Properties
  #--------------------------------------------------------------
  $strdate = $ReportDate -replace "/", "-"
  $reports = $ReportFileName + $strdate + "pdf";

  $rv.ServerReport.ReportServerUrl = "http://dpweb01.shccs.com/ReportServer"
  $rv.ServerReport.ReportPath = "/Labor/"+ $ReportName
  $rv.ProcessingMode = "Remote"
  #Write-Host $ReportName
  #--------------------------------------------------------------
  # set up report parameters
  #--------------------------------------------------------------
  $params = $null

  #create an array based on how many incoming parameters
  $params = New-Object 'Microsoft.Reporting.WinForms.ReportParameter[]' $inputParams.Count

  $d = 0
  foreach ($p in $inputParams.GetEnumerator())
  {
    $params[$d] = New-Object Microsoft.Reporting.WinForms.ReportParameter($p.Name, $p.Value, $false)
    $d++
  }
  # set the parameters
  $rv.ServerReport.SetParameters($params)
  $rv.ShowParameterPrompts = $false
  $rv.RefreshReport()
  $rv.ServerReport.Refresh()

  #--------------------------------------------------------------
  # set rendering parameters
  #--------------------------------------------------------------
  $mimeType = $null
  $encoding = $null
  $extension = $null
  $streamids = $null
  $warnings = $null

  #--------------------------------------------------------------
  # render the SSRS report in PDF
  #--------------------------------------------------------------
  $bytes = $null
  $bytes = $rv.ServerReport.Render("PDF",
           $null,
           [ref] $mimeType,
           [ref] $encoding,
           [ref] $extension,
           [ref] $streamids,
           [ref] $warnings)

  #--------------------------------------------------------------
  # save the report to a file
  #--------------------------------------------------------------
  $fileName = "C:/Scripts/Labor/" + $reports
  $fileStream = New-Object System.IO.FileStream($fileName, [System.IO.FileMode]::OpenOrCreate)
  $fileStream.Write($bytes, 0, $bytes.Length)
  $fileStream.Close()
  $fileStream.Dispose();
  $reportdone = $reportname + " " + $(Get-Date -f yyyy-MM-dd) + ".PDF"
  #Write-Host $reportdone

  #--------------------------------------------------------------
  # Copy FIlES to Sharepoint
  #--------------------------------------------------------------
  # Set the variables
  $destination = "http://intranet.shccs.com/shcsites/toolbox/D  Labor/Daily Reports/"
  $File = Get-ChildItem "C:\Scripts\Labor"
  $FilePath = $File.FullName
  Write-Host $FilePath
  # Since we're doing this remotely, we need to authenticate
  $securePasssword = ConvertTo-SecureString "password" -AsPlainText -Force
  $credentials = New-Object System.Management.Automation.PSCredential ("example\user", $securePasssword)

  # Upload the file
  $webclient = New-Object System.Net.WebClient
  $webclient.Credentials = $credentials
  $fileupload = $destination + $File
  Write-Host $fileupload
  $webclient.UploadFile($fileupload, "PUT", $FilePath)

  #$file = "c:\Scripts\file.txt"
  #$FilePath | Add-Content -Path $file
  #$fileupload | Add-Content -Path $file
  $a++
}
Send-MailMessage -To "user <user@example.com>" -From "user <user@example.com>" -Cc "user <user@example.com>" -Subject "Daily Labor Reports are Complete" -SmtpServer "relay.example.com" -Body "Labor Reports have been uploaded"

#--------------------------------------------------------------
# LOG ERROS
#--------------------------------------------------------------
$LaborLogs = "c:\Scripts\LaborLogs.txt"
#$error[0].Exception | gm

Add-Content $LaborLogs ("=" * 80)
Add-Content $LaborLogs $startTime
Add-Content $LaborLogs $strdate
Add-Content $LaborLogs $error[0]
Add-Content $LaborLogs ("=" * 80)


text:
Q: How to sum repeated elements in an array in JavaScript? I have two arrays.  The first is array_impuestos which is the tax names.  The second is array_impuestos_valor which contains the corresponding tax values. The tax value for the tax name at index 0 of array_impuestos would be the value at index 0 of array_impuestos_valor.
I need to detect which elements are repeated in array_impuestos and sum the corresponding values in array_impuestos_valor.
For example, 'iva.21%' appears twice in array_impuestos corresponding to both '21' and '10.5' in array_impuesto_valor.
I need to sum those last 2 values.

array_impuestos = ["iva.21%", "irfp.-7%", "iva.21%"];
array_impuestos_valor = ["21", "3.5", "10.5"];

array_impuestos.forEach(function (elemento1, indice1, array1) {
  nombre1 = elemento1;
  indice1 = indice1;
  array_impuestos_valor.forEach(function (elemento2, indice2, array2) {
    if (indice1 == indice2) {
      impuesto_repetido = (array_impuestos.indexOf(elemento1) === indice1);
      if (impuesto_repetido == false) {
        //I don't know how to continue sincerely
        console.log(nombre1 + '  ' + elemento2);
      }
    }
  });
});

A: You can do something like this, group the array_impuestos_valor values according to their corresponding array_impuestos values.

let array_impuestos=["iva.21%","irfp.-7%","iva.21%"];
let array_impuestos_valor=["21","3.5","10.5"];

const hash_sum = {};
for(let i=0; i<array_impuestos.length; i++){
    if(!hash_sum[array_impuestos[i]])
    hash_sum[array_impuestos[i]] = +array_impuestos_valor[i];
    else
    hash_sum[array_impuestos[i]] += +array_impuestos_valor[i];
}

console.log(hash_sum);

array_impuestos = [];
array_impuestos_valor = [];

// 1st method
for(const x in hash_sum){
    array_impuestos.push(x);
    array_impuestos_valor.push(hash_sum[x]);
}

console.log(array_impuestos, array_impuestos_valor);

// 2nd method
console.log(Object.keys(hash_sum), Object.values(hash_sum));

A: Here's a more functional solution:

const nombres = ['iva.21%', 'irfp.-7%', 'iva.21%'];
const valores = ['21', '3.5', '10.5'];

const impuestos = nombres.reduce((impuestos, nombre, i) => {
  impuestos[nombre] = (impuestos[nombre] || 0) + +valores[i];
  return impuestos;
}, {});

console.log(impuestos); // { 'iva.21%': 31.5, 'irfp.-7%': 3.5 }

A: this should work (making use of the concept of object in JS to build a map)

let array_impuestos=["iva.21%","irfp.-7%","iva.21%"];
let array_impuestos_valor=["21","3.5","10.5"];
let res = {};
for(let  i = 0; i < array_impuestos.length; i++)
     res[array_impuestos[i]] = +array_impuestos_valor[i] + (res[array_impuestos[i]] ? res[array_impuestos[i]] : 0)
console.log(res)

A: let array_impuestos=["iva.21%","irfp.-7%","iva.21%"];
let array_impuestos_valor=["21","3.5","10.5"];

for(let i=0;i<array_impuestos.length;i++){
   console.log(calculation(array_impuestos[i]))
}

function calculation(key){
    let arr = []
    let sum = []
    let total = 0
    array_impuestos.forEach(function(item,index){
        if(item == key) {
            arr.push({key:item,index:index})
        }
    })

for(let item of arr){
    sum.push(array_impuestos_valor[item.index])
}

//performing sum
for(let i=0;i<sum.length;i++){
    total += parseFloat(sum[i])
}
return total
}


text:
Q: Android: When a service is killed, how can we persist the service state for later restoration? We have created an app that is essentially a timer/stopwatch with some decked out features.  We defined a service that ticks the clock and alerts listeners (activities, etc.) who are subscribed to certain timer events.
We would like to be able to save the state of the timer/stopwatch (elapsed seconds, time until next event, user-provided config etc.) whenever android kills our service (for memory recollection), and then restore the state of the service when the app is restored by the user.  For us, this means possibly preserving and restoring objects and their state.  We have lots of composition in our service.  Basically, our service is composed of all our timer models, of which die when the service dies.
What strategies are there to persist the state of the service?  PreferencesManager probably isn't robust enough for our purposes, though it might be.  Can we rely on the Service onDestroy()  method to save state (say in SQLite)?  If android decides to kill our process, is it even guaranteed that the service onDestroy() will be called?
Thank you!

A:
We defined a service that ticks the clock and alerts listeners (activities, etc.) who are subscribed to certain timer events

You do not need to have a service running all the time, watching the clock tick. This approach is user-hostile, as it ties up system RAM for no good reason. Use AlarmManager to get control at "certain timer events", and keep your service out of memory for the rest of the time.

We would like to be able to save the state of the timer/stopwatch (elapsed seconds, time until next event, user-provided config etc.)

Do not persist "elapsed seconds". Persist the time when the timer/stopwatch began. Elapsed seconds is then a matter of subtraction.
Do not persist "time until next event". Persist the time of the next event.
These values do not continuously change, and therefore can be persisted when the timers are started or other major lifecycle events in the life of the timer.

What strategies are there to persist the state of the service?

Use a database, SharedPreferences, or a file format of your own choosing.

Can we rely on the Service onDestroy() method to save state (say in SQLite)?

No.

If android decides to kill our process, is it even guaranteed that the service onDestroy() will be called?

It is not guaranteed to be called.


text:
Q: Chrome 109 / Edge 109 howto access localhost domains in the last days chrome and edge stopped working to access localhost domains o my windows machine. Firefox is still able to, so I guess it has something to do the browser engine.
My setup: I have a vm started with vagrant on hyper-v. Inside the vm is my apache webserver.
On my windows 11 operating system the hosts file points my local development websites to the ip of the vm. This was working for the last years without any problem.

*

*DNS over https is not enable in Edge or Chrome.

*I already have tried using different local domains like localhost or .local. without success

*I have tried ipconfig /flushdns without success

*I reinstalled Chrome without success

My host file is
172.28.148.95 workspace.localhost.de
127.0.0.1 workspace.localhost.de

What can I do, that Edge and Chrome can access local domains?


text:
Q: LUIS intents not relating to entities We want to create a chatbot with about 80 intents, where most of them are just questions with direct answers related to HR (benefits, payroll, etc). It could be done with QnA maker but we decided using LUIS and utterances to have the option to query entities in the future if we need to.
I have tried to create some entities to lift the score of some intents, for example, we have a benefit question about inscriptions to sports in our company:
Utterance:
How can I enroll in soccer?
What steps do I have to register in tennis lessons?
...
So I have created two entities, one for "ActivityType" (soccer, tennis, etc), and other for "Enrollment" (register, enrollment, etc). The later is more as a synonym variable so I don't have to write that many utterances.
Then the utterances translates into:
How can I {Enrollment} in {ActivityType}
What steps do I have to {Enrollment} in {ActivityType} lessons?
These are my questions:
1) "Enrollment" entity is used to avoid creating that many utterances, does it make sense here or there is something better in LUIS for that?
2) I have tested the system and in some questions, it picks up the two entities (enrollmnet and activitytype) which are only present in a specific intent, but then it assigns in the top another intent which doesn't have at all those entities. I would expect the entities to somewhat lift the probability of selecting the intents that are using it (in this case, there is only one using them, so it should be pretty obvious but is not being selected)
Any help will be greatly appreciated :)


text:
Q: Convert a 32bit integer into 4 bytes of data in javascript I was asked to convert the integers to 32-bit binary numbers.
So is used integer.toString(2) and got the required value in 32-bit binary format of 0'sand 1's. But actually what I was asked to do is convert the integer into 4 bytes of data.
I am unable to get the output as suggested. I have used integer.toString(8), integer.toString(16). but of no use.
Example:
 num=1065489844
 num.toString(2) //Output: 111111100000100001010110110100
 num.toString(8) //Output: 7740412664

Please let me know, where I am lacking.

A: Now you can use ArrayBuffer and DataView. They are native so the performance will be much better if you need to use it very often.
function toBytesInt32 (num) {
    arr = new ArrayBuffer(4); // an Int32 takes 4 bytes
    view = new DataView(arr);
    view.setUint32(0, num, false); // byteOffset = 0; litteEndian = false
    return arr;
}

equals to
function toBytesInt32 (num) {
    arr = new Uint8Array([
         (num & 0xff000000) >> 24,
         (num & 0x00ff0000) >> 16,
         (num & 0x0000ff00) >> 8,
         (num & 0x000000ff)
    ]);
    return arr.buffer;
}

which use javascript bitwise operators to achieve that.

A: if you need a hex format output, here is the code.
/* Convert value as 8-bit unsigned integer to 2 digit hexadecimal number. */

function hex8(val) {
    val &= 0xFF;
    var hex = val.toString(16).toUpperCase();
    return ("00" + hex).slice(-2);
}

/* Convert value as 16-bit unsigned integer to 4 digit hexadecimal number. */

function hex16(val) {
    val &= 0xFFFF;
    var hex = val.toString(16).toUpperCase();
    return ("0000" + hex).slice(-4);
}

/* Convert value as 32-bit unsigned integer to 8 digit hexadecimal number. */

function hex32(val) {
    val &= 0xFFFFFFFF;
    var hex = val.toString(16).toUpperCase();
    return ("00000000" + hex).slice(-8);
}

var num = 1065489844;
console.log("0x" + hex32(num)); // will output 0x3F8215B4

A: SEIAROTg's answer does not output a string. I have theroughly tested with both positive and negative numbers and this code will give you a 4 byte string output representing the number in big endien format(2's compliment 0xFFFFFFFF = -1).
var toBytesInt32=function(num) {
    var ascii='';
    for (let i=3;i>=0;i--) {
        ascii+=String.fromCharCode((num>>(8*i))&255);
    }
    return ascii;
};

by the way if you want to go the other way around you can use
var fromBytesInt32=function(numString) {
    var result=0;
    for (let i=3;i>=0;i--) {
        result+=numString.charCodeAt(3-i)<<(8*i);
    }
    return result;
};

to convert a 4 byte string to an integer


text:
Q: SSD compatibility Alienware Area-51 R2 Computer parts are really not my speciality and I am trying to extend my Alienware Area-51 R2 from 2015 with an additional SSD. However I am bit lost with the technical terms and how they fit together. In the specifications of the Alienware Area-51 R2 I see there is
M2
    • One M.2 card slot for WLAN and Bluetooth
    • Storage Four SATA ports

I am thinking about buying an SSD that has this: Some Vendor XXX (1000GB, M.2 2280)
I read in a thread about someone complaining that his M.2 SSD wont work with the Alienware Area 51 R2. I am now confused, if this should work or not. Are there requirements regarding the motherboard or some drivers that could mean I have a slot for M.2 2280 SSD but it wont work with any M.2 2280 SSD?


text:
Q: Worklight Quality Assurance https setup I recently setup https on a Worklight Quality Assurance virtual appliance. I provided the certificate signed by my CA following the directions on the IBM Knowledge Center:
http://www-01.ibm.com/support/knowledgecenter/SSFRDS_6.0.0/com.ibm.mqa.install.doc/topics/t_confighttps.html?lang=en
and configured the appliance to accept connection only in https (I disabled port 80 through the firewall configuration wizard).
However, when I try to connect on https, the certificate retrieved by the browser is the default certificate issued by the appliance.
Is this correct? I was expecting the browser to retrieve the certificate I just imported.
Many thanks,
Marco

A: The best way to check if the certificate has been updated properly is to check the modified date of the cert and the key.


text:
Q: Many programs notify me that "grep/sed/uname/... not found"; some run, some don't. My system(?) path is damaged, how do I go about a diagnosing it? Some manifestations of this problem: macports won't install, MATLAB won't run, BTT works but incessantly spams me with " not found" popups, and emacs shell does not work.
My interactive shell PATH is fine, so this is my '/etc/paths' file:
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/Users/sambo/bin
where that last one is my own personal scripts. Could I have damaged it just from appending? Anyways, that's problem and help would be appreciated.
EDIT: With echo -e ${PATH//:/\\n}, I get
/Users/sambo/.rvm/gems/ruby-1.9.2-p290/bin
/Users/sambo/.rvm/gems/ruby-1.9.2-p290@global/bin
/Users/sambo/.rvm/rubies/ruby-1.9.2-p290/bin
/Users/sambo/.rvm/bin
/usr/bin
/bin
/usr/sbin
/sbin
/usr/local/bin
/Users/sambo/binsr/sbin
/sbin
/usr/X11/bin
/usr/texbin
â
/Users/sambo/sox
/Users/sambo/bin
/usr/texbin

/Users/sambo/.rvm/gems/ruby-1.9.2-p290/bin:/Users/sambo/.rvm/gems/ruby-1.9.2-p290@global/bin:/Users/sambo/.rvm/rubies/ruby-1.9.2-p290/bin:/Users/sambo/.rvm/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/Users/sambo/binsr/sbin:/sbin:/usr/X11/bin:/usr/texbin:â:/Users/sambo/sox:/Users/sambo/bin:/usr/texbin

*

*is it OK for these ruby bins to be upstream of the system bins?

*could that junk cause any trouble?

A: Your question is unclear as it seems to ask several things. However the issue re launching from the Dock can be answered.
The Dock does not call a shell. .profile and other startup scripts are only run when Terminal.app or similar starts a shell or you run a shell script via launchd etc.
To change the path used for Apps launched from the Dock, Finder or other GUI then you need to change the path your Workspace uses this is in ~/.MacOSX/environment.plist
e.g. mine is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>WAFDIR</key>
  <string>/Users/mark/src/third_party/git-svn/waf</string>

  <key>PATH</key>
  <string>/Users/mark/bin:/Users/mark/env/bin:/Users/mark/usr/local/bin:/usr/local/bin:/opt/local/bin:/usr/local/git/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/X11R6/bin:/usr/libexec/binutils:</string>
</dict>
</plist>

Also have a look at this question.