text:
Q: Alternative to Dark Energy If Black Holes consume mass and re radiate it in the form of massless photons the mass of the universe is declining.  Could this explain the accelerating expansion of the universe without the necessity of invoking Dark Energy?

A: No, you can't explain accelerating expansion in this way. There are three separate problems with your proposed explanation.
First of all, mass isn't relevant. In General Relativity, gravity and the expansion of the universe depends on energy (and momentum), not on mass. The massless photons carry away energy, and the energy of the hole decreases by the same amount, so energy is conserved. (Momentum is also conserved.)
Second, the energy and momentum of photons does gravitate in a different way than the energy and momentum of black holes. But both cause a deceleration of the expansion, not an acceleration.
Third, all black holes that we know of are not radiating any net photons, because their Hawking temperature is far lower than the temperature of the cosmic microwave background. They are all absorbing photons.

A: Most black holes are still consuming far more ambient light than they are radiating through Hawking radiation. More fundamentally, energy has the same effect on the curvature of spacetime whether it is light energy or mass energy, and black holes do not change the total amount. So no, the acceleration of Universal expansion must be explained some other way.

A: This won't work. Make sure you understand what dark energy is.

In standard cosmology, there are three components of the universe: matter, radiation, and dark energy. Matter is anything whose energy density scales with the inverse cube of the scale factor, i.e., $\rho \propto a^{-3}$, while radiation is anything which scales to the inverse fourth power of the scale factor ($\rho \propto a^{-4}$). This can be understood intuitively: for an ordinary particle in a cube-shaped box, doubling the length of an edge of the box decreases the density (and hence energy density) by a factor of eight ($2^3$). For radiation, the decrease in energy density is greater, because an increase in spatial distance also causes a redshift.
The final component, dark energy, is an intrinsic property of space, and so has a constant energy density regardless of the volume under consideration ($\rho \propto a^0$). Thus, unlike ordinary matter, it does not get diluted with the expansion of space.

Photons are radiation - their energy density scales to the inverse fourth power of the scale factor. Dark energy is fundamentally different from photons, and cannot be made up of it.


text:
Q: Why am I getting this error? Fatal error: Uncaught Error: Call to a member function execute() on boolean in This is my php code:
<?php
$group = filter_input(INPUT_POST, 'groupchooser', FILTER_UNSAFE_RAW,
FILTER_FLAG_STRIP_LOW);

$db = mysqli_connect("localhost", "test", "password", "id3234074_posts");

$stmt = $db->prepare('SELECT TOP 10 titles, comments * FROM $group ');

$stmt->execute(array(':id' => $_GET['id']));

$row = $stmt->fetch();

if($row['id'] == ''){
header('Location: ./');
exit;
}
?>

I have have tried without using prepare and it still gets me a similar error about the boolean.

A: You have three mistakes in your code:
SELECT TOP X is SQL Server syntax, but judging by the API in your code, you're using MySQL, so you need to use LIMIT X.
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10');

Further, you're biding parameters to the query via execute(), but have no placeholders in it. So, you need to either add them with bind_param() (for example, a WHERE clause), or remove the parameters from execute():
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10 WHERE id = ?');

$stmt->bind_param("i", $_GET["id"]);

$stmt->execute();

Or
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10');

$stmt->execute();

Lastly, you have a couple of fields you're selecting and the wildcard *. You can have this:
$stmt = $db->prepare('SELECT titles, comments FROM $group LIMIT 10');

to select titles and comments, or this
$stmt = $db->prepare('SELECT * FROM $group LIMIT 10');

to select all the fields in the $group table.

Sidenote: you're directly embedding client data into your query, and  filter_input() isn't helping. You need to be absolutely, positively, 100% sure of what you're inputting into you're query. A safer option could be to have a list of possible groups, and only allow the user to pick one of them:
$group = filter_input(INPUT_POST, 'groupchooser', FILTER_UNSAFE_RAW,
FILTER_FLAG_STRIP_LOW);
$groups = ["group1", "group2"];
if (!in_array($group, $groups)) {
    throw new Exception("Invalid group");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift - SKShapeNode from user-drawn image (using CGMutablePath()) everyone!
I bet this is a simple fix but I can't wrap my mind around it. In the game I'm making, I want a user to be able to draw something (a squiggle, a circle, etc.) and make an SKNode (SpriteNode, ShapeNode, etc.) from that drawing. I've almost got it working, but when I draw on the screen, it starts the drawing at a random point in the top right of the screen and flips my finger motions vertically (but not horizontally). To truly get an idea of my problem you might have to see it, so here's my GameScene.swift code:
import SpriteKit
import GameplayKit

class GameScene: SKScene {

var lastPoint = CGPoint.zero
var swiped = false

var ref = CGMutablePath()
var lineDrawing = SKShapeNode()

override func didMove(to view: SKView) {

    lineDrawing = SKShapeNode(rectOf: self.frame.size)
    lineDrawing.lineWidth = 10
    lineDrawing.position = CGPoint.zero
    self.addChild(lineDrawing)

}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false

    if let touch = touches.first {

        lastPoint = touch.location(in: self.view)

    }
}

func drawLineFrom(fromPoint: CGPoint, toPoint: CGPoint) {

    ref.move(to: fromPoint)
    ref.addLine(to: toPoint)

    lineDrawing.path = ref
    lineDrawing.lineCap = CGLineCap.round
    lineDrawing.lineWidth = 10
    lineDrawing.strokeColor = SKColor.black//maybe .strokeTexture for chalk

}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true
    if let touch = touches.first {
        let currentPoint = touch.location(in: view)
        drawLineFrom(fromPoint: lastPoint, toPoint: currentPoint)

        // 7
        lastPoint = currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    if !swiped {
        // draw a single point
        drawLineFrom(fromPoint: lastPoint, toPoint: lastPoint)
    }

}

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}
}

I would really appreciate some help on this issue :) Thanks so much in advance!


text:
Q: Dynamically highlight td in a table Problem
How to highlight dynamically a selected td?
Codepen
Pen here
Code
The map is a 2d array random generated, something like this:
map = [[1,1,1,1,0],
       [1,0,0,0,0],
       [1,0,1,1,1],
       [1,0,0,0,1],
       [1,1,1,0,1]]

I can move the player 3 squares per turn and, one of this squares is his actual position. I used this function to call the movement:
function movements(character){
    var possibleMovement=3;
    let coord=character.actualPosition;
        let row = $($("#tableGame tr")[coord.row]);
        let cell = $($("td", row)[coord.cell]);

    forward(row, cell, possibleMovement, character);
    backward(row, cell, possibleMovement, character);
    goUp(row, cell, possibleMovement, character);
    goDown(row, cell, possibleMovement, character);
};

and with the functions below I try to highlight the cells where the character can actually move.
function forward(row, cell,possibleMovements, character){
    for(var i = 0; i<possibleMovements; i++){
        cell = $($("td", row)[coord.cell+i]);
        var tile = $(".tile", cell).addClass('possibleSteps');
    };
};

function backward(row, cell, possibleMovements, character){
    for(var i = 0; i>=possibleMovements; i--){
        console.log('sei qua');
        cell = $($("td", row)[coord.cell+i]);
        var tile = $(".tile", cell).addClass('possibleSteps');
    };
};

Task
I need to highlight the tiles near the character:

*

*Two tiles above character.actualPosition

*Two tiles below

*Two tiles at his right

*Two tiles at his left

These are the two " testing function "
function forward(row, cell,possibleMovements, character){
    for(var i = 0 ; i<possibleMovements; i++){
        cell = $($("td", row)[coord.cell +i]);
        var tile = $(".tile", cell).addClass('possibleSteps');
        console.log([coord.row] + "<<<row" + [coord.cell+i] + "<<<cell");
    };
};

function backward(row, cell, possibleMovements, character){

    possibleMovements= possibleMovements*-1;

    for(var i = 0 ; i>possibleMovements; i--){
        cell = $($("td", row)[coord.cell+i]);
        var tile = $(".tile", cell).addClass('possibleSteps');
        console.log([coord.row] + "<<<row" + [coord.cell-i] + " <<<cell");
    };
};

A: Finally i found an answer. I want to say thanks to this post  because it helps me a lot to find a solution that works.
The final functions to highlight the tiles near the character are these
function movements(){
    let possibleMovement=3;
    let row = character.actualPosition.row;
    let cell = character.actualPosition.cell;
    forward(possibleMovement, row, cell);
    backward(possibleMovement, row, cell);
    goUp(possibleMovement, row, cell);
    goDown(possibleMovement, row, cell);

};

function forward(possibleMovements, row, cell){

    let charRow = row;
    let charCell= cell;
    var table = $("table")[0];

    for(var i = 0; i<possibleMovements; i++){
        let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
        let $cell = $(cell);
        $(cell).addClass('possibleSteps');
    };
};

function backward(possibleMovements, row, cell){
    let charRow = row;
    let charCell= cell;
    var table = $("table")[0];

    for(var i = -1; i>(possibleMovements*-1); i--){
        let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
        let $cell = $(cell);
        $(cell).addClass('possibleSteps');
    };
};

function goUp(possibleMovements, row, cell){
   let charRow = row;
    let charCell= cell;
    var table = $("table")[0];

    for(var i = -1; i>(possibleMovements*-1); i--){
        let cell = table.rows[charRow+i].cells[charCell]; // This is a DOM "TD" element
        let $cell = $(cell);
        $(cell).addClass('possibleSteps');
    };
};

function goDown(possibleMovements, row, cell){
    let charRow = row;
    let charCell= cell;
    var table = $("table")[0];

    for(var i = -1; i<possibleMovements; i++){
        let cell = table.rows[charRow+i].cells[charCell]; // This is a DOM "TD" element
        let $cell = $(cell);
        $(cell).addClass('possibleSteps');
    };
};

The main solution was to understand this 4 lines of code, and how i can iterate through them:
    var table = $("table")[0];
    let cell = table.rows[charRow].cells[charCell+i]; // This is a DOM "TD" element
    let $cell = $(cell);
    $(cell).addClass('possibleSteps');


text:
Q: What are Clojure's Naming Conventions? Can anyone explain or point me to where I can find clojure's naming conventions for:

*

*File names

*Functions (From what I understand, function names are simply dash separated values)

*Variables

A: You might want to look at the Clojure library coding standards on the developer Wiki - this is probably the most comprehensive list that I've seen.
Update: link above seems to be dead, consider instead: https://clojure.org/dev/contrib_howto#_coding_guidelines
To your specific points:

*

*File names are lowercase, and stored in a directory structure to match the namespace, and end in .clj e.g. "my/special/namespace.clj

*Functions are dash-separated-lowercase-words, ideally descriptively chosen so that your code is clear and self-documenting. Don't be afraid to re-use good function names in different namespaces (that is what namespaces are for!).

*Variables (by which I assume you mean parameters, let-bound variables etc.) are also usually dash-separated-lowercase-words. Since code-is-data, I think it is appropriate that functions and data have the same naming convention :-)

A: There is an interesting set of naming conventions documented in a comment by
Taoensso in his
Encore library.
He proposes names using ! for side-effects, ? for booleans,
$ for expensive operations, _ as dereffable,
* for macros; plus a few other combos.

A: You might want to take a look at this non official style guide.

A: There are some interesting guidelines on naming written by Stuart Sierra which suggest that:

*

*pure functions should be nouns describing the return value (age instead of calculate-age)

*side-effecting functions should be verbs describing the action (create- for constructing and get- for retrieving), reserving the bang swap! changes to mutable references.

*verbs that can also be nouns should be distinguished as verb phrases (send-message instead of message)

*coercions should name the output type without an arrow prefix (connection instead of ->connection) except when the input type must be explicit (input-type->output-type)

*namespace aliases can save on repetition (products/price instead of products/product-price) and prevent local clashes in let bindings

*functions returning functions should have the -fn suffix

A: Even though you didn't ask for it explicitly, I'll explain what I've seen for protocol naming conventions.
Typically, the name starts with an uppercase "I" and then the rest is camel case, where the first letter of each word is capitalized, and the rest is lower case. For example, I want to define a protocol for rocket ships, I'd use the name IRocketShip
I've also seen 'A' instead of 'I' used, probably to represent the word 'abstract'.


text:
Q: js-grid output height restriction issues - Cannot control overflow of output I am currently using js-grid to surface data returned from a database query as part of a web application. All features seem to operate as I would like; however, when the data returned leads to the height of the overall grid being greater than that of the parent element it "overflows".
For example, it should look like:

but, with enough data, I'm getting:

I have set the height value in the jsGrid call to that of the container element, as well as trying to set a height and max-height css value using both css and jQuery. I've also added an overflow of scroll and auto, to no effect.
function surfaceDataGrid(message, recipient) {
var fieldData = JSON.parse(message.Data);
activeRequests.splice(0, activeRequests.length);
var columns = getColumns(recipient);
var Columns = columns.list.length;
var recipientElement = '#' + recipient;
var gridHeight = $(recipientElement).height();
var gridWidth = $(recipientElement).width();
$(recipientElement).html('

');
if (fieldData.length !== 0) {
    loggingAction('log', 'NOTIFICATION : Query returned ' + fieldData.length + ' rows of data. ');
    $(recipientElement).children('#jsgrid').jsGrid({
        data: fieldData,
        editing: false,
        fields: eval(columns),
        height: gridHeight,
        inserting: false,
        pageindex: 1,
        pagesize: 1,
        paging: false,
        selecting: "true",
        sorting: true,
        width: gridWidth,
    });
    var Rows = ($('.jsgrid-table tbody tr').length) - 3;
    $('.jsgrid-table').removeAttr('style');
    var gridheight2 = (gridHeight - 28) + "px";
    var headerwidth = (gridWidth / Columns) + 'px';
    $('.jsgrid-header-cell').width(headerwidth).width('28px');
    $('.jsgrid-grid-body').css('margin-top', '28px');
    $('.jsgrid .jsgrid-grid-body').css('height',gridheight2);
    $('.jsgrid-table').width(gridWidth + 'px');
    $('.jsgrid-grid-body .jsgrid-table').width(gridWidth + 'px').height(gridheight2 + 'px');
    $('.jsgrid-row').attr("tabIndex", "1");
    $('.jsgrid-alt-row').attr("tabIndex", "1");
}
else {
    $(recipientElement).children().remove();
    $(recipientElement).append('

No data returned.
 Please resubmit!

');
    $(recipientElement).fadeIn(fadeINtiming);
    loggingAction('log', 'NOTIFICATION : Query returned no data.');
}
$('tr').click(function () {
    var instantVariable0 = $('.jsgrid-header-row').parent().children()[0];
    var selectedType0 = $(instantVariable0).text();
    var instantVariable1 = $(this).parent().children()[0];
    gridValueSelected = $(instantVariable1).text();
    loggingAction('log', 'NOTIFICATION : A cell has been clicked');
    loggingAction('info', 'INFORMATION : Agent has selected ' + selectedType0.split(' ')[1] + ' value of "' + gridValueSelected + '".');
    $(this).addClass('selectedRow').siblings().removeClass('selectedRow');
});

}

A: Here you go with a solution https://jsfiddle.net/kL291xp5/39/

var data = [];

$("#jsGrid").jsGrid({
        height: 300,
        width: "100%",
        paging: false,
        autoload: true,

        fields: [
            { name: "Date", type: "textarea", width: 150 },
            { name: "User", type: "textarea", width: 150},
            { name: "Comment", type: "textarea", width: 150}
        ]
    });

$('button').click(function(){
 var comment = $('#comment').val().trim();
  if(comment.length > 0){
   data.push({
     Date: new Date(),
      User: 'ABC',
      Comment: comment
    });

    $("#jsGrid").jsGrid({
      controller: {
         loadData: function() {
           return data;
          }
        }
    });

    $('#comment').val('');
  }
});
.jsgrid-cell {
    overflow: hidden;
}

#comment{
  width: 300px;
  height:100px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.1/jsgrid-theme.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.1/jsgrid.css" rel="stylesheet"/>
<link href="https://code.jquery.com/ui/1.10.4/themes/redmond/jquery-ui.css" rel="stylesheet"/>

<textarea id="comment"></textarea>
<button type="submit">Add Comments</button>


text:
Q: discord ban command available to all users node.js I am working on a discord bot i made a ban command but it is available to all users i am using discord.js 12.0
This is my code
const Discord = require("discord.js");
const client = new Discord.Client();

const express = require("express")
const app = express()

app.get("/", (req, res) =>{
  console.log("helloe")
})

app.listen(3000, () => {
  console.log("Ready")
})

client.once('ready', () => {
    console.log('Beast Bot is ready');
    client.user.setActivity('Discord Ping Messages || ~help || (Made by CaptainBeast#1394)  ', { type:"WATCHING"}).catch(console.error)

});

const ownerId = "602113193489203232";
const owner2Id = "725629309854679092";

client.on("message", async message => {
    if (message.author.bot) return false;

    if (message.mentions.has(ownerId)) {

        message.reply(`Thanks for pinging my owner you will be banned with in 24 hours :))`);

    };
    if (message.mentions.has(owner2Id)) {

      message.reply(`Thanks for pinging my co-owner you will be banned with in 24 hours :))`);

  };
  if(message.content.startsWith("~mute")) {
    if(message.member.hasPermission("KICK_MEMBERS"))
    {
      message.reply(`Thanks for pinging my co-owner you will be banned with in 24 hours :))`);

    }
  };

  if (!message.guild) return;

  // if the message content starts with "!ban"
  if (message.content.startsWith('$ban')) {
    // Assuming we mention someone in the message, this will return the user
    // Read more about mentions over at https://discord.js.org/#/docs/main/master/class/MessageMentions
    const user = message.mentions.users.first();
    // If we have a user mentioned
    if (user) {
      // Now we get the member from the user
      const member = message.guild.members.resolve(user);
      // If the member is in the guild
      if (member) {
        /**
         * Ban the member
         * Make sure you run this on a member, not a user!
         * There are big differences between a user and a member
         * Read more about what ban options there are over at
         * https://discord.js.org/#/docs/main/master/class/GuildMember?scrollTo=ban
         */
        member
          .ban({
            reason: 'They were bad!',
          })
          .then(() => {
            // We let the message author know we were able to ban the person
            message.channel.send(`Successfully banned ${user.tag}`);
          })
          .catch(err => {
            // An error happened
            // This is generally due to the bot not being able to ban the member,
            // either due to missing permissions or role hierarchy
            message.channel.send('I was unable to ban the member');
            // Log the error
            console.error(err);
          });
      } else {
        // The mentioned user isn't in this guild
        message.channel.send("That user isn't in this guild!");
      }
    } else {
      // Otherwise, if no user was mentioned
      message.channel.send("You didn't mention the user to ban!");
    }
  }

});

// inside a command, event listener, etc.
const help = new Discord.MessageEmbed()
    .setColor('#0099ff')
    .setTitle('Commands')
    .setURL('')
    .setAuthor('CaptainBeast', 'https://www.clipartmax.com/png/full/307-3072086_discord-icon-discord-icon-png.png')
    .setDescription('Here are the list of some available commands')
    .setThumbnail('https://www.clipartmax.com/png/full/307-3072086_discord-icon-discord-icon-png.png')
    .addFields(
        { name: 'Commands', value: ':) commands' },
        { name: '\u200B', value: '\u200B' },
        { name: '~help', value: 'Displays list of available commands', inline: true },
        { name: '~ping', value: 'sent pong ', inline: true },
    )
    .addField('More stuffs coming soon', 'the bot is still under development', true)
    .setImage('')
    .setTimestamp()
    .setFooter('Made by CaptainBeast#1394', 'https://www.clipartmax.com/png/full/307-3072086_discord-icon-discord-icon-png.png');

const prefix = "~";
client.on("message", (message) => {
  // Exit and stop if it's not there
  if (!message.content.startsWith(prefix)) return;

  if (message.content.startsWith(prefix + "help")) {
    message.channel.send(help);

  } else
  if (message.content.startsWith(prefix + "foo")) {
    message.channel.send("bar!");
  }
  if (message.content.startsWith(prefix + "ping")) {
    message.channel.send("pong!");
  }
});

client.login('censored')

This is my whole code

A: After your if condition to know if it's the ban command, you don't look at the permission of the person who wrote the message.
You need just to add the condition
For Disord.js V12
if (message.member.hasPermission("BAN_MEMBERS")) {
    ...
}

For Discord.js V13
if (message.member.permissions.has("BAN_MEMBERS")) {
    ...
}


text:
Q: Why is traceroute showing a private IP address between the router and the WAN router? I have a TP-Link Router (TL-R605), connected on the LAN to a TP-Link switch, and connected to the WAN directly to my internet provider router (ZTE F670L).
The TP-Link router has an IP address of 192.168.0.1, and my computers sits under the 192.168.0.0/24 subnet, with DHCP enabled at the TP-Link router.
The ZTE router has an IP address of 192.168.1.1, and the TP-Link router WAN port gets a static IP address of 192.168.1.2. DCHP is disabled on the ZTE router.
It seems that when I'm tracing a route, the TP-Link router does a hop to a 169.254.11.21 address, instead of going directly to 192.168.1.1. I have not manually added any routing rules.
user@home:~$ traceroute 1.1.1.1
traceroute to 1.1.1.1 (1.1.1.1), 30 hops max, 60 byte packets
 1  192.168.0.1 (192.168.0.1)  0.280 ms  0.223 ms  0.191 ms
 2  169.254.11.21 (169.254.11.21)  0.881 ms  0.993 ms  0.853 ms
 3  192.168.1.1 (192.168.1.1)  1.066 ms  0.775 ms  1.105 ms
 4  172.31.255.1 (172.31.255.1)  7.256 ms  7.224 ms  2.032 ms
 5  172.21.11.2 (172.21.11.2)  1.948 ms  1.969 ms  1.886 ms
 6  172.21.10.234 (172.21.10.234)  2.810 ms  3.154 ms  3.092 ms
 7  172.19.252.33 (172.19.252.33)  2.378 ms  3.214 ms  3.154 ms
 8  as28283.portoalegre.rs.ix.br (177.52.38.57)  3.116 ms  3.078 ms  3.305 ms
 9  as13335.portoalegre.rs.ix.br (177.52.38.200)  9.235 ms  9.203 ms  9.170 ms
10  one.one.one.one (1.1.1.1)  2.778 ms  2.747 ms  2.715 ms

This traceroute was run out of a Linux server inside the LAN (192.168.0.3), and no routes are manually added there as well:
user@home:~$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.0.1     0.0.0.0         UG    202    0        0 enp2s0
192.168.0.0     0.0.0.0         255.255.255.0   U     202    0        0 enp2s0
192.168.0.1     0.0.0.0         255.255.255.255 UH    100    0        0 enp2s0

So can someone please explain why it's hoping to 169.254 address and how can I remove it?

A: I have the same router.
From what I understand that extra hop is just caused by the DHCP server replying what IP to forward next

A: and it sure is taking a long time inside the ER605 to access that internal hop in the ER605, which from what support says is necessary for the WAN/LAN port support, and this embedded and non published DHCP server starts passing out addresses
at 169.254.11.21/22... and so on for the WAN interface(s) despite having a STATIC IP address assigned to a WAN port.
Z


text:
Q: useState reset in memo I am trying to re order a list that is stored in state.
When I click on a button a keyId is stored in a context variable.
The behavior that I'm trying to implement is whenever a new item in the list is clicked, it shuffles to the top of the list and pushes the rest of the items down.
I am only able to get the active id at the top of the list, and the rest of the list items seem to reset on each render.
As far as I can tell when debugging, the reorderedList state does not appear to update - or its referencing an older piece of state.
I've read about some issues with memo and closures but I couldn't seem to get it to work.
export const reorderList= (
  list,
  keyId
) => {
  const expanded = list.find(
    ({ id }) => id === keyId
  );
  const collapsed = list.filter(
    ({ id }) => id !== keyId
  );

  return [expanded , ...collapsed];
};

export const ListSummary = memo(
  ({ listProps }) => {
    const { keyId } = useKeyIdContext();

    const [reorderedList, setReorderedList] = useState(
      listProps
    );

    useEffect(() => {
      setReorderedList(
        reorderList(
          reorderedList,
          keyId
        )
      );
    }, [keyId]);

    return (
      <>
        {reorderedList.map(r => (
          <SomeList
            key={r.id}
            r={r}
            isExpanded={keyId === r.id}
          />
        ))}
      </>
    );
  }
);


text:
Q: trigger is not working , not updating the record trigger CompareAndChangeOpportunityOwner on Account (after update) {

    List<Account> SelectedAccount = [SELECT ID,OwnerID, (SELECT ID,OwnerID FROM Opportunities)  FROM Account WHERE Account.ID IN : trigger.oldMap.keyset()];

    Map<ID,Opportunity> AccountIDandOpportunity = new Map<ID,Opportunity>();

    For(Account acc : SelectedAccount) {
        for(Opportunity op : acc.Opportunities){
            AccountIDandOpportunity.put(acc.ID,op);
        }
    }

    List<Opportunity> opp = new List<Opportunity>();
    List<opportunity> opp2 = new List<opportunity>();

    for(Account a : trigger.new)
    {
       opp2.add(AccountIDandOpportunity.get(a.ID));
       for(Opportunity op : opp2){
       system.debug('compareeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'+op.ownerID+'    '+a.ownerID);
       if(op.OwnerID.equals(a.OwnerID)){
           op.OwnerID = a.OwnerID;
           opp.add(op);
           }
       }

    }

    update opp;
}

The trigger is entering the if statement, but the value is not updating.
please help.

A: I see that there are couple of things wrong with the implementation:
Example this piece of code.
Map<ID,Opportunity> AccountIDandOpportunity = new Map<ID,Opportunity>();

For(Account acc : SelectedAccount) {
            for(Opportunity op : acc.Opportunities){
                AccountIDandOpportunity.put(acc.ID,op);
            }
        }

The relationship between account and opportunity is one to many as one account may contain many opportunities.
The map in which you are putting the opportunities will give you one to one mapping only because a map can contain only unique keys. So every-time you add an opportunity with same account Id to the map, the previous one gets replaced.
Second mistake that I found was that your requirement says that you want to update the owners of the opportunities which do not match your account owner, however in the code you are updating those opportunities which have same ownerId as that of account so actually you wont see any change in the data base.
 if(op.OwnerID.equals(a.OwnerID)){
           system.debug('cominggggggggggggggggggggggggggggggggggggg');
           op.OwnerID = a.OwnerID;
           opp.add(op);
           }
       }

If you put a NOT operator before your If condition, it will work but only for one opportunity.
Here is an optimized piece of code. I have typed this directly as I do not have access to IDE but you'll get the basic idea.
trigger CompareAndChangeOpportunityOwner on Account (after update) {

   //Query Opportunities related to the accounts
    List<Opportunity> queriedOpportunites = [SELECT ID,OwnerID,AccountId FROM Opportunity WHERE AccountID IN : trigger.new];
    List<Opportunity> oppToUpdate = new List<Opportunity>();

    for(Opportunity opp : queriedOpportunites){
        //Check if Opportunity Owner = Account Owner
        if(!opp.OwnerID.equals(trigger.newMap.get(opp.AccountId).OwnerID)){
            opp.OwnerID = trigger.newMap.get(opp.AccountId).OwnerID;
            oppToUpdate.add(opp);
        }
    }
    update oppToUpdate;
}


text:
Q: Extra information at prediction time when using a Bayesian logistic regression vs. normal I have a binary classification problem (i.e. is observation positive or negative) and I'm interested in what information I can obtain about observations in my test set. I don't care about the model parameters or observations in my training set. I have plenty of data and would just use an uninformative prior as the task is fairly simple.
With a frequentist logistic regression I can only get a probability estimate of whether the observation is positive/negative, but from what I've heard Bayesian methods can give more information such as an uncertainty estimate. With regards to this I have the following questions:

*

*How does the Bayesian method obtain this extra information? Can
you refer to any material on this?

*What extra information can be obtained at prediction time? Can
one get more information than an uncertainty estimate?

A: You can start with the Bayesian logit model - intuitive explanation? thread, or this one about linear regression. The basic difference is that with Bayesian model you get a full probabilistic model, so what the model returns is the posterior distributions of your parameters and posterior predictive distribution of the predictions. Additional advantage is that you can include some prior information in your model, but if you plan to use "uninformative" prior, you do not seem to be interested in such advantage.
So the basic difference for your purpose is that in frequentist case you would obtain your predictions and you could estimate confidence intervals, or prediction intervals. In Bayesian case, given your model you could estimate and simulate the whole posterior predictive distribution, so instead of interval estimates you could check many more properties of the distribution.
Notice however that in frequentist setting you could also simulate the potential predictions from your model to approximate the posterior predictive distribution, or use bootstrap for similar purpose.


text:
Q: Common mistakes in concluding that series is convergent or not Assuming $(na_{n})_{n=1}^{\infty}$ convergent to $0$ then
$\sum_{n=1}^{\infty}a_{n}$ is convergent, true or false ?
wel' I say it is true because:
$n$ convergent to infinity and $na_{n}$ is convergent to zero
meaning is also convergent to zero.
So the question who is "convergent faster".
I can conclude that $a_{n}$ is convergent faster then $\frac{1}{n}$ to $0$
because $n\frac{1}{n}$ convergent to $1$.
meaning $\exists \alpha \in \mathbb{R}_{> 1}\ \exists N \in \mathbb{N}\ \forall n>N \ a_{n} \leq \frac{1}{n^{\alpha}}$
And we know that $\sum_{n=1}^{\infty} \frac{1}{n^{\alpha}}$ is convergent there fore the tail of  $\sum_{n=1}^{\infty}a_{n}$ is convergent meaning the series is convergent.
I was told this is not true and the answer is false.
So can someone please give a counterexample and please explain to me what I did wrong in my proof.
Thanks in advanced !!

A: Just because $na_n \to 0$, it doesn't follow that $a_n < n^{-\alpha}$ for some $\alpha > 1$.
Counterexample: $a_n = \dfrac{1}{n\log n}$. The corresponding series diverges; the simplest way to see this is via the integral test (or Cauchy's condensation test if you know that one).

A: $$
\sum_{n=2}^\infty \frac{1}{n \log n}
$$
is divergent, but $\lim_{n \to \infty} \frac{n}{n \log n}=0$.


text:
Q: Alpha-channel all 1.0 in WebGLRenderTarget when reading rendered image for post-processing I am using Three.js to render the world to a WebGLRenderTarget. My world does not full the whole screen and thus, has transparent background. The purpose is to provide alpha-channel aware image effects.

*

*I render the world to a WebGLRenderTarget buffer

*I try to post-process this by reading from the buffer and writing to the real screen
My post-processing function depends on the alpha channel. However, looks like that somehow Three.JS post-processing shader fails to read the alpha channel correctly - it is all 1.0 no matter what values I try to put in to WebGLRenderTarget.
The simple way to demostrate the problem.
I create a render target:
        var rtParameters = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat};

        for(var i=0; i<this.bufferCount; i++) {
            this.buffers[i] = new THREE.WebGLRenderTarget(this.width, this.height, rtParameters);
        }

I clear the buffer setting alpha to 0.3::
        function clear(buf) {
            // For debugging purposes we set clear color alpha
            renderer.setClearColor(new THREE.Color(0xff00ff), 0.3);
            renderer.clearTarget(buf, true, true, true);
        }

        // Clean up both buffers for the start
        clear(buffers[0]);

And then I use this buffer as a read buffer and render to the screen in my post-processing fragment shader function (ThreeJS post-processing examples):
            "void main() {",

                    // texture is the buffer I rendered before
                    "vec4 sample = texture2D( texture, vUv);",

                    // Everything goes to white (1.0) when trying to visualize the
                    // alpha channel of previously rendered WebGLTarget.
                    // It should get value 0.3 - slight gray
                    "gl_FragColor = vec4(sample.a, sample.a, sample.a, 1.0);",
            "}"

Other color values are read correctly. If I use vec4(sample.r, sample.g, sample.b, 1.0) it directly copies as expected.

*

*Is there a problem of clearing the alpha channel for WebGLRenderTarget?

*Is there a problem of reading alpha values as having WebGLRenderTarget as texture for 2D image post-processing in GLSL shader?

A: Here is a fiddle that implements what I believe you are trying to achieve.
http://jsfiddle.net/6vK6W/3/


text:
Q: Android browser won't download pdf file I have a web app that lets users download a pdf file. It is ASP.NET MVC and it all works fine on desktop browsers, iPhone, Android Chrome, and in a native Android app that overrides the  Web View setDownloadListener().
However, the download doesn't seem to work when using the default Android browser. I'm testing on a Galaxy Nexus running 4.2.2 and on a Nexus S 4g running 2.3.7. I have PDF viewer apps installed on both devices.
When I test in Android Chrome, the user sees a "Starting Download..." toast and then a Download complete notification is shown in the status bar. The user can touch this notification to open the file in a pdf viewer. In Android's default browser there is no toast and no download file is saved.
I put wireshark on the network and I see the following request:
GET /appapth/ViewPDF/8383600280757433_11_05_2012 HTTP/1.1
Host: 192.168.1.117
Connection: keep-alive
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
X-Requested-With: com.google.android.browser
User-Agent: Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; Galaxy Nexus Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
Accept-Encoding: gzip,deflate
Accept-Language: en-US
Accept-Charset: utf-8, iso-8859-1, utf-16, *;q=0.7
Cookie: (lots o'cookie data)

and the response is:
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: application/pdf
Content-Encoding: gzip
Expires: -1
Server: Microsoft-IIS/7.5
Set-Cookie: ___TempData=; path=/
Set-Cookie: ___TempData=(lot's o'cookie data); path=/; HttpOnly
Date: Mon, 01 Apr 2013 18:22:20 GMT
Content-Length: 48244

......YQ.....T...?J.h)...!E.S(lots o'binary data)

As you can see from the trace application/pdf content is downloaded. You can also see that I'm not using the content-disposition header and the response is downloaded with gzip encoding.
Any ideas on why this does not work on the Default Android browser? The user does not have access to the downloaded data and no viewer (or intent) is launched. The response is just silently ignored. (I'm guessing that Android default browser requires the content-disposition or doesn't like Gzip on the download, but I'm just guessing)
Update ----
I removed our action filter that was implementing Gzip compression and I added in the
Content-Disposition attachment header. so, MVC code in my controller is like:
public virtual ActionResult ViewPDF(string id)
{
    try
    {
        byte[] pdf = GetPDFContent(id);
        FileContentResult fcr = new FileContentResult(pdf, "application/pdf");
        fcr.FileDownloadName = id + ".pdf";
        return fcr;
    }

and the Http response is now:
HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Content-Type: application/pdf
Expires: -1
Server: Microsoft-IIS/7.5
Content-Disposition: attachment; filename=433_07_05_2012.pdf
Set-Cookie: ___TempData=; path=/
Set-Cookie: ___TempData=(lots o'cookie data);path=/; HttpOnly
Date: Mon, 01 Apr 2013 19:56:07 GMT
Content-Length: 59069

%PDF-1.3 %.... 13 0 obj << (lots o'binary pdf data)

There is no longer any gzip and there is a content-disposition, but on the Android default browser there is still no visible download.
Update 2 ---
tried the suggestions from https://stackoverflow.com/a/5728859/90236 and http://winzter143.blogspot.com/2012/03/android-handling-of-content-disposition.html and http://androidforums.com/application-development/256987-android-phone-download-issue-asp-net-website.html but I still get the same results.

A: Found my own answer and it was so much simpler than where I was looking. My page with the download link is in an iframe. Something in the Android default browser loses your download if it occurs in an iframe. I added target="_blank" to the a tag that initiates the download and everything now works fine.
Here is some sample code to demonstrate the the problem and the fix.

<title>Test page</title>
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">

        Download sample pdf

and inner.html:

<title>test iframe</title>
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">

This does NOT work on Android default browser.

    Download sample pdf within iframe

Download sample pdf within iframe with target.


text:
Q: Error when execute within a TFS build definition When I tried to call command-line to get latest update for my TFS mapped folder
TF get /recursive
The call complete successfully from the run window of Windows 7.
However, when I put the call into a .bat file and run it via InvokeProcess within a build definition (guide to do that), it failed.
The message is as below.

Unable to determine the workspace. You may be able to correct this by
  running 'tf workspaces /collection:TeamProjectCollectionUrl'

What happens? How can I get around with that?

A: The reason this is happening is because when you run the command locally, the folder you're downloading is mapped to a workspace. When you execute the command in your build, it's running under the build service account, which doesn't have a workspace mapped for the folder you're specifying.
You shouldn't need to use the tf get command as part of your build. When you configure your build, you can specify which folders should be mapped in the workspace on the "Source Settings" tab. The build process will handle making sure the contents of the folders you map in your workspace are present automatically.

A: The cause for my issue is that the build agent execute my .bat file under a different Windows account which is something like NTSERVICE; when I run it directly, my TFS login account was used (which was previously remembered in Windows 7 Credential Manager)
So the solution is to put in the login name and password as TF get /login:SomeTFSUsername,SomePassword (see more here)


text:
Q: create data frames for each ID of another data frame I looked in the question database but I didn't find an answer, so sorry if I miss something.
The question is very simple: how can I create new data frames based on a column ID of another one?
If this in the original df:
structure(list(ID = structure(c(12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L), .Label = c("B0F",
"B12T", "B1T", "B21T", "B22F", "B26T", "B2F", "B33F", "B3F",
"B4F", "B7F", "P1", "P21", "P24", "P25", "P27", "P28", "P29"), class = "factor"),
    EC = c(953L, 838L, 895L, 2170L, 2140L, 1499L, 2120L, 881L,
    902L, 870L, 541L, 891L, 876L, 860L, 868L, 877L, 3630L, 3400L,
    2470L, 2330L, 1810L, 2190L, 2810L, 2200L, 2440L, 1111L, 2460L,
    2210L, 2340L, 1533L, 880L, 2475L, 2350L, 2440L, 1456L, 2320L,
    2220L, 2990L, 2240L, 2210L, 2630L)), .Names = c("ID", "EC"
), row.names = 40:80, class = "data.frame")

How can I create two new df, based on the ID? So I can have two new df named B21T and P1 for example?
I know I can do it with a subset, but if I have many IDs it would take a lot of time.
So I think that what I'm looking for is a way to automatize the subset function.

A: Consider df is your data.frame, then just do:
df$ID <- droplevels(df$ID)  #  drop unused levels from `ID`
list2env(split(df, df$ID), envir=.GlobalEnv)

A: You can put all the different subsets you want in a list and, then extract them from there:
#DF <- structure(list(ID = structure(c(12L ...

#all different "ID"s
ids <- as.character(unique(DF$ID))

#create empty list to insert all different subsets
myls <- vector("list", length(ids))

#insert the different subsets
for(i in 1:length(ids))
 {
  myls[[i]] <- DF[DF$ID == ids[i],]
 }

names(myls) <- ids

You can accesss the wanted dataframe:
> myls$P21
    ID   EC
56 P21 3630
57 P21 3400
...

> myls$P1
   ID   EC
40 P1  953
41 P1  838
...

This might take some time, though, if you have really many "ID"s.
EDIT
Waaay better than for loop is Jilber's answer. Here used as split(DF, DF$ID, drop = T).


text:
Q: How to prevent rendering I use handlebars and dynamic provisioning of templates.
The template HTML for each form is put into the script tags and is downloaded runtime from the server. Eg:.

When the form is shown, I read html from script tag, compile using handlebars and then show it to the user.
I have a bundle of several such templates which I download.
However, I see that the browser actually tries downloading the src of images and sound files in text/html found in the script tags.
Is there a way to disable that?
https://gist.github.com/brendo/1857345 Gist perfectly explains the issue but doesn't recommend.


text:
Q: How can I define callback function for an option in Owl Carousel 2? I am trying to change value of an option by coming value from database. In order to do this, I think i should define a callback function. But it's not working.
My callback function is:
function nav_cb(){
    if( settings.nav==='on' ){
        return true;
    }else{
        return false;
    }
}

And my init codes are here.
var owl = $('.owl-carousel');
owl.owlCarousel({
    loop: true,
    nav: nav_cb,
    dots: true,
});

But it doesn't accept this result of function. How can i make it return true or false?

A: I've just found it myself. They should be like this. Working fine.
var nav_check = 0;
if( settings.nav==='on' ){
    nav_check = true;
}else{
    nav_check = false;
}

var owl = $('.owl-carousel');
owl.owlCarousel({
    loop: true,
    nav: nav_check,
    dots: true,
});


text:
Q: Assigning values to an object and its nested object I am a novice and am missing something simple. I have two Classes
Public Class Param
    Public Property temperature As String
    Public Property display As Boolean
    Public Property storage As Boolean
    Public Property reason As Boolean
    Public Property stats As Object
    Public Property errors As Object
End Class

Public Class getTemperature
    Public Property method As String
    Public Property params As Param()
    Public Property id As String
End Class

I want to declare and assign values to the  objects but I keep getting the error "Object reference not set to an instance of an object" when trying to assign values to items within param. I don't understand,  I have created both the object GetTemperature and the object Params, what am I missing?
 Dim GetTemp As New getTemperature
    GetTemp.method = TextBoxMethod.Text
    GetTemp.id = TextBoxID.Text
    Dim params As New Param
    params.temperature = "true"
    'GetTemp.params(0) = params

I have also tried, but get the same response:
 Dim GetTemp As New getTemperature
    GetTemp.method = TextBoxMethod.Text
    GetTemp.id = TextBoxID.Text
    GetTemp.params(0).temperature = "True"

A: Try this:
Public Class Param
    Public Property temperature As String
    Public Property display As Boolean
    Public Property storage As Boolean
    Public Property reason As Boolean
    Public Property stats As Object
    Public Property errors As Object
End Class

Public Class getTemperature
    Public Property method As String
    Public Property params As List(Of Param)
    Public Property id As String

    Public Sub New()
        params = New List(Of Param)
    End Sub
End Class

So you could write something like:
        Dim a As New getTemperature
        a.params.Add(New Param)

A: It will work if you remove the parenthesis
Public Class getTemperature
    Public Property method As String
    Public Property params As Param
    Public Property id As String
End Class

and then
Dim GetTemp As New getTemperature
GetTemp.method = TextBoxMethod.Text
GetTemp.id = TextBoxID.Text
Dim params As New Param
params.temperature = "true"
GetTemp.params = params


text:
Q: How to retrieve ID of inserted entry using sqlsrv in PHP I have one query that will return the ID of the inserted row. When I change the query to insert into a different table I only get errors when fetching the identity.  Keep in mind this is the stripped down debugging code of the main program so I can troubleshoot better.
I should also mention that I am using custom wrappers around the sqlsrv commands but they are basically the same. Assume $IC->connection is a connection resource and performing a connection->prepare returns a result stmt object.
$upsert_custom = "
INSERT INTO CampusDictionary (attributeID, code, name, seq, active)
SELECT ?, ?, ?, 0, 1;
SELECT SCOPE_IDENTITY();"; // This query will work as expected
$upsert_custom = "
INSERT INTO Person (currentIdentityID, staffNumber, comments)
SELECT ?, ?, ?;
SELECT SCOPE_IDENTITY();"; // Using this query I get errors
$custom_stmt = $IC->connection->prepare( $upsert_custom, array( &$attributeID, &$code, &$name) );

$name = "TEST";
$attributeID = '832';
$code = '9999';

$IC->connection->begin_transaction();
$custom_stmt->execute();
$custom_stmt->next_result();
$custom_stmt->fetch();
$dictionaryID = $custom_stmt->get_field(0);
print_r("THIS WOULD CREATE ID: " . "\r\n");
var_dump($dictionaryID);
die( print_r( $IC->connection->get_errors(), true));
$IC->connection->rollback();
$custom_stmt->cancel();

When using the first query only, I get the following output:
php test.php
THIS WOULD CREATE ID:
string(5) "16774"

When using the second query, I get the following:
THIS WOULD CREATE ID:
bool(false)
Array
(
    [0] => Array
        (
            [0] => IMSSP
            [SQLSTATE] => IMSSP
            [1] => -14
            [code] => -14
            [2] => An invalid parameter was passed to sqlsrv_get_field.
            [message] => An invalid parameter was passed to sqlsrv_get_field.
        )

)

I know that an AFTER INSERT and AFTER UPDATE trigger on the Person table exists but I don't have rights to view these triggers. From what I've read, the SCOPE_IDENTITY shouldn't worry about the trigger anyways.
What is going on here? I need to insert into the Person table and use the ID in another table all within one transaction. I've spent hours troubleshooting this but can't get it to work.

A: After hours of troubleshooting I finally post here and within 10 minutes I figure it out... I'll leave this here for anyone else that runs into this issue. Perhaps someone smarter than I can explain the WHY.
The solution is to add "SET NOCOUNT ON;" to the beginning of the query. The working code for the second query looks like so:
$upsert_custom = "
SET NOCOUNT ON;
INSERT INTO Person (currentIdentityID, staffNumber, comments)
SELECT ?, ?, ?;
SELECT SCOPE_IDENTITY();";
$custom_stmt = $IC->connection->prepare( $upsert_custom, array( &$attributeID, &$code, &$name) );

$name = "TEST";
$attributeID = '832';
$code = '9999';

$IC->connection->begin_transaction();
$custom_stmt->execute();
//$custom_stmt->next_result();//$custom_stmt->next_result();
//$dictionaryID = $custom_stmt->fetch_assoc();
$custom_stmt->fetch();
$dictionaryID = $custom_stmt->get_field(0);
print_r("THIS WOULD CREATE ID: " . "\r\n");
var_dump($dictionaryID);
//die( print_r( $IC->connection->get_errors(), true));
$IC->connection->rollback();
$custom_stmt->cancel();

Output of this is:
THIS WOULD CREATE ID:
string(5) "43210"


text:
Q: Why can't we see the glow of scattered light which has been scattered very far away? It said to use red colur objects as a sign of danger because it is scattered at least and hence can be seen from far?
But if use suppose blue colour bulb in a open area (where no objects to absorb light) , I agree that its rays will not reach us when far because all colour is already scattered and hence we cannt see it.
But why we cannt see even that scattered blue light from far(very) , although we can see scattered light from sky that is much farther than blue bulb?
It is said that during time of sunset or sunrise, appears red as all blue colour is scattered very before, My doubt is why cannt  we see that blue colour scattered light? Although it is said our eye can watch at infinity.
Just because scattered light is far, we cannt see it, Can't scattered light reach  us from that far?

A: Suppose you placed a bulb very far away(say infinity). Now if the bulb is turned on, you can't see the light at infinity, because of the intensity, as you can see in this image,
The farther the light travels the more area it has to cover, now a bulb shining at infinity have to cover an infinite area where you are standing(at infinity from bulb).
Thus the density of rays decreases very much, and become invisible.
Note- You can see a bulb shining when you are close to is because it's intensity and light ray density is high, but as you move away both decreases and at a point you can't see the bulb anymore.

A: Red things are used as stop signs because of our vision, not because red light travels farther. Red things appear bright to us because of the way our brain works. Not all that many things are red, so a red object is not likely to blend in to the background.
In clear air, scattering works over longer distances. At noon, light travels straight down through the atmosphere. The atmosphere gets thinner and fades away with altitude, but about half of it is below 3 miles high. At sunset, light travel a longer path through the atmosphere.
Blue light scatters more often and at a larger angle than red light.
At sunset, almost all the blue light from the sun has been scatter away from its original path. So when you look directly at the sun, red predominates.
Likewise, when you look near the sun, you are looking at an angle almost directly at the sun. A lot of what you see is red light that was almost aimed at you, and has been deflected a little. You will get some blue, but a lot of the blue was deflected at a sharper angle.
When you look at $90^o$ from the sun, you will see the sky is still blue, particularly if you look up. Light that was headed somewhat in your direction, but higher gets overhead before it is deep in the atmosphere. There is it scattered. Blue light is likely to be scattered $90^o$. Red light is not. So the sky appears blue.


text:
Q: Sqrt induces a problem in simplifying We have an expression such as
 Sqrt[-2 - d^2 + 2 Sqrt[1 + d^2]] Sqrt[-d^2 - 2 (1 + Sqrt[1 + d^2])]

When we use
FullSimplify[Sqrt[-2 - d^2 + 2 Sqrt[1 + d^2]] Sqrt[-d^2 - 2 (1 + Sqrt[1 + d^2])] ]
The result is nothing simplified.
But when we use
FullSimplify[(-2 - d^2 + 2 Sqrt[1 + d^2]) (-d^2 - 2 - 2 Sqrt[1 + d^2])]

in which we firstly expanded the second expression and after that we multiplied them to each other albeit without the Sqrt.
we can see the result is d^4 and Sqrt[d^4] is d^2.
How can we directly obtain the the most simplified yield from the first expression i.e.,
Sqrt[-2 - d^2 + 2 Sqrt[1 + d^2]] Sqrt[-d^2 - 2 (1 + Sqrt[1 + d^2])]

A: Your purported solution isn't correct. For example:
Sqrt[-2-d^2+2 Sqrt[1+d^2]] Sqrt[-d^2-2 (1+Sqrt[1+d^2])] /. d->.1

-0.01 + 0. I

It helps to add assumptions:
FullSimplify[
    Sqrt[-2-d^2+2 Sqrt[1+d^2]] Sqrt[-d^2-2 (1+Sqrt[1+d^2])],
    d ∈ Reals
]

-d^2

A: In:
expr = Sqrt[-2 - d^2 + 2 Sqrt[1 + d^2]] Sqrt[-d^2 - 2 (1 + Sqrt[1 + d^2])];
Assuming[d ∈ Reals, Simplify[expr]]

Out:

-d^2


text:
Q: Find real (optical) center of SVG icons using SCSS mixin So I was reading through this pretty interesting (and accurate) article on the play button never being centered optically -
https://medium.com/@erqiudao/the-play-button-is-not-optical-alignment-4cea11bda175
After reading this I wanted to try and take a stab at creating a mixin that will always find the actual center of an icon no matter the shape of it. But! It is a lot trickier than I thought it would be so came here for some help!
Oh and side note: currently I am passing all of my svg icons into a font file that has some base styles on it such as:
font-family:"IconFont";
display:inline-block;
vertical-align:middle;
line-height:1;
font-weight:normal;
font-style:normal;
speak:none;
text-decoration:inherit;
text-transform:none;
text-rendering:optimizeLegibility;
-webkit-font-smoothing:antialiased;
-moz-osx-font-smoothing:grayscale;

Any help or guidance would be highly appreciated!
Best,
Artem


text:
Q: wpf mvvm async Как сохранить состояние view и передать параметр MainWindow Есть программа, слева меню, справа открывается view. На View, при нажатии кнопки, запускается задача и работает ProgressBar. Для  этого я использую Task, чтобы менялся ProgressBar на лету. Дальше я дошел (я новичок) до async и все хорошо. Но теперь я бы хотел, чтобы переключаясь через окна пока работает Task, ProgressBar не обнулялся бы, т.к. задача ещё работает. Но ProgressBar не обновляется. И еще хотел бы, чтобы на кнопке в меню крутился круглый ProgressBar, чтобы клиент понимал, что работает программа.
Но как из ViewModel передать параметр MainWindow?
ProgressBar это отдельный UserControl который я помещаю во View.
<ProgressBar Value="{Binding CurrentProgress}" Margin="10,0" HorizontalAlignment="Center" VerticalAlignment="Center" Height="15" Width="780"/>

CurrentProgress обернутый в Task async метод берет количество делит на сто и увеличивается на 1 во время цикла. Это все работает.
Подробнее:
Wpf MVVM
Есть программа основное окно слева кнопки справа UserControl. Кнопка меню код
 DataContext = new ImportContractUslViewModel();

На этом UserControl располагается еще один UserControlProgressBar с кодом
   <ProgressBar Value="{Binding CurrentProgress}" Margin="10,0" HorizontalAlignment="Center" VerticalAlignment="Center" Height="15" Width="780"/>

ViewModel
public double CurrentProgress
{
    get { return _currentProgress; }
    set
    {
        _currentProgress = value;
        RaisePropertyChanged("CurrentProgress");
    }
}

public async void ImportPaymentsDoc() //Метод обработки
{
    inserted = 0;
    var importDoc = Task.Factory.StartNew(() =>
    {
        var res = db.eias_PaymentDocument.Include("eias_PaymentDocument_ChargeInfo").Where(c => c.AccountGUID != null ).OrderBy(c => c.AccountGUID).Select(c => c).ToList();
        //Получаем значение из базы
        count = res.Count; // Считаем кол-во записей
        foreach (var ty in res)
        {
            //Код обработки записей ...

            inserted++;
            updateProgress(inserted);

        }
    });

    await importDoc;

    importDoc.Wait();
    System.Windows.Forms.MessageBox.Show(importDoc.Status.ToString());
}

//Метод подсчета значений прогресс бар

private  void updateProgress(int Analyzed)
{
    if (Analyzed != 0)
    {
        int percentage = 100 * Analyzed / count;
        CurrentProgress = percentage;
    }
}

После того как я запускаю операцию обработки прогресс бар начинает считать проценты все ок но стоит мне перейти в другой DataContext задача выполняется дальше проверено ждет завершения но я бы хотел что бы прогресс бар не обнулялся.
А так же как повесить Круглый прогресс бар на кнопку меню не забудем MVVM. Что бы пользователь мог лазить по программе и видел что задача например Квитанции выполняется и знал когда завершилась что бы можно было обратно перейти и нажать следующую кнопку.

A: Проблема в том, что вы каждый раз создаете новый экземпляр VM:

DataContext = new ImportContractUslViewModel();

У него естественно свой экземпляр свойства CurrentProgress, который по умолчанию и равен 0.
Решение - создавать VM один раз и всегда использовать только этот единственный экземпляр.


text:
Q: Is it possible to append or merge one or more XFA form-based PDF files together with iText? I have one PDF file that has an embedded form that is based on XFA (XML) forms.  The first PDF has a table which holds a list of people.  If that table overflows, the subsequent list of people are handled by an addendum page which is also a PDF (XFA based form).  Is it possible to merge all XFA-based PDFs into one PDF using iText?

A: @BrunoLowagie Thanks for your response.   Actually, I managed to get iText to concatenate PDF interactive forms to create a custom PDF packet.  Let me explain how I did this.
From using Adobe Acrobat XI Pro, I learned that when the XFA PDF is loaded, I cannot edit the form if I go to Tools->Edit (it gives me the usual warning that this PDF was created by LiveCycle Designer), but when I go to Pages->Extract, then select all pages to be extracted, the whole XFA-based PDF is extracted and converted over to an AcroForms based PDF.  So if I had 25 fields in the XFA-based PDF, it had successfully converted all 25 fields into AcroForm fields. Somehow Adobe Acrobat had to determine the variable names based on the XML structure.  (i.e. xpath)  //form1/Page1/variable1 was converted to acro field name: form1[0].Page1[0].variable1[0].  All visible (editable form) fields were present and aligned (pixel-perfect) as usual.
If I had flattened the XFA PDF, I would again need to place the form fields back on each page, which would be tedious.  By using Pages->Extract->All Pages, it converts everything for me (no flattening needed - flattening which strips all fields also; also no XFA worker lib needed).
However, my PDF packet is static and I would like to repeat the addendum page in case data overflows from the 2nd page.  I know I could have modified the initial XFA to handle this overflow, but the client wants to use the exact page look for the addendum, with headers/footers intact.
I found that I can achieve this by extracting the addendum page separately via Adobe Acrobat Pro->Pages->Extract->(Select Addendum Page), then it was converted to a PDF form w/AcroForm intact.
I took the original PDF packet and attempted to concatenated the addendum PDF page. So for the moment, the main packet has AcroForm fields and the Addendum PDF page also has AcroForm fields.
When I used PdfCopy or PdfConcatenate to do the concatenation, I noticed that I lost all form fields when I called form.getFields()
When I used the (deprecated) PdfCopyFields to do the concatenation, all AcroForm fields were intact.  (Exactly what I needed!)  I also tested the PdfCopyFields where some fields were filled/saved and the PdfCopyFields still worked & carried over the prefilled values over.  I looked at the reason why PdfCopyFields was marked for deprecation, saying that we can either merge accessible files and lose the forms or merge the forms or lose the accessibility (tagged PDFs).  What if I don't care about tagged PDFs or accessibility?....and still need PDFCopyFields to carry over the form fields intact. So far I'm forced to keep using the PDFCopyFields since it does exactly what I need for PDF concatenation with Interactive Form Fields.  Is it possible to update PDFCopy to have an option to copy over the fields if PDFCopyFields is going away?


text:
Q: Matplotlib colorbar - changed behavior for limits I try to limit the range of a colorbar using matplotlib. The old behavior was, that the colorbar could be scaled using vmin and vmax keywords of the plot function. This affected both the color itself and the labels of the color bar.
Now the behavior seems to be, that only the color is scaled, while the labels remain the automatic ones.
import numpy
import numpy.random
import matplotlib.pyplot as plt

# create somehing to plot, maximum value should be much large than 10
z = numpy.random.rand(20, 20) * 57.8412
t = numpy.linspace(0, 1, 20)
x, y = numpy.meshgrid(t, t)

# this is supposed to be the maximum value of the plot
max_value = 25 # or 100

fig = plt.figure()
axis = fig.add_subplot(1, 1, 1)

plot = axis.contourf(x, y, z, 100, cmap=None, vmin=0, vmax=max_value)
cbar = plt.colorbar(plot)

plt.show(block=False)

The labels of the color bar remain the same for both pictures (up to 58), even though the maximum value should either be 25 for the first picture or 100 for the second one.
How do I restore the hold behavior and also scale the labels of the color bar.

A: I'm not sure I understand the desired outcome, but I think you would want to set the levels explicitely.
import numpy as np
import matplotlib.pyplot as plt

# create somehing to plot, maximum value should be much large than 10
z = np.random.rand(20, 20) * 57.8412
t = np.linspace(0, 1, 20)
x, y = np.meshgrid(t, t)

# this is supposed to be the maximum value of the plot
max_value = 25 # or 100

fig, ax = plt.subplots()
ax.set_title(f"max_value={max_value}")
cntr = ax.contourf(x, y, z, levels=np.arange(max_value+1), vmin=0, vmax=max_value)
cbar = fig.colorbar(cntr)

plt.show()

A: The problem is your values in z are greater than 25. If you want to limit the scale values to 25 or less, you need to either truncate the values in z that are greater than 25, or remove them before you make the plot.
Here is an example of truncating the values in z to 25 or less:
import numpy
import numpy.random
import matplotlib.pyplot as plt

znew = z
znew[z > 25] = 25

t = numpy.linspace(0, 1, 20)
x, y = numpy.meshgrid(t, t)

# this is supposed to be the maximum value of the plot
max_value = 25 # or 100

fig = plt.figure()
axis = fig.add_subplot(1, 1, 1)

plot = axis.contourf(x, y, znew, 100, cmap=None, vmin=0, vmax=max_value)
cbar = plt.colorbar(plot)

plt.show(block=False)

Alternatively, you could simply remove those values by setting them to NaN:
znew = z
znew[z > 25] = numpy.nan

t = numpy.linspace(0, 1, 20)
x, y = numpy.meshgrid(t, t)

# this is supposed to be the maximum value of the plot
max_value = 25 # or 100

fig = plt.figure()
axis = fig.add_subplot(1, 1, 1)

plot = axis.contourf(x, y, znew, 100, cmap=None, vmin=0, vmax=max_value)
cbar = plt.colorbar(plot)

plt.show(block=False)


text:
Q: I am missing the Issue tracking list, do I need to activate some feature? I am using sp2013. I have created a new website and selected the projecttemplate. When I go to site content I miss some OOTB lists:

Issue Tracking
Links

Do I need to activate some features which are generate this lists? When I click on "Add an app" I can create by my self a new links or issue tracking list. But I was expecting OOTB these lists are created.

Like you see below, the feature is already activated.

I hope you understand my question. Because when I click on add new app it is possible to add these lists. But I was expecting them OOTB in my site content.

Do you have these lists OOTB already created in your site content? Please make a printscreen of your site content.

A: I just created a new site collection with the project template, and as you mention the 2 list are not added by default. Add the lists and you get them as web parts.
If you ever are missing out any of the lists, just activate the Team collaboration list feature.
Team collaboration lists provide the following:
Libraries

*

*Form Library

*Picture Library

*Document Library

Lists

*

*Announcements

*Calendar

*Contacts

*Custom List

*Custom List with DataSheet view

*Discussion board

*External List

*Issue tracking list

*Links

*Project List

*Survey

*Tasks


text:
Q: How to conditionally reference a DLL based on a compilation symbol? Visual Studio 2013.
I have an external DLL which I am referencing like this in the csproj file:
  <ItemGroup>
    <Reference Include="NameOfDll">
      <HintPath>Path\To\Dll\NameOfDll.dll</HintPath>
    </Reference>

I want this reference to function when a compiler symbol exists and to not function when that compiler symbol does not exist. (To address the first comment, below, let's say the compiler symbol is called Fred.)
This question
[ Conditional Reference ]
made me think I could add an attribute called Condition to the Reference element shown above but I can't work out what value to give that attribute to effect what I want.
I'd be most happy to be given a way to do this in the VS UI but I'll take any method.

A: The conditional compilation symbols are in the DefineConstants MSBuild property. Check that this contains your symbol:
<Reference Include="NameOfDll" Condition="$(DefineConstants.Contains('Fred'))">
  <HintPath>Path\To\Dll\NameOfDll.dll</HintPath>
</Reference>

Pick a distinctive name for the symbol. Not something that could be a substring of another constant like Debug or Trace.


text:
Q: Angular Rest Api con HttpClient Estoy llamando a un servicio que ejecuta una función adentro.
this._itemService.searchProducts(product).subscribe(
   data => this.products = data
);

El problema esta en que la primera vez que se ejecuta no carga el valor en this.products. Simplemente queda como "undefined".
Al hacer click nuevamente en el Front si me carga correctamente todo..
Será algún problema async de typescript?
Muchas gracias


text:
Q: Can not use components from imported module I have a simple task I'm trying to accomplish. I've created a SharedModule with a component called InputComponent. I want to use this component in SigninComponent which is part of the AuthModule. I export the InputComponent from SharedModule and import the SharedModule into the AuthModule. However, when I use <app-input>, I get the following error:
src/app/auth/signin/signin.component.html:3:5 - error NG8001: 'app-input' is not a known element:
1. If 'app-input' is an Angular component, then verify that it is part of this module.

shared.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { InputComponent } from './input/input.component';

@NgModule({
  declarations: [
    InputComponent
  ],
  imports: [
    CommonModule
  ],
  exports: [
    InputComponent
  ]
})
export class SharedModule { }

input.component.ts
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-input',
  templateUrl: './input.component.html',
  styleUrls: ['./input.component.css']
})
export class InputComponent implements OnInit {

  @Input() label?:string;
  @Input() inputType?:string;

  constructor() { }

  ngOnInit(): void {
  }

}

auth.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SharedModule } from '../shared/shared.module';

import { SigninComponent } from './signin/signin.component';
import { SignupComponent } from './signup/signup.component';
import { SignoutComponent } from './signout/signout.component';

@NgModule({
  declarations: [
    SigninComponent,
    SignupComponent,
    SignoutComponent
  ],
  imports: [
    CommonModule,
    SharedModule
  ]
})
export class AuthModule { }

signin.component.html

Sign In

<form>
    <app-input inputType="email" label="Email Address"></app-input>
</form>

Any help would be greatly appreciated. I feel like I'm missing something small and just can't figure it out.
Extra note
I have other components within the same AuthModule (SignoutComponent for example), that will throw the same error if I try to use <app-signout>

A: Posting here just incase someone runs into something similar.
Due to how I had routing setup, I was eagerly loading my Auth components. (not lazy loading) In order to get this to work, I needed to import my AuthModule to my AppModule.


text:
Q: Converting SAS code to another language, to turn into self-contained distributable exe I am a SAS programmer, and have built an opioid morphine milligram equivalent (MME) calculator using Base/SAS.  Deploying any kind of SAS distributable is difficult because the end-user would have to have a SAS license, which is very expensive. I do have the option of SAS/Connect, which is a client/server setting, but I want my end-users to keep their data on their systems, and not upload to a SAS server in the cloud.  The reason is, the data privacy is very important with medical claims.  So.  The code is not terribly complicated, but I don't know where to start to convert it to a self-contained executable with a user interface so that the end-user can browse a file on their system, then run the program to calculate the MME per patient.  The deliverable back to the end user would be summary file(s) of the patient's daily opioid MME dose, and other reports the end-user may want.  I can do all of this in SAS but SAS does not make it is to distribute code.  Maybe if I share the code and explain what it does, someone could help me?  It would be a paying job $$.
Here is the SAS code using Hash Tables.
The second method of calculating a patient's daily opioid MME dose involves SAS Hash Tables.  I have relied on several SAS papers describing how to use hash tables, please see the references section at the end of this article.
Assume dataset CLAIMS has the following columns:  PATIENT_ID, RX_FILL_DATE, NDC_CODE, DAYS_SUPPLY, QTY_DISPENSED, DAILY_MME_DOSE, STRENGTH_PER_UNIT, MME_CF (MME conversion factor), and that the DAILY_MME_DOSE column has already been calculated using the formula below:
DAILY_MME_DOSE = STRENGTH_PER_UNIT*(QTY_DISPENSED/DAYS_SUPPLY)*MME_CF
Create a DATA _NULL_ step, which will loop through the dataset CLAIMS, and add the patient's daily MME doses across multiple opioid prescriptions and multiple prescribers, if there are any.
DATA _NULL_;
    FORMAT DATE DATE9.;
        /* define the hash table PATIENT_MMES, it starts out empty */
DECLARE HASH PATIENT_MMES();
/* define the two-part key for the hash table: PATIENT_ID and DATE */
RC=PATIENT_MMES.DEFINEKEY('PATIENT_ID','DATE');
/* define the data to be included in the PATIENT_MMES hash table, adding the TOTAL_MMES column, which we will be adding to as we iterate through the dataset CLAIMS */
    RC=PATIENT_MMES.DEFINEDATA('PATIENT_ID','DATE','TOTAL_MMES');
    RC=PATIENT_MMES.DEFINEDONE();

/* iterate through the CLAIMS dataset until the end-of-file (EOF) is reached */
    DO UNTIL (EOF);
      SET CLAIMS END=EOF;
      /* initialize TOTAL_MMES to missing */
      TOTAL_MMES = .;

      /* iterate through the entire days supply of each opioid script: */
        DO I = 0 TO (DAYS_SUPPLY-1);

           /* define DATE as a dynamic date counter, it will loop through             every day in the drug's days supply */
         DATE = RX_FILL_DATE + I;

         /* define DAY as the day number of the DAYS_SUPPLY */
         DAY = I+1;

         /* initialize TOTAL_MMES to the first DAILY_MME_DOSE */
         TOTAL_MMES = DAILY_MME_DOSE;

/* use the Find function to look up the patient_id and the date.          If the combination is not found, then add the patient_id, date, and TOTAL_MMES to the hash table PATIENT_MMES */

           RC=PATIENT_MMES.FIND();
         /* RC is 0 if the patient_id, date combination was found
              RC is not 0 if the patient_id, date combination was not found
            If not found, then add to the hash table */

             IF RC NE 0 THEN PATIENT_MMES.ADD();
         /* If the patient-date combination is found, because we already
 added it, then increment the TOTAL_MMES by the DAILY_MME_DOSE */

         IF RC=0 THEN
         DO;
            TOTAL_MMES = TOTAL_MMES + DAILY_MME_DOSE;
            /* if the combination was found, then replace the
  TOTAL_MMES with its new, incremented value */
            RC=PATIENT_MMES.REPLACE();
         END;

    END;
    /* when the end-of-file is reached, output to the dataset
       PATIENT_DATE_SUMMARY */
    IF EOF THEN PATIENT_MMES.OUTPUT(dataset: 'PATIENT_DATE_SUMMARY');
    STOP;
  RUN;

A: There is no tool that takes a SAS program or step and compiles it into a separate .exe or .dll.
If you are working at a company that has a SAS Server installed you can published your code as a stored process, and other users can run the stored process through a browser when they are logged into the SAS Server.
You can create a .dll or (.exe) that protects the computation method and makes it available to non SAS environs.  The .dll would require all the data for the computation be passed into it, or some data retrieval parameters if the .dll is supposed to retrieve the data itself (2 examples: (1) a data filename, or (2) an odbc connection string and query).
SAS has several interfacing methods and call routines that allow a SAS session to execute a method in a dynamic load library (.dll) or run an external program.
DLL:

*

*module call routine

*modulen function

*modulec function

EXE:

*

*X statement

*%SYSEXEC statement

If you are looking to make a whole bunch of data reporting features available to a wide audience of non-SAS users you will have to implement that functionality in a non-SAS system that is widely and freely distributable, some examples:

*

*separate exe you compile and distribute that users can run

*

*might require other (non-SAS) 3rd party library licensing to get the output charts you want

*web server endpoint

*

*output be generated by technology such as R, PHP, Perl, ASP, etc...

*program source code for different system (such a R)

*

*Users would install R and run the source code themselves

The requirement to protect the health data means the most likely scenario is you MME computation is performed and delivered through some sort of web server.  This also provides you the greatest control over 'versions' of the computation that users will be using.

A: You probably still want to use "a statistics-oriented language," and one possibility that occurs to me is the open-source language "R."
https://en.wikipedia.org/wiki/R_(programming_language)
Now, this is not a direct "answer" to your question but it might be a pointer in a viable direction.  "R" is specifically oriented towards statistics work, and, unlike SAS (which consists of macro-calls except in the DATA steps), it is entirely a procedural programming language.  Hope this helps ...
(Both SAS and SPSS today include interfaces to "R," because it is a powerful adjunct to both of these tools and somewhat "fills a hole" in their traditional approaches.)
Another open-source programming language that is often used in statistics work, in conjunction with "R," is Python:
https://en.wikipedia.org/wiki/Python_(programming_language)
It is particularly well-suited to working with lists, and I see these two products being successfully used together in projects where SAS or SPSS might otherwise be used.  Both have a vibrant and active user community and are well-supported.

A: For SAS developers who consider doing this, the thought is to work with a statistics oriented language. That is fine but a lot of the stats I see are not statistically bound but more of a thought flow vs a particular proc. Statistics leads to a polynomial and that is then implemented. YMMV. Look at the SAS code above and it does not use any stat proc that I see.
I would strongly say don't use R. It is an aging language and Python seems to have taken its usefulness.
For exes, I would also say that it is best to not go that route. Why? They are hard to distribute and can be reverse-engineered.
The world I am working on, right now, is the suggested path which is server-side Blazor (aka, C#/.NET). Cross-platform, secure code base (no IP loss), works almost as seamlessly as a Windows app but distributed over the web. Behind the scenes, you can use whatever language to determine the formula but deliver it via the web using something else.

A: If you want to let them keep their data in their system then you probably need to convert the logic to SQL.  You might look into using windowing functions that most modern implementations of SQL support (unlike SAS's PROC SQL). But if performance is an issue you might end up needing custom code for each different database engine you want to support as each SQL implementation will have its own idiosyncrasies.
For example your algorithm could easily be implemented in Teradata's SQL by joining your input data to the SYS_CALENDAR.CALENDAR view on CALENDAR_DATE between RX_FILLED_DATE and RX_FILLED_DATE+DAYS_SUPPLY.  Then just generate the sum of DAILY_MME_DOSE grouped by the PATIENT_ID and CALENDAR_DATE.  In some other database you might need to build your own calendar table or view.


text:
Q: Is there a way to set the amount of memory available in the iPhone Simulator? Does anyone know if its possible to set the amount of memory available in the simulator?
I'm assuming the simulator will use as much memory as possible from the system but this makes it more difficult to recreate certain low memory crashes/bugs.

A: You can invoke the "Simulate Memory Warning" in Simulator.  Go to the "Hardware" pulldown menu.  That's really about as far as you can go.

A: Apple documentation states that you can only simulate the low memory warning.
Having said that, there are limitations when invoking from the menu. Here's a post that lets you better simulate real world scenarios when trying to invoke the warning: Easier low memory warning simulator testing with keyboard shortcuts
I agree with @Jasarien that trying to limit the memory within the simulator is an artificial test and should be done on the device.

A: No it isn't possible.
Testing things like memory consumption and performance should be done on the device, not the simulator. Even if you could limit the memory in the simulator you wouldn't get the same effect as there are very many different factors that will dictate how much available memory any given iPhone device will currently have.
You can simulate a "memory warning" to test if your responses to that warning behave correctly, but other than that, you should really be testing this kind of thing on a physical device.

A: No this is not possible.
You can always simulate the memory warning situation. According to this you can also verify with the profiler how much memory your app is using see what limits you exceed.


text:
Q: How To Update multiple tables In MS Access with VBA? Every month I have to UPDATE my MS Access db from approximately 30 excel files. They have all the same structure and format. firstly, I have to consolidate all the data from all excel sheets in one.
Then I run the code (below) to update my db. However I run the code for every tables because I don't know how to improved the code in order to update using the primary key.
So have 3 questions:
The most important for me is : How can i make this vba code update all the tables in once based on the Primary Key?
Is it possible to say to the vba code to look at specific range in the excel template which correspond to a specific column in the MS Access db? In order to avoir to consolidate all the excel sheets before updating the db.
An then if both question below can be solved: Is it possible to select the Folder where all these excel files are and the code will loop through all files?
Public Sub UpdatePriceList()
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim sProduct As String, sVariety As String, cPrice As Variant
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
    "Data Source=C:\Users\Gord\Desktop\Database1.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "PriceList", cn, adOpenKeyset, adLockOptimistic, adCmdTable

Range("A2").Activate  ' row 1 contains column headings
Do While Not IsEmpty(ActiveCell)
    sProduct = ActiveCell.Value
    sVariety = ActiveCell.Offset(0, 1).Value
    cPrice = ActiveCell.Offset(0, 2).Value

    rs.Filter = "product='" & sProduct & "' AND variety='" & sVariety & "'"
    If rs.EOF Then
        Debug.Print "No existing record - adding new..."
        rs.Filter = ""
        rs.AddNew
        rs("product").Value = sProduct
        rs("variety").Value = sVariety
    Else
        Debug.Print "Existing record found..."
    End If
    rs("price").Value = cPrice
    rs.Update
    Debug.Print "...record update complete."

    ActiveCell.Offset(1, 0).Activate  ' next cell down
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

thank you in advance!


text:
Q: Logstash conditional check for nil/null value in a field I have a json data with some field value as null (eg: "location": null). I would need to check whether this field is null, and take some action.
I have tried using if [location] == 'null' { do something } but it fails, also I have tried with if [location] == 'nill' { do something }
Found some relative links that mentioned to check whether the field exist if [location] but this can't be used in my case.
Please help me to solve this, thanks in advance.

A: You will need to use the ruby filter to check if the field has a null value.
The following filter checks if the field is null and then, if true, adds a tag to the event.
ruby {
    code => "if event.get('location').nil?; event.set('tags','null-value');end"
}

You can then use the tag normally in logstash to do what you want, for example
if "null-value" in [tags] { do something }


text:
Q: Is there any level of physics that is "solved"? At each level of physics, between rotating galaxies, orbiting planets, wind and motion of matter, to motion of molecules, atoms, particles, and maybe strings, there's always some degree of uncertainty in predicting the physics from theory. Relativity and quantum mechanics are the usual culprits in this uncertainty, but sometimes it's just the huge number of complicated interactions that make the physics impossible to calculate (e.g. even the 3-body problem has no known closed-form solutions)
So my question is, is there a level of physics that is "solved" per se?
I can think of quantum electrodynamics which is experimentally verified to ten parts in a billion, but I was hoping to understand more examples. Thank you.

A: How can you guarantee that there will be no physics discovered in the future that will resolve to our theoretical physics of today, while at the same time providing a greater depth of knowledge?
You can't, no one can. Only mathematical proofs can be considered to be solved, or closed.

A: From a purely practical standpoint, there are a number of fields of study which by now contain very few unanswered questions and can be considered (again, for practical purposes) "solved". These include AC and DC circuit analysis (both lumped and distributed), continuum mechanics (elastic behavior of beams, columns, etc.), subsonic airflow around wings, fluid mechanics (even though the navier-stokes equations still cannot be solved explicitly in most cases), dynamic systems analysis both in the time and frequency domains (i.e., newton's laws for complex machinery), and heat transfer and thermodynamics.
In short: if you can take engineering classes in a technical field, physicists will have moved on to something else.


text:
Q: Spring with AMQP and RabbitMQ, queue with optional x-dead-letter-exchange I have an existing queue created in RabbitMQ. It can be created with or without x-dead-letter-exchange parameter. I am creating a consumer of this queue in Spring using the RabbitTemplate. When I declare the queue, I don't want to specify the x-dead-letter-exchange parameter. I would like the template to somehow figure it itself or not care. I am throwing AmqpRejectAndDontRequeueException from my consumer to indicate bad messages, but I want the creator of the queue to be responsible for the decision whether or not to create an exchange and queue for the rejected messages.
Here is my bean that declares the queue in Spring:
@Bean
Queue queue() {
    Map<String, Object> args = new HashMap<>();
    // set the queue with a dead letter feature
    args.put("x-dead-letter-exchange", REJECTED_EXCHANGE);
    args.put("x-dead-letter-routing-key", REJECTED_ROUTING_KEY);
    Queue queue = new Queue(Constants.QUEUE_NAME, false, false, false, args);
    return queue;
}

This works fine, but when the creator of the queue decides not to use the dead letter feature, I see the following error:
Channel shutdown: channel error; protocol method: #method<channel.close>
(reply-code=406, reply-text=PRECONDITION_FAILED -
inequivalent arg 'x-dead-letter-exchange' for queue 'queueName'

The message is a bit longer, it continues telling me which side has which x-dead-letter-exchange (none or a name of the exchange). I've tried different combinations (e.g. creating the queue with exchange and not specifying it in the Spring or creating the queue without the exchange and specifying it in the Spring), only to see different variants of this message.
How do I declare the queue so it simply accepts whatever parameters are already set in the queue?

A: Yes, The possible cause is - if you declare some queues manually and later your program (client in code) tries to create one (based on the settings you had in code) then you get this error. The reason behind it is when your code (client application) tries to access one queue. It gets a signal from the server that the connection is not available for this.
To solve this problem

*

*Delete all the queues that you have created manually, and let the client program create them by itself.

*If you got problems in deleting the queues, because of some data is there in it, or for some reason, you want to maintain it, create one queue manually, and move all the queue data to be deleted in it through "Move" tab of the queue.

A: As you can see in the spring docs: The RabbitMQ broker will not allow declaration of a queue with mismatched arguments., so you can't do it.
In the RabbitMQ Java API there is a method to check whether a queue already exists: queueDeclarePassive.
If the Spring AMQP API provides a similar functionality you can use it before trying to declare the queue.

A: Yes.This kind of issue happens when you have created exchanges or queues manually in rabbitMQ and then you application try to create other one.And it finds the same queue or exchanges with different properties/configuration so it shows mismatch in configuration.
Solution:
Allow your application program to create exchanges and queues only.
Hope this helps.

A: From: https://github.com/jondot/sneakers/issues/121

Try completing all the messages in the queue, delete the queue, then
  try and re-declare it with the code that failed above. I think you'll
  find this particular error goes away


text:
Q: missing $ error when creating a table I am going to create a table using the following commands. I use the xepersian package.
\begin{latin}
\begin{table}[h!]
\centering
\begin{tabular}{|c c c|}
 \hline
 p & q & \varphi_q^p(x)\\ [0.5ex]
 \hline
 p & -1 & \vert x \vert^p \\
 2 & 0 & ln(x^2+1) \\
 2 & -0.5 & 2 \sqrt{x^2+1}-2 \\
 2 & 1 & \frac{x^2}{x^2+1} \\
 1 & 1 & \frac{\vert x \vert}{\vert x \vert +1} \\ [1ex]
 \hline
\end{tabular}
\label{table:1}
\end{table}
\end{latin}

Although I used the latin environment I got the error of missing $. How can I solve this problem?

A: Using the amsmath package for formulas and enclosing them properly, ie $formula$, will remove the error.
\documentclass[12pt]{article}
\usepackage{amsmath}

\begin{latin}
\begin{table}[h!]
\centering
\begin{tabular}{|c c c|}
 \hline
 p & q & $\varphi_q^p(x)$ \\ [0.5ex]
 \hline
 p & -1 & $\vert x \vert^p$ \\
 2 & 0 & $\ln(x^2+1)$ \\
 2 & -0.5 & $2 \sqrt{x^2+1}-2$ \\
 2 & 1 & $\frac{x^2}{x^2+1}$ \\
 1 & 1 & $\frac{\vert x \vert}{\vert x \vert +1}$ \\ [1ex]
 \hline
\end{tabular}
\label{table:1}
\end{table}
\end{latin}

\end{document}

A: As Leucippus implies, subscripts (_{}), superscripts (^{}), \frac, \sqrt, \ln, \vert are commands that can only be used in math mode, so you need to enclose them in dollar signs or \( ... \).  As such he has answered your question, this answer is just a suggestion for an alternative way of typesetting that table.
Changes:

*

*I've added the array package, and used *{3}{>{$}c<{$}} as the column specification for the table. This will create three c columns (*{3}) where a $ is inserted at the start (>{$}) and end (<{$}) of each cell, effectively setting all cells in math mode.

*I've loaded booktabs and used \toprule, \midrule and \bottomrule instead of \hline, while removing vertical rules. A lot of people prefer this style of tables, see for example the manual of booktabs.

*mathtools provides \DeclarePairedDelimiter, with which I've defined the \abs macro to set the absolute values.
Additional note:

*

*Often when using [h!] as a float specifier, you will get a warning saying  `h' specifier changed to `ht'. This is because there is no room for the table exactly where you put it, so h is not an option. Therefore it is recommend to use at least ht as float specifiers, thereby giving LaTeX some more freedom as to where the float should be placed. See for example `h' float specifier changed to `ht' warning when not attempting to specify a float

\documentclass[12pt]{article}
\usepackage{array,booktabs,mathtools}
\DeclarePairedDelimiter\abs{\lvert}{\rvert}
\begin{document}
\begin{tabular}{*{3}{>{$}c<{$}}}
\toprule
 p & q & \varphi_q^p(x) \\ [0.5ex]
\midrule
 p & -1 & \abs{x}^p \\
 2 & 0 & \ln(x^2+1) \\
 2 & -0.5 & 2 \sqrt{x^2+1}-2 \\
 2 & 1 & \frac{x^2}{x^2+1} \\
 1 & 1 & \frac{\abs{x}}{\abs{x}+1} \\
\bottomrule
\end{tabular}
\end{document}


text:
Q: Remove plus sign from url using .htaccess My current url is:
http://localhost/mywbsite/search/one+piece/149

I want to change link to like this
http://localhost/mywbsite/search/one-piece/149

I have already .htaccess file with this code
Options -MultiViews
RewriteEngine On
RewriteBase /indianrealitybytes/

RewriteCond %{THE_REQUEST} /search_advance\.php\?keywords=([^&]+)&f=([^\s&]+) [NC]
RewriteRule ^ search/%1/%2? [R=301,L]

RewriteRule ^search/([^/]+)/([^/]+)/?$ search_advance.php?keywords=$1&f=$2 [QSA,L,NC]

I don't know where to change to remove plus(+) sign to dash (-) sign

A: You can add a new rule for +/- conversion:
Options -MultiViews
RewriteEngine On
RewriteBase /indianrealitybytes/

RewriteCond %{THE_REQUEST} /search_advance\.php\?keywords=([^&]+)&f=([^\s&]+) [NC]
RewriteRule ^ search/%1/%2? [R=301,L]

RewriteRule ^([^+]*)\+(.*)$ $1-$2 [R=302,NE,L]

RewriteRule ^search/([^/]+)/([^/]+)/?$ search_advance.php?keywords=$1&f=$2 [QSA,L,NC]


text:
Q: Handling Loop And Array in Jmeter + Groovy - Response code 500 I am trying to create a script that perform a loop, and fill array with Http results.
the expected results is array with passwords, with the size of the loop (in the example 3).
The problem is that in each iteration of the loop it is not familiar with the array that I created in the first iteration of the loop.
Can someone please advise how to fill an array inside a loop in Jmeter?
Or how to solve this issue? any example will be  great
res_g1 - is the value that I want to enter to each place in the array, meanning a password.
Password - is the array that I would like to feel with data
loop counter - counts the iteration of the loop 1,2,3
def loop_counter = ${__counter(TRUE)};
def results = vars.get('res_g1')
if (loop_counter == 1)
{
    def  Password = new String[3];
    System.out.println("Entered the loop");
}

Password[loop_counter -1] = vars.get('res_g1');
System.out.println("loop number is :  " + loop_counter + " Password is" + results );

A: Here is how to do it:
Use a Counter element inside loop:

Then use this script:

Pay attention to:

*

*Cache compiled script being checked for performances

*the storage of the array I want to fill as a Variable using vars.putObject(...)

*the vars.getObject(.) to get it back

*The use of Logger.info from SLF4J for logging instead of System.out.println


text:
Q: Extract content from local HTML file with RapidMiner I'm trying since 5 h to retrieve specific content from a locally saved html document. Mainly I would like to gather the Value "Worldwide" and "3,041,070".

Worldwide

#3,041,070

I really do not know which operators I must choose to get everything working.

A: I figured it out. In combination with Regular Expression I made it work.enter image description here

A: First form the extensions install the text mining models the run this simple example. You will get both values.
<?xml version="1.0" encoding="UTF-8"?><process version="7.3.001">
  <operator activated="true" class="text:extract_information" compatibility="7.3.000" expanded="true" height="68" name="Extract Information" width="90" x="313" y="85">
    <parameter key="query_type" value="Regular Expression"/>
    <list key="string_machting_queries"/>
    <parameter key="attribute_type" value="Nominal"/>
    <list key="regular_expression_queries">
      <parameter key="Type" value="itemprop="significantLink">(.*)</a></div>"/>
      <parameter key="Value" value="">#(.*)</span>"/>
    </list>
    <list key="regular_region_queries">
      <parameter key="ValueType" value="itemprop="significantLink">.</a></div>"/>
      <parameter key="Value" value="data-value=".">"/>
    </list>
    <list key="xpath_queries"/>
    <list key="namespaces"/>
    <parameter key="ignore_CDATA" value="true"/>
    <parameter key="assume_html" value="true"/>
    <list key="index_queries"/>
    <list key="jsonpath_queries"/>
  </operator>
</process>


text:
Q: CSS width issue on mobile responsive Wondering why the 2 pages, About and Contact have different width when it comes to the text.
They are both using the same style but one is narrow and one is wider. Mainly noticed this on the mobile version especially and its driving me crazy.
https://genesisventuresinvestments.com/about.html
https://genesisventuresinvestments.com/contact.html
.dummy-dummy-text{
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: -1;
  padding: 0 20px;
  transform: translate(-50%, -50%);
}

A: I used word-break: break-word and works fine, however I'd recommend using clamp() to edit the font size as a best practice, here are some suggestions
h1 {
font-size: clamp(1.913rem, calc( 12px + 2.475vw ), 2.587rem);
line-height: 1.1;
}

h2 {
font-size: clamp(1.575rem, calc( 12px + 1.800vw ), 2.025rem);
line-height: 1.1;
}

h3 {
font-size: clamp(1.282rem, calc( 12px + 1.350vw ), 1.688rem);
line-height: 1.1;
}

h4 {
font-size: clamp(1.125rem, calc( 12px + 0.900vw ), 1.350rem);
line-height: 1.1;
}

p {
font-size: clamp(1.035rem, calc( 12px + 0.540vw ), 1.125rem);
line-height: 1.1;
}

span {
font-size: clamp(0.900rem, calc( 12px + 0.360vw ), 1.012rem);
line-height: 1.1;
}


text:
Q: Proof of a theorem in distribution theory (probably Cochran's Theorem) I want to prove the following theorem (I'm not sure but probably it is called Cochran's Theorem) :
Let $X$ follows $n$-variate multivariate normal distribution with mean vector $\mathbf{\mu}$ and covariance matrix $\Sigma$. Also let $A_1,A_2,\dots,A_m$ be symmetric projection matrices of order $n$ such that $rank(A_i)=r_i$ and $\sum_{i=1}^m A_i=I$. Let $U_i=X^TA_iX$. Show that $U_i$'s are independent random variables, respectively distributed as $\chi_{r_i}^2$.
I cannot find the idea to attack the problem. If anyone can give me any lead (even for the simple $m=2$ case, which I may generalize), I'll me much grateful. Thank you.


text:
Q: Drupal 7 local install faliure Doing my very first loading of local Drupal 7 with Xampp and install went well. In Windows 7 tried to open localhost in browser and received this error message:

Warning: require_once(C:\xampp\htdocs\drupal/includes/bootstrap.inc):
  failed to open stream: No such file or directory in
  C:\xampp\htdocs\drupal\index.php on line 19
Fatal error: require_once(): Failed opening required
  'C:\xampp\htdocs\drupal/includes/bootstrap.inc'
  (include_path='.;C:\xampp\php\PEAR') in
  C:\xampp\htdocs\drupal\index.php on line 19

This was a stock standard install until this.

A: Make sure that you have the file named bootstrap.inc inside includes folder.