text:
Q: How does Angular2's pipes work with data binding? I'm writing a simple todo app to learn Angular 2. I noticed that using pipes break the update behavior.
I have the following template
<input type="text" placeholder="Search" #queryBox (keyup)="query=queryBox.value">

<ul class="task-list">
    <task-item *ng-for="#task of tasks | filter:containsString:query" [task]="task" (onDelete)="delete($event)"></task-item>
</ul>

and when I click on the delete button, the underlying data model is changed but this change is not reflected in the UI. I have determined it's because the filter pipe doesn't get called. If I change the above line to
<task-item *ng-for="#task of tasks" [task]="task" (onDelete)="delete($event)"></task-item>

then things like add, delete works again, but obvious I don't get filtering. Why would adding pipes break the update behavior of this binding?

A: That's because by default Pipes are stateless (they render UI just once).
You have to add :
 @Pipe({
  selector: ...,
  pure: false
})

When you set 'pure' to false, Angular updates the data inside the pipe each cycle.

A: By default, pipes are stateless/pure. If their inputs don't change, the pipes are not executed during a change detection cycle. For this question, where we have
"#task of tasks | filter:containsString:query"

tasks, containsString and query are the inputs, and pipe filter is stateless/pure. tasks is an array (reference).
When a task is deleted, the array reference doesn't change – the tasks input to the pipe doesn't change – hence the stateless/pure pipe is not executed.
If we make the pipe stateful with pure: false, then the pipe will be evaluated on every change detection cycle – even if the inputs do not change.
You may also need to either

*

*specify the onPush change detection strategy for the component (if possible), or

*implement the pipe's transform() method such that it returns the same array (reference).

These alternatives are explained in detail in this answer (I don't want to repeat all of that here).


text:
Q: 'await' won't work even in an async function I googled this but can't find a result that relates to my problem. I put 'await' in an async function but node.js says "SyntaxError: Unexpected identifier". Can someone help? I just started learning JavaScript recently.
async function removeFile(data) {
    return new Promise((resolve, reject) => {
        try {
            if (!data.arg) {
                //check if there's filename
                data.msg.channel.send("What did you want me to remove baka?").then(async result => {
                    data.client.setTimeout(data.tsundere, 5000, result);
                });
            } else {
                //check if there's repo id in the config file (Personal)
                if (!data.config.group && !data.config.repo_id) {
                    data.msg.channel.send("Hmmph! Please set the repo channel ID in the config file first?");
                    //check if the channel is valid (Personal)
                } else if (!data.config.group && !data.msg.guild.channels.has(data.config.repo_id)) {
                    data.msg.channel.send("You just wasted my time finding an inexistent channel!");
                    //check if the repo channel is set through the repo command
                } else if (data.config.group) {
                    data.shimautils.sdataCheck(data.sdata, data.msg.guild.id).then(onRes => {
                        if (onRes.length < 1) {
                            data.msg.channel.send("There's no repo channel set!");
                        } else {
                            //insert good stuff here
                            data.msg.channel.send("This command is WIP!");
                            let gch = data.msg.guild.channels.get(data.sdata.get(data.msg.guild.id)[0]),
                                temp;
                            //the problem lies here
                            await getMessages(data.msg.guild, data.msg.channel);
                            console.log(temp);
                            data.msg.channel.send(temp.size);
                        }
                    }, async () => {
                        data.msg.channel.send("There's no repo channel set!");
                    });
                } else {
                    //insert good stuff here (Personal)
                    data.msg.channel.send("This command is WIP!");
                }
            }
        } catch (err) {
            reject(err)
        }
        resolve(true);
    });
}

edit: Here is the content of getMessages()
getMessages() is used to get messages in a channel.
async function getMessages(guild, channel) {
    return new Promise(async (resolve, reject) => {
        try {
            if (!channel.id) {
                reject(false);
            } else if (!guild.channels.has(channel.id)) {
                reject(false);
            } else {
                var fetchedMessages, fetchedSize, plscontinue = true,
                    firsttime = true;
                channel.fetchMessages({
                    'limit': 100
                }).then(async result => {
                    fetchedMessages = result.clone();
                }, async rej => {
                    reject(rej);
                });
                while (plscontinue) {
                    if (firsttime) {
                        fetchedSize = fetchedMessages.size;
                        firsttime = false;
                    }
                    if (fetchedSize == 100) {
                        plscontinue = true;
                        channel.fetchMessages({
                            'limit': 100,
                            'before': fetchedMessages.lastKey()
                        }).then(async fetched2 => {
                            fetchedSize = fetched2.size;
                            fetchedMessages = fetchedMessages.concat(fetchedMessages, fetched2)
                        }, async err => reject(err));
                    } else {
                        plscontinue = false;
                    }
                }
            }
        } catch (err) {
            reject(err);
        }
        resolve(fetchedMessages);
    });
}

A: You can only use await directly inside the async function. And you dont need to construct a Promise, thats what async function is doing for you internally. Additionally, the sense of await is to replace the callbacks and then chains:
 async function removeFile(data) {
   if (!data.arg) {
     //check if there's filename
     const result = await data.msg.channel.send("What did you want me to remove baka?")
     data.client.setTimeout(data.tsundere, 5000, result);
    } else {
        //check if there's repo id in the config file (Personal)
        if (!data.config.group && !data.config.repo_id) {
            await data.msg.channel.send("Hmmph! Please set the repo channel ID in the config file first?");
            //check if the channel is valid (Personal)
        } else if (!data.config.group && !data.msg.guild.channels.has(data.config.repo_id)) {
            await data.msg.channel.send("You just wasted my time finding an inexistent channel!");
            //check if the repo channel is set through the repo command
        } else if (data.config.group) {
          const onRes = await data.shimautils.sdataCheck(data.sdata, data.msg.guild.id);
          if (onRes.length < 1) {
            await data.msg.channel.send("There's no repo channel set!");
           } else {
             //insert good stuff here
             await data.msg.channel.send("This command is WIP!");
             let gch = data.msg.guild.channels.get( data.sdata.get(data.msg.guild.id)[0]);

             const temp = await getMessages(data.msg.guild, data.msg.channel);
             await data.msg.channel.send(temp.size);
          }

          await data.msg.channel.send("There's no repo channel set!");

        } else {
          //insert good stuff here (Personal)
          await data.msg.channel.send("This command is WIP!");
       }
   }
   return true;
 }

The same applies to getMessage :
 async function getMessages(guild, channel) {
    if (!channel.id) {
      throw false; //???
    } else if (!guild.channels.has(channel.id)) {
      throw false; //???
    }

    let fetchedMessages = await channel.fetchMessages({ 'limit': 100 });
    const result = fetchedMessages.clone();

    while (fetchedMessages.length >= 100) {
         fetchedMessages = await channel.fetchMessages({
              limit: 100,
              before: fetchedMessages.lastKey()
         });
        result.push(...fetchedMessages);
    }
    return result;
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a download button that saves the content of a string? I have a PHP script that is producing an string that I want to download as a  file by clicking a button.
I know how to save the string in a file on the web-server and point on it with a link, but that is not what I want to do.
I want by clicking a button to stream a file to the user that contains the string.
UPDATE: What I am looking for is something very close to this :
text file

The Question that puts for me is how do I transform the $string into this base64 part and what is utf-16le ?? Can someone explain this a bit?
UPDATE actually some bad guys have felt into frustration that they are unable to answer and closed the topic. Without asking me. ome peple here take this a competition to gather points. But I went on and found the solution to my question.
You simple have to add download="file.txt"
text file

In this way you download a file. not a stream.
have fun.

A: What you want to do is to save the file on your server and then just use html like this:
Download

Of course that the link will be changed dynamically by some js or jQuery (don't know how to do it? Go to https://stackoverflow.com/a/179717)
I'd send a respond from the php file that will contain the file name or path...
Also look at this answer
https://stackoverflow.com/a/2793756

A: This could be a solution:
<?php
header('Content-type: text/plain');
header('Content-Disposition: attachment; filename="yourfilename.ini"');

//output the contents the file should contain. For example:
echo "a=1\nb=2\nc=3";
?>

Found it here


text:
Q: In TFS 2015 is there a way to increase the dashboard limit for a team project? Our team is running an instance of TFS 2015. The maximum number of dashboards per team project appears to be capped at 20 per project. I would like to create more since we are running all of our backlog under one team project.
Is there a way to increase this cap in TFS 2015? Does anyone know if update 2 or TFS 2017 increases this cap?

A: In TFS we can only create 20 dashboards per team. (Tested on TFS 2015 and 2017) and there isn't a way to modify the limits.
You have to delete an existing dashboard to create a new one once it reached 20.
I have submitted a user voice to request this feature, you can go an vote it up to achieve it in future.


text:
Q: C++ Inverting all bits in a fstream The title is my question - how would I go about flipping all the bits in an std::ifstream that's been loaded from a file?
ifstream file( "filename.png" );

if ( !file.is_open( ) ) {
    return false;
}

I don't know how I should be going from here. By flipping, I'm referring to inverting the bits (0 if 1, 1 if 0)

A: This is an X-Y problem.  I really doubt you want to flip all the bits in a PNG format file, simply because there are other fields in the file besides the bitmap bits.  Also, unless the image is pure black & white, there is more to the color bits than inverting the bits.
That said, here's how to flip the bits.
While not the end of the file, do:
  read a block of bytes (uint8_t)
  for each byte read do:
     read the byte
     invert the byte (a.k.a. using `~` operator)
     store the byte
  end-for
  write block to new file.
end-while

Side effects of inverting pixels
Most images are made up of pixels, or picture elements.  These elements are usually represented by a number of bits per pixel and if multiple colors, bits per color.
Let us take for example an RGB image with 24 bits per pixel.  This means that there are 8 bits to represent the red, 8 bits for green and 8 bits for blue.  Each color has a value range of 0 to 255.  This represents the amount of color.
Let us take 1 color, green, with a value of 0x55 or in binary 0101 0101.  Inverting (flipping) the bits will yield a value of 0xAA or 1010 1010.  So after flipping the green value is now 0xAA.
If this is what you want to happen, changing the amount of color on each pixel, then you will need to extract the color quantities from the PNG file for the image and invert them.

A: Here's one way to do it:
#include <fstream>

int main(int argc, char **argv)
{
    std::ifstream ifile(argv[1]); /// input
    std::ofstream ofile(argv[2]); /// output

    if (ifile.is_open() && ofile.is_open()) {
        char ch;
        std::string data = "";

        while (ifile.get(ch)) {
            for (unsigned int i = 0; i < 8; ++i)
                ch ^= (1 << i);
            data += ch;
        }
        ofile << data;
    }
    ifile.close();
    ofile.close();
    return 0;
}

usage:
./prog input output

input:
$ xxd -b input
0000000: 00110001 00110000 00110000 00110001 00001010

output:
$ xxd -b output
0000000: 11001110 11001111 11001111 11001110 11110101


text:
Q: How do you connect paintEvent to a slot? Just like the title says I want to connect paintEvent to a slot, so that it can be triggered by a timer, how do I do this? I can provide any more information you guys need, I'm very new to QT though, so keep that in mind.
EDIT: So I tried it in a little test program and it doesn't appear to be updating. Unless I've misunderstood how paintEvent works, I don't know what's wrong. This should move a black point (10x10 pixels) across the screen from the upper left corner to the bottom right.
Here's the header file:
#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include <QtGui>
#include <QtCore>

namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = 0);
    ~Dialog();
    QTimer *timer;

private:
    Ui::Dialog *ui;

protected:
    void paintEvent(QPaintEvent *e);

};

#endif // DIALOG_H

Here's the implementation file:
#include "dialog.h"
#include "ui_dialog.h"
#include "windows.h"

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);

    timer = new QTimer(this);
    connect(timer,SIGNAL(timeout()),this,SLOT(update()));

    timer->start(1000);
}

Dialog::~Dialog()
{
    delete ui;
}

void Dialog::paintEvent(QPaintEvent *e)
{
    QPainter painter(this);
    QPen pointPen(Qt::black);
    pointPen.setWidth(10);
    painter.setPen(pointPen);
    QPoint test;

    static unsigned int coord;

    coord = 10;

    test.setX(coord);
    test.setY(coord);

    painter.drawPoint(test);

    coord += 10;

}
Here's the client code:
#include "dialog.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Dialog w;
    w.show();

    return a.exec();
}

A: You cannot connect to paintEvent directly, since it is not a slot. Instead, connect your timer signal to repaint (to trigger an immediate repaint) or update (the preferred method, since it consolidates multiple repaint requests to avoid flicker).
EDIT
There's some quirkiness regarding updating a QDialog (see this thread on the Qt forums) -- apparently, due to a bug in Qt versions 4.6 and below (and possibly in later versions, as well).
I would refrain from overriding paintEvent on a QDialog. Instead, create a custom QWidget (which you can insert as a child into your dialog) and perform your rendering there.

A: here is a simple example ....
in widget.h file ...
class Widget:public QWidget
{
    Q_OBJECT
    QPainter    painter;
    QTimer      timer;
public:
    Widget();
    void paintEvent(QPaintEvent *);
};

in widget.cpp
Widget::Widget()
{
    connect(&timer,SIGNAL(timeout()),this, SLOT(update()));
    timer.start(200);
}

void Widget::paintEvent(QPaintEvent *)
{
    painter.begin(this);
    painter.drawRect(0,0,100,rand()%200);
    painter.end();
}

in main.cpp
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}


text:
Q: SQLAlchemy Core indexing from list within SQL I'm currently trying to convert some of my Snowflake SQL code to SQLAlchemy Core python code and I can't quite seem to figure out how to convert indexing an array within SQL to SQLAlchemy Core code.
For example if I have the following SQL query, how could I convert it to SQLAlchemy Core?
SELECT
    TRIM(SPLIT(CATEGORIES, ',')[0]) AS MAIN_CATEGORY,
    ...
FROM EXAMPLE_TABLE

So far I have tried this:
from sqlalchemy import func, select
...
select([
    func.trim(
        func.split(table.c.categories, ",")[0]
    ).label("main_category")
])

But it doesn't look like SQLAlchemy is able to convert the [0] python part to a SQL code.
Any way around this?

A: well it seems they have support for trim, and split, so you could ether try SPLIT_PART, or GET
select 'a,b,c' as a
    ,split(a, ',') as b
    ,b[0] as c
    ,get(b, 0) as c1
    ,split_part(a, ',', 0) as c2;

A
B
C
C1
C2

a,b,c
[   "a",   "b",   "c" ]
"a"
"a"
a

Not sure if/how these map to what SQLAlchemy exposes/supports


text:
Q: Best way to retrieve email from a open id that does not provide it using python social auth I've successfully implemented python social auth in my django application however I noticed that twitter does not provide an email address for me to save. is there a way of extending the social auth pipeline so I can ask for a new users email address if one is not provided?

A: The way to do it is by extending the default pipeline with a function that checks if an email was provided and ask for one in not. Check the example application at https://github.com/omab/python-social-auth/blob/master/examples/django_example, it does that with this pipeline https://github.com/omab/python-social-auth/blob/master/examples/django_example/example/app/pipeline.py.
Basically the flow is:

*

*User signup with twitter

*That pipeline checks if the user is new and if an email was returned by the auth provider

*If no email, then redirect the user to a form, otherwise continue (the form POSTs to /complete/twitter, that way the auth process will continue where it stopped)

*The pipeline function is ran again, but an email is detected in the request POST data

*The pipeline stores the email in the details which is used to create the user later


text:
Q: Mount an ISO virtually using /dev/sr0 device I'm doing a study about how CD-ROM can be mounted virtually and all I could find out was mounting using loop devices.
mount -o loop disk1.iso /mount-point

This is fairly easy.
I understand that /dev/sr0 is a block device and it point to some buffer in kernel and the kernel device driver puts the filesystem (ot whatever it puts i am not sure) in that buffer and when we use mount it mounts the filesystem to the specified mount-point.
But am wondering whether we can mount an ISO of our choice (e.g. disk1.iso) by using SCSI CD-ROM device /dev/sr0 (without changing anything in the kernel) as it is done in Vmware and Virtualbox, where we can specify the ISO and it automatically emulates a CD-ROM hardware and the ISO can be mounted using /dev/sr0 device?
The major problem which i see here is that how /dev/sr0/ will be linked to the iso?

A: The thing here is that /dev/sr0 is linked to a kernel device driver. That device driver will allow access to a physical CDROM if available through that node; VMWare and VirtualBox emulate hardware as you mention and hence the kernel and device driver think they're communicating with hardware.
The /dev/sr0 doesn't point to a certain buffer directly, it provides an interface to the block device interface that allows userspace processes to acces the contents of the hardware device.
If you want to make an image available as a block device, then your only choice (besides virtualization and emulating hardware) is to use loop devices with losetup... or to write your own replacement device driver, but I expect that's not a viable option for now.
If you want to make that image available as /dev/sr0 (are we talking about faking out some software that demands access to a CDROM at that location?) then you could move that file to e.g. /dev/sr0.moved and then symlink the appropriate /dev/loopX to /dev/sr0. Of course, if the software in question tries special commands that only apply to CDROM devices, then this won't work. Otherwise it shouldn't be a problem.

A: If you use cdemu instead of the loop mount it will give the desired effect. It emulates a cd-rom device. Where as mounting just gives access to the files. It can also be used for mounting cue/bin files and other image types. This gives the ability to mount images that have more than one track or data/music track combinations.


text:
Q: R, error in finding degree, closeness and betweenness Trying to apply the common measures of centrality to a simple data set of non-directed like this:

It gives error:
Error in closeness(net, gmode = "graph") : unused argument (gmode = "graph")

When I removed the argument (gmode = "graph), it gives:
Error in degree(W) : Not a graph object

I have tried to use this lines to convert them, but still doesn't work:
W <- graph_from_adjacency_matrix(df)
W <- graph_from_data_frame(df)

How can I correct them? thank you.
Here are the lines:
Bob <- c(0,1,0,0,0)
Kate <- c(0,0,0,1,0)
David <- c(0,0,0,1,0)
Jack <- c(0,0,1,0,0)
Peter <- c(0,1,0,0,1)
df <- data.frame(Bob, Kate, David, Jack, Peter)

library(igraph)

W <- data.frame(df)
net <- network(W)

net %v% 'vertex.names'

degree(W, gmode="graph")
closeness(net, gmode="graph")
betweenness(net, gmode="graph")

Add-on after this question is answered, in case it can help someone - to convert Excel format into a adjacency_matrix, use below lines.
df <- readxl::read_excel("spreadsheet.xlsx", sheet = "Sheet1")
W <- as.matrix(df)
W <- graph_from_adjacency_matrix(W)

A: Your code is somewhat mysterious, suggesting perhaps a use of of some other package? There is no such function network in igraph, functions degree, closeness, and betweenness don't have argument gmode. I believe the following is what you were after:
library(igraph)
# We are going to use graph_from_adjacency_matrix, so we need a matrix
# rather than a data frame
df <- cbind(Bob, Kate, David, Jack, Peter)

W <- graph_from_adjacency_matrix(df)

V(W)$name
# [1] "Bob"   "Kate"  "David" "Jack"  "Peter"

degree(W)
#   Bob  Kate David  Jack Peter
#     1     3     2     3     3
closeness(W)
#        Bob       Kate      David       Jack      Peter
# 0.05000000 0.08333333 0.11111111 0.16666667 0.05000000
# Warning message:
# In closeness(W) :
#   At centrality.c:2784 :closeness centrality is not well-defined for disconnected graphs
betweenness(W)
#   Bob  Kate David  Jack Peter
#     0     4     0     3     0

A: The function degree exists both in igraph and sna package. However, gmode argument only exists in the sna package version of it. A basic solution for this can be  using sna::degree(net, gmode="graph") can be helpful for this issue.
Source:
degree {sna}      R Documentation
Compute the Degree Centrality Scores of Network Positions
Description
Degree takes one or more graphs (dat) and returns the degree centralities of positions (selected by nodes) within the graphs indicated by g. Depending on the specified mode, indegree, outdegree, or total (Freeman) degree will be returned; this function is compatible with centralization, and will return the theoretical maximum absolute deviation (from maximum) conditional on size (which is used by centralization to normalize the observed centralization score).
Usage
degree(dat, g=1, nodes=NULL, gmode="digraph", diag=FALSE,
    tmaxdev=FALSE, cmode="freeman", rescale=FALSE, ignore.eval=FALSE)


text:
Q: Unable to store numbers using vector vector<int> oper(int A, int B) {

    std::vector <int> arrayV;

    int addition = A + B;
        arrayV.push_back(addition);
    int mutiplication = A * B;
        arrayV.push_back(mutiplication);
    int subtraction;
        if(A >=B ){
            subtraction = A - B;
        }
        else(B >A );{
            subtraction = B - A;
        }
        arrayV.push_back(subtraction);
    int division;
         if(A >=B ){
            division = A / B;
        }
         else(B >A );{
            division = B / A;
        }
        arrayV.push_back(division);
}

//Can anyone letme know where did I go wrong with my code that it keeps telling me "egmentation Fault (SIGSEGV)", I want arrayV to be able to store numbers after +, *, -, /;

A: As I and others have pointed out in the comments, you forgot to return arrayV;. Also, your else has the wrong syntax
std::vector<int> oper(int A, int B) {

    std::vector <int> arrayV;

    int addition = A + B;
    arrayV.push_back(addition);

    int mutiplication = A * B;
    arrayV.push_back(mutiplication);

    int subtraction;
    if(A >=B ){
        subtraction = A - B;
    }
    else{
        subtraction = B - A;
    }
    arrayV.push_back(subtraction);
    int division;
    if(A >=B ){
        division = A / B;
    }
    else{
        division = B / A;
    }
    arrayV.push_back(division);
    return arrayV;
}


text:
Q: CopyOf returning array jump is an array that has been initialised.
FunctionMonius3.difRandoms method returns an array
jump = FunctionMonius3.difRandoms(posMonius.length, lines * col, generator);

or
jump = Arrays.copyOf(FunctionMonius3.difRandoms(posMonius.length, lines * col, generator), v.length);

Does the first option just creates a reference that is destroyed when the method FunctionMonius3.difRandoms ends or is it ok?
   * @param n - number of array elements
   * @param sup - max value
   * @param g - generator
  public static int[] difRandom (int n, int sup, Random g){
      int[] result = new int [n];
      int i = 0;
      while (i < result.length) {
          int random = g.nextInt(sup) + 1;
          if (!contidoEmParte(aleatorio,result,i)){
              result[i] = random;
              i++;
          }
      }
      return result;
  }


text:
Q: Nested Replace JS I am trying to make a makeshift BBCode parser for fun and I have it to where it will replace all tags that are not the same but I cannot get it to replace two or more of the same tags in a row. For example I have the following BB:
[big][big][c red]WARNING[/c][/big][/big]

it will only output:
[big]WARNING[/big]

the code I am using is as follows:
function parseBBCode(text, element) {

    //RegExp for BBCode to find
    var find = new Array();
        find[0] = /\[b\](.*?)\[\/b\]/g;            //Bold
        find[1] = /\[bg (.*?)\](.*?)\[\/bg\]/g;    //Background
        find[2] = /\[big\](.*?)\[\/big\]/g;        //Big
        find[3] = /\[c (.*?)\](.*?)\[\/c\]/g;      //Color
        find[4] = /\[f (.*?)\](.*?)\[\/f\]/g;      //Font
        find[5] = /\[i\](.*?)\[\/i\]/g;            //Italics
        find[6] = /\[img (.*?)\]/g;                //Image
        find[7] = /\[p\](.*?)\[\/p\]/g;            //Pre
        find[8] = /\[small\](.*?)\[\/small\]/g;    //Small
        find[9] = /\[s\](.*?)\[\/s\]/g;            //Strike

    var replace = new Array();
        replace[0] = "$1";
        replace[1] = "$2";
        replace[2] = "$1";
        replace[3] = "$2";
        replace[4] = "$2";
        replace[5] = "$1";
        replace[6] = "";
        replace[7] = "
$1
";
        replace[8] = "$1";
        replace[9] = "$1";

    for (var i = 0; i < find.length; i++) {

        text = text.replace(find[i], replace[i]);
    }

    $(element).html(text);
}

Is there anyway I can make this replace nested elements as well?

A: There's probably a much cleaner solution, but this will fix your problem. Basically, keep replacing until the regex can't find a match. It's not a full-proof solution, but will work on correctly formatted BBCode
...
for (var i = 0; i < find.length; i++) {

    while(find[i].test(text)) {
        text = text.replace(find[i], replace[i]);
    }

}
...


text:
Q: Data extraction from /Filter /FlateDecode PDF stream in PHP I can not decrypt the data from the stream like:
    56 0 obj
    << /Length 1242 /Filter /FlateDecode >>
    stream
    x]êΩnƒ Ñ{ûbÀKq¬æ\âê¢....(whole binary is omitted)
    endstream
    endobj

I tried isolate the binary content (x]êΩnƒ Ñ{ûbÀKq¬æ\âê¢....) in a file and in a binary string. Decoding function gzinflate($encripted_data) sends me error of decoding, and I think it happens because encoded content in not "deflated" or so.
In PDF Reference v 1.7, (six edition), on a page 67, I found the description of /FlateDecode filter as: ...Decompresses data encoded using the zlib/deflate compression method, reproducing the original text or binary data
I need real raw solution, aka php function or/and algorithm what to do with this "\FlateDecoded" stream.
Thank You!

A: Long overdue, but someone might find it helpful. In this case:
<< /Length 1242 /Filter /FlateDecode >> all you need is to pass the isolated binary string (so basically everything between "stream" and "endstream") to zlib.decompress:
import zlib
stream = b"êΩnƒ Ñ{ûbÀKq¬æ\âê"  # binary stream here
data = zlib.decompress(stream) # Here you have your clean decompressed stream

However, if you have/DecodeParms in your PDF object thing become complicated. You will need the /Predictor value and columns number. Better use PyPDF2 for this.

A: Since you didn't tell if you need to access one decompressed stream only or if you need all streams decompressed, I'll suggest you a simple commandline tool which does it in one go for the complete PDF: Jay Berkenbilt's qpdf.
Example commandline:
 qpdf --qdf --object-streams=disable in.pdf out.pdf

out.pdf can then be inspected in a text editor (only embedded ICC profiles, images and fonts could still be binary).
qpdf will also automatically re-order the objects and display the PDF syntax in a normalized way (and telling you in a comment what the original object ID of the de-compressed object was).
Should you require to re-compress the file again (maybe after you edited it), just run this command:
 qpdf out-edited.pdf out-recompressed.pdf

(You may see some warning message, telling that the utility was attempting to repair a damaged file....)
qpdf is multi-platform and available from Sourceforge.

A: header('Content-Type: text');           // I going to download the result of decoding
$n = "binary_file.bin";                 // decoded part in file in a directory
$f = @fopen($n, "rb");                  // now file is mine
$c = fread($f, filesize($n));           // now I know all about it
$u = @gzuncompress($c);                 // function, exactly fits for this /FlateDecode filter
$out = fopen("php://output", "wb");     // ready to output anywhere
fwrite($out, $u);                       // output to downloadable file

Jingle bells! Jingle bells!...
gzuncompress() - the solution

A: i just used
import de.intarsys.pdf.filter.FlateFilter;

from jpod / source forge
and it works well
FlateFilter filter = new FlateFilter(null);
byte[] decoded = filter.decode(bytes, start, end - start);

the bytes are straight from the pdf file

A: I wanted to add a more complete answer because I faced the same problem.
I found my answer in the source code of a well established PHP PDF parsing library: FPDI.
https://github.com/flagshipcompany/fpdf/blob/master/fpdi/src/pdf_parser.php#L878
I discovered there is multiple ways to encode a stream: '/FlateDecode', '/LZWDecode', '/ASCII85Decode', '/ASCIIHexDecode'.
For FlateDecode only, gzuncompress native PHP function is the key. For the others, FPDI source code contains decoder than you can reuse in your projects.


text:
Q: Is there a measure of internal energy flow? A system might have internal energy and/or kinetic energy. Kinetic energy in classical mechanics is a form of energy the object has, only because of its relative movement to other objects.
If you have a system like an oscillator, then you have a system where the amount of internal energy (energy of the spring, say) and the kinetic energy oscillate periodically. The amount of energy that is flowing from "internal energy" to "kinetic energy" and back therefore also meassures how this system is different from a system with might have the same amount of energy in total, but all its energy only stored in form of internal energy.
Is there a reasonable meassure of this difference, that is the ''energy-form flow''?
Maybe such a meassure might also be related to the entropy, because if there is kinetic energy around, I expect the entropy to be higher than otherwise.
Then I was thinking mabye that something like $\frac{dE_{kin}}{dt}$ might therefore be relevant. But the only quantity which directly puts energy and time together is the action. However, I'm not sure if the action has an illustative meaning, which goes beyond its definition, anyway.

A: It's not used particularly often, but there is a measure of energy flow called the "mechanical Poynting vector." Just as the Poynting vector for electromagnetic radiation in a vacuum gives the energy flux carried by the EM wave, the mechanical Poynting vector gives the energy flux carried by waves in a mechanical system. Wikipedia gives the definition as
$$\mathbf{S}_m(\mathbf{r},t) = \frac{1}{2}\sum_i m_i \dot{r}_i^2(t)\dot{\mathbf{r}}_i(t)\delta\bigl(\mathbf{r} - \mathbf{r}_i(t)\bigr)$$
Or more generally, if you have a continuous system (a fluid), it would be
$$\mathbf{S}_m(\mathbf{r},t) = \frac{1}{2}\rho(\mathbf{r},t)v^2(\mathbf{r},t)\mathbf{v}(\mathbf{r},t)$$
Keep in mind that this is a vector field, which makes it a local measure: the value of $\mathbf{S}_m$ at each point only measures energy flow at that point.

A: The physical notion of energy flow (and momentum flow) is contained in the stress-energy tensor. The momentum is the flow of energy, the stress is the flow of momentum. The reason this is not apparent in potential energy problems is becuase the potential energy is stored in the mutual gravitational field of the object and the Earth, and this field reconfigures itself at the speed of light in response to the motion of the object. This means that the flow of potential energy is to and fro from far away places, essentially instantly.
The stress tensor is reviewed in this answer: Where does the reaction to action come from?

A: I'm not sure if this is what you were thinking about, but the change in potential energy is (minus) the work done by the conservative force related to the potential energy in question.
For example, in an ideal spring, $W_s = -F_s\,\mathrm{d}x = \mathrm{d}E_e$, with $W_s$ the work done by the spring, $F_s$ its force, and $\mathrm{d}E_e$ the differential of the elastic energy. So, if you divide by the differential of time, you get the instantaneous power: $P_s = -F_s\,v = \frac{\mathrm{d}E_e}{\mathrm{d}t}$. This tells you how fast the elastic potential energy is changing. If this is the only force, it can only go to kinetic energy.
Furthermore, the rate of change in kinetic energy is the instantaneous power of the net force acting on the system: $\frac{\mathrm{d}E_\mathrm{kin}}{\mathrm{d}t} = P_\mathrm{net\ force}$.


text:
Q: Which is faster? I was chatting with a friend today about increasing the load time of pages and he mentioned to me that the "mysql_num_rows" is old and takes a lot of time.
Would replacing the mysql_num_rows with the code below be quicker?
$query      =   mysql_query("SELECT COUNT(*) FROM sent_messages WHERE  from_sender = '".$_SESSION['id']."'") or die(mysql_error());
$result     =   mysql_fetch_array($query);
$count      =   $result['COUNT(*)'];

I don't know too much about time complexity and algorithms so any advice would be greatly appreciated.
Thanks

A: mysql_num_rows() is not old, but it's slower because it requires more data to be transfered between client and database. mysql_num_rows() is irreplaceable if you need to read data AND count it. I recommend this way if all you need is a count of records:
$query  = mysql_query("SELECT COUNT(*) FROM sent_messages WHERE  from_sender = '".$_SESSION['id']."'") or die(mysql_error());
$count  = mysql_result($query,0);

A: Māris Kiseļovs' answer covers the ground here. However, I just want to add the following in order to avoid confusion:
In general, try and do as much work in the DB / query as possible. I.e., don't fetch a lot of data only to perform calculation and transformation in PHP (or any other language). Always seek to only request what you need from the DB, thus minimizing the data interchange.
In this specific case you'll be better off with the COUNT(*) and mysql_result() approach; performing the calculations in the DB layer, only requesting the needed data (the number of records).
However, were you to list the records, too (i.e., presenting the count and iterating over the set of records) you should just do a normal SELECT ... FROM ... to fetch the records (in order to generate the list) and do mysql_num_rows() on this result set (in order to get the count). In this case there would be no gain in a separate SELECT COUNT(*) ... query since you are need the entire result set from the DB anyway.


text:
Q: How to kill powershell process via cmd? Unified Remote app I have started using Unified Remote app on my Android device.
This app has a lot of features including quick actions which lets me run cmd remotely and add command line to it. It's a widget and I just need to press a button in the widget to start a process. Everything seems to be fine, I press a button and a powershell script starts.
This is a command line in cmd:
Powershell.exe -File C:\my_path\user\myscript.ps1
The problem is when I try to kill a powershell process, it just doesn't work.
I have created a new button to stop a process and this is a command-line via cmd:
taskkill /IM "powershell.exe" /F

My aim is to make a button which stops a script from running.

A: killall -9 powershell will kill all the processes that have the string powershell in their name.


text:
Q: select radio buttons using vba Sub Mind_stone()
Dim IE As Object
Dim doa As HTMLDocument
Dim HTMLdoc As HTMLDocument
Dim button As HTMLInputButtonElement
Dim i As Integer
Set IE = CreateObject("internetexplorer.application")

IE.Visible = True
IE.navigate "https://eqvm.titusn.co.in/PavbnjsPnrtl/login.jsp"

Do While IE.busy
 Application.Wait DateAdd("s", 1, Now)
Loop
IE.document.getElementById("username").Value = "efeqwf"
IE.document.getElementById("password").Value = "*****"
IE.document.getElementsByClassName("button ok")(0).Click
IE.document.querySelector("[title='PSR - Indirect Materials']").Click
'IE.document.getElementsByClassName("dijitReset dojoxMultiSelectItem")(1).Click
'IE.document.querySelector("[title='div_3_1_2_radiogroup']").Click
'itemlength = IE.document.all.Item("div_3_1_2_radiogroup").Length
'IE.document.getElementsByName("div_3_1_2_radiogroup").Item(1).Checked = True
End Sub

        <input
            type="radio"
            class="dijitReset dijitCheckBoxInput"
            data-dojo-attach-point="focusNode"
            data-

        <input
            type="radio"
            class="dijitReset dijitCheckBoxInput"
            data-dojo-attach-point="focusNode"
            data-dojo-attach-event="onclick:_onClick"
            value="on"
            tabindex="0"
            id="dijit_form_CheckBox_7"
            aria-labelledby=" dijit_form_CheckBox_7_radio_label"
            name="div_3_1_2_radiogroup"
            aria-checked="true"
            style="user-select: none;"
        />

    <input
        type="radio"
        class="dijitReset dijitCheckBoxInput"
        data-dojo-attach-point="focusNode"
        data-dojo-attach-event="onclick:_onClick"
        value="on"
        tabindex="0"
        id="dijit_form_CheckBox_7"
        aria-labelledby=" dijit_form_CheckBox_7_radio_label"
        name="div_3_1_2_radiogroup"
        aria-checked="true"
        style="user-select: none;"
    />

Create New / Create from existing PSR

i am new to the web-scraping , now i am trying to click the radio button through vba but i cant find the solution to that
for the first 4 stage (username,password,button ok,title) i have successfully passed but i am struggling for the above code
Second one is which i'am trying to click


text:
Q: switch icons on button click in react I am using react-full-screen library.
Link to code sandbox
I have a navbar, where I have placed the JSX for the button with icons.
class AdminNavbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFfull: false
    };
  }

  render() {
    return (
      <Navbar className="navbar" expand="lg">
        <Container fluid>

              <button className="btn-fullscreen" onClick={this.props.goFull}>

              </button>

        </Container>
      </Navbar>
    );
  }
}

And then in my another Admin Component, I am using it as props and performing the onClick()
class Admin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFull: false
    };
  }

  goFull = () => {
    if (document.body.classList.contains("btn-fullscreen")) {
      this.setState({ isFull: true });
    } else {
      this.setState({ isFull: false });
    }
    document.body.classList.toggle("btn-fullscreen");
  };
  render() {
    return (
      <Fullscreen
        enabled={this.state.isFull}
        onChange={(isFull) => this.setState({ isFull })}
      >

            <AdminNavbar {...this.props} goFull={this.goFull} />

      </Fullscreen>
    );
  }
}

Problem: the icons are not changing on click of the button. I  also tried using the active class. but no luck.

A: You don't have to check the classList on body. The icon toggle can be achieved by state change.Please have a look at the code.
import React from "react";

import AdminNavbar from "./AdminNavbar";

import Fullscreen from "react-full-screen";

class Admin extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFull: false
    };
  }

  goFull = () => {
    this.setState({ isFull: !this.state.isFull });
  };
  render() {
    return (
      <Fullscreen
        enabled={this.state.isFull}
        onChange={(isFull) => this.setState({ isFull })}
      >

            <AdminNavbar
              {...this.props}
              isFull={this.state.isFull}
              goFull={this.goFull}
            />

      </Fullscreen>
    );
  }
}

export default Admin;

The admin Navbar code
import React from "react";

//  reactstrap components
import { Navbar, Container } from "reactstrap";

class AdminNavbar extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isFfull: false
    };
  }

  render() {
    return (
      <Navbar className="navbar" expand="lg">
        <Container fluid>

              <button className="btn-fullscreen" onClick={this.props.goFull}>
                {!this.props.isFull ? (

                ) : (

                )}
              </button>

        </Container>
      </Navbar>
    );
  }
}

export default AdminNavbar;


text:
Q: How to change CUDA version I met this error when compiling a modified caffe version.
OpenCV static library was compiled with CUDA 7.5 support. Please, use the same version or rebuild OpenCV with CUDA 8.0
I have some old code may not compatible with CUDA8.0, so I want to change my cuda version for this error.
I modified my ~/.bash_profile like this
# export PYTHONPATH=$PYTHONPATH:/usr/local/cuda-8.0/lib64/
# export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-8.0/lib64
export PYTHONPATH=$PYTHONPATH:/usr/local/cuda-7.5/targets/x86_64-linux/lib/
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-7.5/targets/x86_64-linux/lib/

But it did't work. Still the same error. What should I do? Thanks.

A: This solution explains how you can have multiple different cuda versions installed, i.e. 10.2, 11.3 and 11.6 and switch between them. It's an extension of @w.t and makes use of update-alternatives.
Afaik, after cuda 11.x the installations on Ubuntu 20.04 cuda installations will be added to the update-alternatives maintenance automatically.
Let's say you installed cuda 10.2, cuda 11.3 and cuda 11.6 (following the official nvidia installation guide: https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html). They will all reside in:
/usr/local/cuda-10.2/...
/usr/local/cuda-11.3/...
/usr/local/cuda-11.6/...

Your update-alternatives will have two entries:
$ sudo update-alternatives --query cuda
...
/usr/local/cuda-11-3 - priority 113
/usr/local/cuda-11-6 - priority 116

Solution 1: If you want to make use of the update-alternatives make sure that your cuda symbolic link points to /etc/alternatives/cuda.
# Change the symbolic link target.
$ sudo ln -sfT /etc/alternatives/cuda /usr/local/cuda

# Check the path.
$ ll /usr/local/cuda

lrwxrwrwrwx 1 root root /usr/local/cuda -> /etc/alternatives/cuda/

Now, all that is left is to make sure /etc/alternatives/cuda points to the version you want to use, e.g. 11.3.
You can make that update with:
$ sudo update-alternatives --config cuda

and follow the instructions to change the version.
Check the path:
$ ll /etc/alternatives/cuda

lrwrwrwrwx root root /etc/alternatives -> /usr/local/cuda-11.3

almost done.
And always make sure to load the correct library PATHs in your ~/.bashrc.
Solution 2:
Directly set your /usr/local/cuda symbolic link to the correct version.
$ ln -sfT /usr/local/cuda-11.3 /usr/local/cuda

Reboot your machine and double check everything is set properly:
$ nvcc -V

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on Mon_May3 19:15:14_PDT_2021
Cuda compilation tools, release 11.3 V11.3.109
Build cuda 11.3.r11.3/compiler.29920130_0

A: Change your CUDA soft link to point on your desired CUDA version. For example:

ll /usr/local/cuda
lrwxrwxrwx 1 root root 19 Sep 06  2017 /usr/local/cuda -> /usr/local/cuda-8.0/

Simply relink it with
Update:
If the symlink already exists, use this other command:
[jalal@goku ~]$ ls /usr/local/cuda
lrwxrwxrwx. 1 root root 20 Sep 14 08:03 /usr/local/cuda -> /usr/local/cuda-10.2

[jalal@goku ~]$ sudo ln -sfT /usr/local/cuda/cuda-11.1/ /usr/local/cuda
[jalal@goku ~]$ ls /usr/local/cuda
lrwxrwxrwx. 1 root root 26 Sep 14 13:25 /usr/local/cuda -> /usr/local/cuda/cuda-11.1/

ln -s /usr/local/cuda-7.5 /usr/local/cuda

(With the proper installation location)

A: Perhaps cleaner:
sudo update-alternatives --display cuda

sudo update-alternatives --config cuda

A: Maybe a bit late, but I thought it might still be helpful for anyone who comes across this question. I wrote a simple bash script for switching to a different version of CUDA within the current bash session: https://github.com/phohenecker/switch-cuda

A: I solved the problem finally.
Modifying ~/.bash_profile to change the path to CUDA is the correct way. But when you changed the file, you need to relaunch the bash.
Simply source ~/.bash_profile won't work. Because source will only append the content in the file to the already existed path rather than cover it.

A: I switched from cuda 10.2 to 11.7. export PATH=/etc/alternatives/cuda/bin:$PATH did the trick for me. I found the solution in this thread: https://stackoverflow.com/a/40599478/7924573


text:
Q: Angular HTML5 mode, router going to otherwise state on page reload I am trying to remove hash tag from my website. I have achieved it by following code.
$locationProvider.html5Mode(true);

As well as added base URL in index file as well.
My issue is if i am on contct-us state after reloading entire page. i am redirecting to home state which is defined as otherwise state.
Configuration used are -
server -Appache
  database - mysql
I have added following code in .htaccess for rewriting rule as well -
     RewriteEngine On
     php_value post_max_size 120M
    php_value upload_max_filesize 120M
     php_value max_execution_time 90

     RewriteCond %{HTTP_HOST} ^54\.201\.153\.244$ [NC,OR]

     RewriteCond %{HTTPS} off
     RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

      RewriteCond %{HTTP_HOST} ^adkarlo.com$ [NC]
        RewriteRule ^(.*)$ https://www.adkarlo.com/$1 [R=301,L]

      #RewriteBase /html/
      ErrorDocument 404 /404.php

    RewriteCond %{REQUEST_FILENAME} -f
     RewriteRule ^ - [L]
   RewriteRule ^(.*)$ index.php [L]

Expected result - After reloading from state contact-us any page i want to go to same page.

A: In order to support reloading of HTML5 mode route URLs, you need to implement server-side URL rewriting to direct non-file requests (that is, requests that aren't explicitly for an existing file) to your index file, typically index.html.
From the documentation

Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html).

Your rewrite rule should not have any # in the destination URL. Instead, use this
RewriteEngine on

# Don't rewrite files
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.php [L]

Source ~ https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode
Also, there's no need to set RewriteBase.


text:
Q: Calculate distances between polygon centres in QGIS Is there a practical way to calculate distances between polygon centroids in QGIS? I have a UK city region map divided into administrative units (1 ward = 1 polygon). I want to represent their population growth in function of the distance to the core city and the best way to do it seems to be looking for the geometrical 'centroid' of each polygon and measure its distance to the 'centroid' of the core city polygon. I can do it manually with the ruler tool but it takes a long time and is not very accurate.
Thanks

A: As Alexandre wrote, it is relatively easy - You want centroids and distance matrix. But I will additionaly suggest that You will use two algorithms from Processing plugin:
1) SAGA > Polygon centroids

and then
2) SAGA > Distance matrix

Both can save results to temporary file which is helpful, especially for centroids.


text:
Q: why this Javascript function doesn't work? I use the following javascript function,
function get_check_value(formId,checkboxId,TxtboxId)
{
alert(formId);

var c_value = "";
for (var i=0; i < document.formId.checkboxId.length; i++)
   {
   if (document.formId.checkboxId[i].checked)
      {
      c_value = c_value + document.formId.checkboxId[i].value + "\n";
      }
   }
   alert(c_value);
   document.getElementById(TxtboxId).value= c_value;
  // alert(c_value.value);

}
and my php page has this,
<form name="orderform" id="orderform">
<input type="text" name="chId" id="chId" >

            Country

    <? foreach($country as $row){   ?>

    <?= $row['dbCountry']; ?>
    <input type="checkbox" name="CountrycheckId" id="CountrycheckId" value="<?= $row['dbCountryId']; ?> " onClick="get_check_value('orderform','CountrycheckId','chId')">
    <? }  ?>

</form>

I am getting formname,checkboxid,textid in alerts inside the javascript function... But
the problem is with the line
for (var i=0; i < document.formId.checkboxId.length; i++)
Webdeveloper toolbar shows this error
document.formId is undefined

A: var selects = document.getElementsByName('CountrycheckId');
for (var i=0; i < selects.length; i++)
{
   if (selects[i].checked)
   {
       c_value = c_value + selects[i].value + "\n";
   }
}

A: You need to access the form via getElementById(formId), see below:
  function get_check_value(formId,checkboxId,TxtboxId)
  {
     alert(formId);

     var c_value = "";
     for (var i=0; i < document.getElementById(formId).checkboxId.length; i++)
        {
        if (document.formId.checkboxId[i].checked)
           {
           c_value = c_value + document.formId.checkboxId[i].value + "\n";
           }
        }
        alert(c_value);
        document.getElementById(TxtboxId).value= c_value;
       // alert(c_value.value);
  }

When you write document.formId Javascript will look for a property of document whose name is (literally) "formId" when you use document.getElementById(formId) Javascript will look for an HTML element whose id is whatever the variable formId is holding.

A: I think you are having multiple elements with the same id inside the document. This isn't valid. Ids are unique and cannot be assigned to multiple elements. You can use name for this and get those elements using
document.getElementsByName("name");

var checkBoxes = document.getElementsByName('CountrycheckId');
var c_value = new Array();

for (var i=0; i < checkBoxes.length; i++)
{
   if (checkBoxes[i].checked)
   {
       c_value.push(checkBoxes[i].value);
   }
}

// join the array using any delimiter like

c_value.join(',');

If you can use a framework like jQuery it would be much more simple
$("input:checkbox[name='CountrycheckId']:checked").each(function(){
    c_value.push(this.value); //or
    c_value.push($(this).val());
});


text:
Q: Can't use pdfbook2 Following situation: I would like to use pdfbook2 to convert a PDF file.
I entered the following command in Windows Powershell:

python3 C:\tmp\pdfbook2 C:\tmp\book.pdf

But every time this error message appears. Can anyone give me a good explanation so that I can easily convert PDFs via pdfbook2?
(I am relatively new to LaTex)


text:
Q: Calling `std.math.clamp` gives compile error `error: unable to evaluate constant expression` in Zig Why does this program fail to compile? Zig version 0.6.0.
const std = @import("std");
fn get_value () f32 {
    return 1.0;
}
test "testcase" {
    const value: f32 = 1. + get_value() ;
    _ = std.math.clamp(value, 0.0, 255.0);
}

Gives compile error:
$ zig test src/clamp.zig
Semantic Analysis [790/1017] ./src/clamp.zig:9:24: error: unable to evaluate constant expression
    _ = std.math.clamp(value, 0.0, 255.0);
                       ^
./src/clamp.zig:9:23: note: referenced here
    _ = std.math.clamp(value, 0.0, 255.0);
                      ^

A: The reason is that value has different type than the constants 0.0 and 255.0.
value is f32, and the type for the constants is comptime_float.
The fix is to cast the constants to f32.
_ = std.math.clamp(value, @as(f32, 0.0), @as(f32, 255.0));

Type of clamp seems to require that all parameters are either comptime values, or all are runtime values.
See https://ziglearn.org/chapter-1/#comptime


text:
Q: Unifying lists of different length by concatenating atoms Consider the following list:

[my,name,is,jack,baur]

I want to unify this to the following pattern:

[my,name,is,Name]

So that the variable Name has the value 'jack baur' in the end.
The variable is working as some sort of wildcard here and should unify with an unknown number of atoms/list members.
Important:

*

*the variable/wildcard is not always at the end

*there could be multiple variables/wildcards

Currently I have something like this:
rule([my,name,is,Name],[hello,Name]).

% Sentence is a list (e.g. [my,name,is,jack,baur]
answer(Sentence,Response) :-
    rule(Sentence,ResponseList),
    atomic_list_concat(ResponseList,' ',Response).

Obviously this only works when Name is exactly one word, not two.
How would I approach this problem in Prolog?

A: You need a custom unification algorithm, such as the following:
unify([], []).
unify([X|L], R) :-
    (var(X) ->
        % unify the variable X with some prefix of R
        append(X, Tail, R),
    ;
        R = [X|Tail],
    ),
    unify(L, Tail).

Usage:
1 ?- unify([i, am, a, Profession, and, i, Verb, it],
           [i, am, a, prolog, programmer, and, i, like, it]).
Profession = [prolog, programmer],
Verb = [like].

This algorithm only allows variables to occur in L for the sake of efficiency. I'll leave the problem of pasting atoms together to you, since you seem to have already solved that.
Note that the current version allows variables to match zero atoms, but you can easily add a constraint to disallow that.

A: here a DCG possibility. It's fairly clean, I think.
list(L) --> {length(L, _)}, L.

rule(R) -->
    [my, name, is], list(Name),
    [and, i, live, in], list(Country),
    {flatten([hello, Name, of, Country],R)}.

rule([hello|Name]) -->
    [my, name, is], list(Name) .

answer(Sentence, Response) :-
    phrase(rule(Response), Sentence), !.

with that
?- answer([my, name, is, bill, the, kid, and, i, live, in, new, york],R).
R = [hello, bill, the, kid, of, new, york].

the essential production here is list//1, that matches any definite length list of tokens.
Beware: list(A),list(B),, with both A, B unbound should be avoided.
It's ok instead if there are tokens in between, like in list(A),[and],list(B),


text:
Q: Is the Angular templateCache shared between apps? Is it persistent? If I have two Angular apps that run on the same domain, will/can they share data in the templateCache? Or is the cache unique to each main application module? In general I'm trying to understand what dictates when a new templateCache is created.
Furthermore I'm not clear on whether or in what way the templateCache is persistent? Looking in local storage and cookies, I don't see where anything is getting stored.

A: templateCache is not persisted in any way; it's an in-memory, client-side cache to avoid multiple HTTP requests to fetch the same template URL.
Specifically, it is used by <script type='text/ng-template'> to preload templates and by templateUrl to cache templates when they are requested multiple times within the same run of the application. Reloading the page creates a new, empty templateCache.


text:
Q: cdosys mail from classic ASP I am supporting a customer running a proprietary Content Management System written in Classic ASP. Certain pages use the cdosys message routine to send email. This is used to report page errors back to me as well as email password reminders and forward customer inquiries to the client requesting site information. I utilize the IIS Virtual mail server to process the mail. If I take a text email and drop it in the inetpub/mailroot/pickup folder it grabs the mail and mails it out just fine. But mailing from the website via cdosys on asp pages (example objmail.Send) the mail never makes it to the pickup folder. Is this a possible permissions issue? The website is running in IIS 10 on Windows Server 2019.

A: I solved this by adding write permissions to the inetpub/mailroot folder and subfolders. I also added read permissions to the smtp subtrees in the metabase for IIS using Metabase explorer as a tool.


text:
Q: schema.org Failing to Validate Dublin Core Meta in 'meta' and 'link' elements I have Dublin Core (DC) meta data in <meta ...> and <link...> elements. Testing my html document with the validator fails to identify the dublin core meta data in my document. But when using DC tags in elemetns like 10 February 2017 	 the validator identifies those meta data elements.
This validator also fails to identify DC tags in meta and link elements.
Example that does not validate but should:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Services to Government</title>
    <link rel="schema.DC" href="http://example.org/terms/" />
    <meta name="DC.date" content="2007-05-05" />

Is the meta data invalid or are the validators in the wrong? Is there a validator that will support <meta > and <link>?
it seems like the prefix:
@prefix dc: http://purl.org/dc/elements/1.1/ .
is not appearing the the validator results for some reason.
I have tried adding additional vocabulaires like:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title>Services to Government</title>
    <link rel="schema.DC" href="http://example.org/terms/" />
    <link rel="schema.DC" xmlns:dc="http://purl.org/dc/elements/1.1/"  xmlns:gml="http://www.opengis.net/gml" xmlns:v="http://rdf.data-vocabulary.org/#"/>
    <meta name="DC.date" content="2007-05-05" />

10 February 2017

Without success.
To recreate, just paste the example html into one of the validators linked above.

A: Those examples are written with an obviously unsupported syntax.
So the validators are not suppose to detect it, as they support common syntax, such as RDFa, JSON-LD, Microdata etc.
Here's a quote that might be relevant:

The major search engines now extract and index metadata embedded with
one of several syntaxes: HTML Microdata, of limited expressivity but
the easiest for webmasters to deploy; RDFa, a richer syntax with
better support for internationalization and multiple RDF namespaces;
and JSON-LD, an RDF-compatible variant of the popular Javascript
Object Notation (JSON). These broadly supported syntaxes effectively
obsolete a series of IETF and DCMI syntax specifications developed
prior to 2008 specifically for expressing Dublin Core™ metadata.

https://www.dublincore.org/resources/metadata-basics/

Parsing those examples would require a parser for that specific syntax (there doesn't seem to be many out there..).
So the solution might be to use some of the common serializations (JSON-LD, Microdata, RDFa)


text:
Q: How to restore correct window control behaviour in Gnome? I'm having an issue on my laptop which is preventing me from changing the settings for GTK+ applications that use headerbars. Non-header bar applications are working just fine.
What happened is that I'd previously had Pantheon installed, but since upgrading, I've not been able to keep up with Pantheon releases, so I'd disabled the PPA (but kept some of the apps I was still using).
Since then, I've tried to clear all of the packages that aren't related to the apps I still use (Plank, Footnote).
However, window controls in Gnome are still working as they would in Pantheon. Changing the settings in dconf editor or Tweaks has no effect.

How can I restore normal functionality?
Resetting the gsettings value did nothing. Logging out and logging in did nothing. I'm stumped at this point.

Here's the latest:

*

*I tried resetting gsettings (remove ~/.config/dconf/* and kill all processes immediately to prevent it from being recreated with existing settings). No avail.

*I searched for every possible GTK+ related settings file in ~/.config, ~/.local, and ~/.cache. Nothing works.

A: I finally found the answer in the most unusual of places:
It was the display manager at fault somehow. Switching from SDDM to GDM solved the problem.


text:
Q: PDF of a log-normally distributed variable after tangens hyperbolicus transformation Assume a variable $x_0>0$ with log-normally distributed noise, such that the observation $x$ of $x_0$ has the following PDF:
$$
p(x\mid x_0) = \frac{1}{\sqrt{2\pi}\sigma x}e^{-\frac{\left(\ln{(\frac{x}{x_0})} - \sigma^2\right)^2}{2\sigma^2}}
$$
(NB: $x_0$ thus corresponds to the mode of the log-normal distribution, following the reparameterization $\mathrm{mode}=e^{\mu-\sigma^2}$)
As it turns out, I cannot measure $x$ directly, but only a transformation $y(x)$:
$$
y(x) = (1-\delta)\tanh(\beta x) + \delta
$$
The parameters $\delta$ and $\beta$ are not relevant to my question, but it can be assumed $0\le\delta\le1$ and $\beta>0$.
Now I have a measurement $y_m$ and I want to compute the probability that a latent variable $x_0$ would generate a $y$ within the window $[y_m-\epsilon; y_m+\epsilon]$.
I have two questions related to this:

*

*What is the PDF for $y$ that would allow me to compute this probability? (Note that for reasons not mentioned here, I want to avoid transforming $y_m$ to $x$-space)

*More pragmatically, the scientific programming module I am using (scipy.stats.lognorm) has CDF implementations for the log-normal distribution. If instead of the above $\tanh$ transformation I had the identity transformation $y(x)=x$, I could simply use something along the lines of lognorm(x0,σ).cdf(y_m+ε) - lognorm(x0,σ).cdf(y_m-ε). Can I still use this lognorm CDF implementation after some appropriate transformation?

A: The hyperbolic tangent function $\tanh$ is a strictly increasing function, so it is quite simple to get the CDF of the random variable $Y$.  I am going to give a more general answer that what you are looking for --- specifically, I will not make any assumption about the distribution $X$, and I will not assume that this is a non-negative random variable.  Using the stipulated transformation with $\beta$ and $0 \leqslant \delta < 1$ you have:
$$\begin{align}
F_Y(y) &\equiv \mathbb{P}(Y \leqslant y) \\[12pt]
&= \mathbb{P}((1-\delta) \tanh (\beta X) + \delta \leqslant y) \\[6pt]
&= \mathbb{P} \bigg( \tanh (\beta X) \leqslant \frac{y-\delta}{1-\delta} \bigg) \\[6pt]
&= \mathbb{P} \bigg( \frac{e^{2 \beta X}-1}{e^{2 \beta X}+1} \leqslant \frac{y-\delta}{1-\delta} \bigg) \\[6pt]
&= \mathbb{P} \bigg( e^{2 \beta X}-1 \leqslant \frac{y-\delta}{1-\delta} \cdot (e^{2 \beta X}+1) \bigg) \\[6pt]
&= \mathbb{P} \bigg( e^{2 \beta X} \cdot \frac{1-y}{1-\delta} \leqslant 1 + \frac{y-\delta}{1-\delta} \bigg) \\[6pt]
&= \mathbb{P} \bigg( e^{2 \beta X} \cdot \frac{1-y}{1-\delta} \leqslant \frac{1+y-2\delta}{1-\delta} \bigg) \\[6pt]
&= \mathbb{P} \bigg( e^{2 \beta X} \cdot (1-y) \leqslant (1+y-2\delta) \bigg). \\[6pt]
\end{align}$$
Taking account of the limits of the function you then have:
$$\begin{align}
F_Y(y)
&= \begin{cases}
0 & & \text{if } y \leqslant 2\delta-1, \\[6pt]
F_X \bigg( \frac{1}{2 \beta} \cdot \log \Big( \frac{1+y-2\delta}{1-y} \Big) \bigg) & & \text{if } 2\delta-1 < y < 1, \\[6pt]
1 & & \text{if } y \geqslant 1, \\[6pt]
\end{cases} \\[6pt]
\end{align}$$
It is easily shown that:
$$\begin{align}
\frac{d}{dy} \log \Big( \frac{1+y-2\delta}{1-y} \Big)
&= \frac{1}{1+y-2\delta} + \frac{1}{1-y} \\[6pt]
&= \frac{(1-y)+(1+y-2\delta)}{(1+y-2\delta)(1-y)} \\[6pt]
&= \frac{2(1-\delta)}{(1+y-2\delta)(1-y)}. \\[6pt]
\end{align}$$
Therefore, differentiating the CDF with respect to $y$ gives the corresponding density:
$$f_Y(y) = \frac{(1-\delta)}{(1+y-2\delta)(1-y) \beta} \cdot
f_X \bigg( \frac{1}{2 \beta} \cdot \log \Big( \frac{1+y-2\delta}{1-y} \Big) \bigg)
\quad \quad \text{for } 2\delta-1 < y < 1.$$
Substitution of the density function for $X$ will give you the final form.  Note that in your problem you have assumed that $X$ is a non-negative random variable, which leads to the effective bound $y \geqslant \delta$.  This bound emerges correctly from substitution into the above equation in the case where $f_X$ has support only over positive argument values.


text:
Q: Postgres with Docker I have docker-compose.yml as:
version: '2.1'

services:
  postgres:
    image: postgres:latest
    container_name: postgres
    environment:
      - "POSTGRES_USER=docker"
      - "POSTGRES_PASSWORD=docker"
    ports:
      - "5432:5432"
    volumes:
      - "./sql:/docker-entrypoint-initdb.d"

In folder sql, I have a .sql file containing:
DROP DATABASE IF EXISTS mytestdb;
CREATE DATABASE mytestdb;
\c mytestdb;

docker-compose gets postgres container up and running. But when I connect to the server via pgadmin, I see no database with name 'mytestdb' created. Instead I see one with name 'docker'.
What am I missing here?


text:
Q: How to set df_print to tibble in markdown for a single R code chunk I would like to show, in an rmarkdown document, the printed output of a tibble as shown in the console. i.e.

*

*First line: dimension summary;

*then the column headers;

*then classes of variables;

*then first 10 lines of the tibble;

*then number of rows not shown.

However, by default, tibbles and other data.frame objects are automatically converted to a tabbed, paginated table showing all contents.
I note that the option to turn off this default behaviour can be set for a whole markdown document by changing the df_print option to tibble in the YAML.
However, how do I set the df_print option to tibble for just a single R code chunk, so that I can show in an Rmarkdown document what the user will see on the console?
Thanks,
Jon

A: There's no need to touch the global setting. You can explicitly call the print function  tibble:::print.tbl_df(df)
Example:

title: "Untitled"
author: "TC"
date: "7/27/2018"
output:
  html_document:
    df_print: "kable"
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## print tibble

```{r}
df <- tibble::as.tibble(mtcars)

tibble:::print.tbl_df(head(df))
```

## print kable (set in YAML header)

```{r}
head(df)
```

output html


text:
Q: passing variables into python from html using json I'm new to html/javascript and Python in general, and have been working on a Django project for a class.  I'm supposed to create an html page that will allow the user to choose attributes to keep, and then pass these variables into a python program that will filter out the relevant attributes from files.  The python work has been finished, and only the html interface needs to be completed.  I understand that this will require the use of json to pass values into the .py, but have been unable to figure out how to do so.
I guess my exact question would be:  Given a page that allows you to check attributes to keep, how would I pass said attributes as variables into a python method?

A: You keep referring to "passing between files", but I think that terminology is confusing and possibly wrong. The file types of the source code for various components is of no concern to your issue. What you want to focus on is this process:

*

*Create an html web page that contains a form, representing the data you are working with.

*When the form is submitted, the form contents will be sent to your server.

*Your server is django, implying that your html page is a template, implying that the template will be served from a django view method.

*The django view method can both serve the fresh template page (when the request.method is not "POST"), and accept and handle the form (when the request.method is "POST"), and redisplay the updated form contents.

*Your django form will keep persistant data in either a session, or in your database. The initial view of your template will show the current attribute values for your object. Results from the form will modify these values and then redisplay the form.

This question is far too broad to give you any more specifics than this. But, I recommend reading a basic django tutorial on how to process forms and templates. You really only need a single view, and a single template file.
To be honest, I don't see JSON being necessary anywhere in this process unless you are trying to make a more advanced API. There is no reason to submit JSON when your form can just submit the normal www form encoded format. JSON would only be necessary if you were writing an API. If that is the case, then your html form would have to first serialize to json, and then submit via an ajax request to your django server, which would be expecting an incoming json request.


text:
Q: How to embed with iframe python.org? I have:
<iframe src="https://www.python.org/" width="900" height="900">
</iframe>

But I get a blank screen on both Firefox and Chrome. I can embed a map from google maps using similar markup, and it works on both browsers. I am a beginner, so I suppose I am missing something obvious. What is it?
Thanks.

A: You can configure Your server to disallow other webpages emebeding of Your webpages (like python did).
Refused to display 'https://www.python.org/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.
more info

A: You can use HTTP Header Field X-Frame-Options,
<meta http-equiv="X-Frame-Options" content="SAMEORIGIN">

There are three possible values for X-Frame-Options:
DENY - The page cannot be displayed in a frame, regardless of the site attempting to do so.
SAMEORIGIN - The page can only be displayed in a frame on the same origin as the page itself.
ALLOW-FROM uri - The page can only be displayed in a frame on the specified origin.
so looks like the url has set 'X-Frame-Options' to 'SAMEORIGIN'.

Refused to display 'https://www.python.org/' in a frame because it set
  'X-Frame-Options' to 'SAMEORIGIN'.


text:
Q: Angular 4 dynamic routerlink server/localhost not responding. Works when routerlink is static I am attempting to create a dynamic navigation menu based on a navigation menu service and a navigation menu component.
First I prototyped the navigation menu to make sure it worked when the component HTML is hardcoded. That code looks like this:

  <md-list>
    <md-list-item routerLinkActive="link-active">

        <md-icon>people</md-icon>Users

    </md-list-item>
    <md-list-item routerLinkActive="link-active">

        <md-icon>hotel</md-icon>Patients

    </md-list-item>
    <md-list-item routerLinkActive="link-active">

        <md-icon>library_books</md-icon>Studies Dashboard

    </md-list-item>
    <md-list-item routerLinkActive="link-active">

        <md-icon>library_books</md-icon>Example Select list

    </md-list-item>
  </md-list>

When I run the application with this code and click one of the links the application successfully navigates and the selected route as specified by the routerLink attribute is loaded into the router outlet.
I am trying to modify the above code to use ngFor to generate the list based on the navigationMenuService. I have tried several different bits of code the most recent of which is:

  <md-list>
    <md-list-item routerLinkActive="link-active" *ngFor="let menuItem of navigationMenuService.getNavigationMenuItems()">

        <md-icon>{{menuItem.iconName}}</md-icon>{{menuItem.label}}

    </md-list-item>

  </md-list>

These appear to work in that if you hover over them the link looks like the correct link, but upon clicking them....things break. Rather than successfully navigating and loading the page into the router outlet I get a "localhost is not responding" error.
The navigationMenuService looks like this:

import { Injectable } from '@angular/core';
import { NavigationMenuItem } from '../../models/NavigationMenuItem';

@Injectable()
export class NavigationMenuService {
    public navigationMenuStatuses = NavigationMenuStatus;
    private navigationMenuStatus: NavigationMenuStatus;

    constructor() {
        this.navigationMenuStatus = NavigationMenuStatus.Hidden;//start with the navigation menu closed.
    }

    getNavigationMenuItems(): NavigationMenuItem[] {
        return [
        {
            iconName: "library_books",
            label: "Studies",
            route: "studies"
        },
        {
            iconName: "library_books",
            label: "Example Select",
            route: "exampleselect"
        }];
    }

    getStatus(): NavigationMenuStatus {
        return this.navigationMenuStatus;
    }

    setStatus(status: NavigationMenuStatus) {
        this.navigationMenuStatus = status;
    }

    //toggles visibility of labels. If status is currently hidden this method has no effect.
    toggleLabels() {
        if (this.navigationMenuStatus == NavigationMenuStatus.Icons) {
            this.navigationMenuStatus = NavigationMenuStatus.IconsAndLabels;
        }
        else if (this.navigationMenuStatus == NavigationMenuStatus.IconsAndLabels) {
            this.navigationMenuStatus = NavigationMenuStatus.Icons;
        }
    }
}

export enum NavigationMenuStatus {
    Hidden,
    Icons,
    IconsAndLabels
}

In case it is relevant, this application uses Angular 4.3.6, Webpack and HMR with @angular/platform-server and @angular/platform-browser modules.

A: I can make this do what I want by adding a navigateToItem method on the navigationMenuService and updating the HTML as follows:

//Created by Devon Holcombe, September 2017
import { Injectable } from '@angular/core';
import { NavigationMenuItem } from '../../models/NavigationMenuItem';
import { ActivatedRoute, Router, Params } from '@angular/router';

@Injectable()
export class NavigationMenuService {
    public navigationMenuStatuses = NavigationMenuStatus;
    private navigationMenuStatus: NavigationMenuStatus;

    constructor(private router: Router) {
        this.navigationMenuStatus = NavigationMenuStatus.Hidden;//start with the navigation menu closed.
    }

    getNavigationMenuItems(): NavigationMenuItem[] {
        return [
        {
            iconName: "library_books",
            label: "Studies",
            route: "/studies"
        },
        {
            iconName: "library_books",
            label: "Example Select",
            route: "/exampleselect"
        }];
    }

    navigateToItem(menuItem: NavigationMenuItem) {
        this.router.navigateByUrl(menuItem.route);
    }

    getStatus(): NavigationMenuStatus {
        return this.navigationMenuStatus;
    }

    setStatus(status: NavigationMenuStatus) {
        this.navigationMenuStatus = status;
    }

    //toggles visibility of labels. If status is currently hidden this method has no effect.
    toggleLabels() {
        if (this.navigationMenuStatus == NavigationMenuStatus.Icons) {
            this.navigationMenuStatus = NavigationMenuStatus.IconsAndLabels;
        }
        else if (this.navigationMenuStatus == NavigationMenuStatus.IconsAndLabels) {
            this.navigationMenuStatus = NavigationMenuStatus.Icons;
        }
    }
}

export enum NavigationMenuStatus {
    Hidden,
    Icons,
    IconsAndLabels
}

  <md-list>
    <md-list-item routerLinkActive="link-active" *ngFor="let menuItem of navigationMenuService.getNavigationMenuItems()">

        <md-icon>{{menuItem.iconName}}</md-icon>{{menuItem.label}}

    </md-list-item>

  </md-list>

While this works it seems like there should be a way to do this using routerLink that I am missing.


text:
Q: generating barcode for Barby gem under EAN-13 While attempting to render in HTML a collection of article barcodes and proceeding incrementally to view the data (relative to other objects on tha page), the controller
require 'barby/outputter/html_outputter'
require 'barby/barcode/ean_13'

and the view invokes
<%= this_barcode = article.barcodes.first.barcode %>
<%= this_barcode.class %>
<%# barcode = Barby::EAN13.new(this_barcode) %>
<%# outputter = Barby::HtmlOutputter.new(barcode) %>
<%# barcode.to_html.html_safe %>
     [returns as expected]
8001300303466 String

however, when wanting to get the barcode and uncommenting that element it fails to process because data not valid for the line barcode = Barby::EAN13.new(this_barcode) (also occurs with barcode = Barby::EAN13.new(this_barcode.to_i))
note  possibly on garden path here, as there is confusion with what the wiki suggests with
barcode = Barby::DataMatrix.new(number) as that would generate the error
uninitialized constant Barby::DataMatrix
How does one ensure the data is correct for proper rendering?

A: Here's the issue:
8001300303466 has 13 characters.  It is the correct barcode.
I was assuming one could submit a correct barcode.  However line 54 of the gem's ean_13.rb file
allows a 12 character data element FORMAT = /^\d{12}$/ and proceeds to calculate the check digit.
Thus,
<%= barcode = Barby::EAN13.new(this_barcode[0...-1]) %>
will end up processing the data correctly.


text:
Q: A farmer buys a used tractor for Rs 12000. He pays Rs 6000 cash and agrees to pay the balance in annual.... A farmer buys a used tractor for Rs $12000$. He pays Rs $6000$ cash and agrees to pay the balance in annual installments of Rs $500$ plus $12 \%$ interest on the unpaid amount. How much will be the tractor cost him?
Answer
It is given that the farmer pays Rs $6000$ in cash.
Therefore, unpaid amount = Rs $12000$ – Rs $6000$ = Rs $6000$
According to the given condition, the interest paid annually is
$12 \%$ of $6000$, $12 \%$ of $5500$, $12 \%$ of $5000$, ..., $12 \%$ of $500$ ( I am unable to understand this step.. please suggest thanks.... )

A: If I'm understanding correctly, the question states that the interest paid annually is
12% of 6000, 12% of 5500, 12% of 5000, ..., 12% of 500. From this we infer that either the interest payable each year is calculated before the Rs $500$ for that year is subtracted from the amount left to pay, or that annual payments of Rs $500$ don't start until the second year. Either way, the answer is the same.
The farmer pays Rs 6000 to begin with, leaving Rs 6000 to pay, so the interest payable in the first year is 12% of 6000.
In year 2, he pays Rs 500, leaving Rs $6000-500=$ Rs $5500$ to pay, so the interest for year 2 is 12% of 5500.
In year 3, he pays Rs 500, leaving Rs $6000-500(2)=$ Rs $5000$ to pay, so the interest for year 3 is 12% of 5000.
,...,
In year 12, he pays Rs 500, leaving $6000-500(11)=$ Rs $500$ to pay, so the interest for year 12 is 12% of 500.
The interest payments form an arithmetic progression with $a_1 = 6000\frac{12}{100} = 720$ and $d = -500\frac{12}{100} = -60$, so the total interest payments are $s_{12} = \frac{12}{2}(720+60) =$ Rs $4680$.
As Ankush pointed out, the total paid is $12000 +$ total interest $= $Rs $16680.

A: The tractor is worth Rs 12000 but the farmer pays an upfront amount of Rs 6000 and the rest as per the arrangement. In the end, total cost will be Rs 12000 + interest payments.


text:
Q: Accessing google sheet and update it via Python I'm using the below code to update the google sheet i have with the data from a PostgreSQL table. The table refresh frequently and i need to update the Google Sheet with the latest data of the table.
I'm new to Google API and went through goggle posts and did all he steps like sharing the google sheet with the client_email, But it is not working.
There are 3 columns as shown below,

The column header are in 3rd row and i need to update the values from 4th row onwards.
Below is the current code,
import psycopg2
import gspread

from oauth2client.service_account import ServiceAccountCredentials
import pprint
#Create scope
scope =  ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']

cnx_psql = psycopg2.connect(host="xxx.xxx.xxx.xx", database="postgres", user="postgres",
                         password="**********", port="5432")
psql_cursor = cnx_psql.cursor()

meta_query = '''select * from dl.quantity;'''
psql_cursor.execute(meta_query)
results = psql_cursor.fetchall()
cell_values = (results)

creds = ServiceAccountCredentials.from_json_keyfile_name('/Users/User_123/Documents/GS/gsheet_key.json',scope)
client = gspread.authorize(creds)

sheet = client.open('https://docs.google.com/spreadsheets/d/***************').sheet1
pp = pprint.PrettyPrinter()

result = sheet.get_all_record()

for i, val in enumerate(cell_values):
    cell_list[i].value = val
    sheet.update_cells(cell_list)

psql_cursor.close()

cnx_psql.close()

Getting the below error,
Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gspread/client.py", line 123, in open self.list_spreadsheet_files() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gspread/utils.py", line 37, in finditem return next((item for item in seq if func(item))) StopIteration

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Users/User_123/Documents/Googlesheet_update.py", line 30, in sheet = client.open('https://docs.google.com/spreadsheets/d/********************').sheet1 File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/gspread/client.py", line 131, in open raise SpreadsheetNotFound gspread.exceptions.SpreadsheetNotFound

A: Your code and comments suggests that you are trying to open the spreadsheet using the full URL, but you're using the open function that only works with titles.
From the docs:

You can open a spreadsheet by its title as it appears in Google Docs:
sh = gc.open('My poor gym results')

If you want to be specific, use a key (which can be extracted from the spreadsheet's url):
sht1 = gc.open_by_key('0BmgG6nO_6dprdS1MN3d3MkdPa142WFRrdnRRUWl1UFE')

Or, if
  you feel really lazy to extract that key, paste the entire
  spreadsheet's url
sht2 = gc.open_by_url('https://docs.google.com/spreadsheet/ccc?key=0Bm...FE&hl')

In your case the last example is the way to go, so use client.open_by_url instead of client.open

A: This Snippet of Code will allow you to connect, from there you can look at the documentation to complete the rest of your actions!

from oauth2client.service_account import ServiceAccountCredentials
import gspread

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive',
         'https://www.googleapis.com/auth/drive.file', 'https://www.googleapis.com/auth/spreadsheets']

#Generate a json file by using service account auth in google developer console
'''
Link: https://console.developers.google.com/
1) Enable API Access for a Project if you haven't done it yet.
2) Go to "APIs & Services > Credentials" and choose "Create credentials > Service account key".
3) Fill out the form
4) Click "Create" and "Done".
5) Press "Manage service accounts" above Service Accounts.
6) Press on ⋮ near recently created service account and select "Manage keys" and then click on "ADD KEY > Create new key".
7) Select JSON key type and press "Create".
8) Go to the google sheet and share the sheet with the email from service accounts.
'''
creds = ServiceAccountCredentials.from_json_keyfile_name('mod.json', scope)
client = gspread.authorize(creds)

sheet = client.open_by_url("#Paste yout google sheet url here").sheet1

data = sheet.get_all_records()

sheet.update_cell(1, 1, "You made it") #Write this message in first row and first column

print(data)


text:
Q: Why would trying to parse downloaded .csv with SwiftCSV not be able to locate file? So I'm writing a Swift app, using Alamofire, SwiftCSV and Realm [attempting to use Realm] and I've successfully downloaded the .csv from my server, but when I attempt to parse the .csv to even see just the headers, it's throwing the catch statement of my do {} catch {}
My ultimate goal is to get Alamofire to download the .csv > SwiftCSV to parse it into readable Objects [~200 of them] > then populate a Realm DB
you can also see the catch{} is being thrown before the .response() is outputting... can anyone explain this to me? is it on a different thread or what?
The crazy thing is the file still exists even when the app starts, so I'm wondering why it doesn't see it at all.
Am I just not understanding the CSV library methods??
ViewController:
var localPath: NSURL?
Alamofire.download(.GET, "http://wristaroo.com/schedule/wristaroo.csv", destination: { (temporaryURL, response) in
    let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let pathComponent = response.suggestedFilename

    localPath = directoryURL.URLByAppendingPathComponent(pathComponent!)

    return localPath!
}).response { (request, response, _, error) in
    print(response)
}

var filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String

filePath = (filePath as NSString).stringByAppendingPathComponent("wristaroo.csv")

let filePathURL = NSURL.fileURLWithPath(filePath)
print("\noutside filePath: \(filePath)")

do {
    let csv = try CSV(url: filePathURL)
    print("test")

    csv.enumerateAsArray({ (array) in
        print(array.first)
    })
} catch {
    print("error outside")
}

var filePath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! as String

filePath = (filePath as NSString).stringByAppendingPathComponent("wristaroo.csv")

let filePathURL = NSURL.fileURLWithPath(filePath)
print("\noutside filePath: \(filePath)")

do {
    let csv = try CSV(url: filePathURL)
    print("test")

    csv.enumerateAsArray({ (array) in
        print(array.first)
    })
} catch {
    print("error outside")
}

Console Output:
outside filePath: /Users/michaeldvinci/Library/Developer/CoreSimulator/Devices/522F6430-CB63-4607-89B8-6B3B4D9A3100/data/Containers/Data/Application/4DAA3C89-FF7E-4A0F-B251-4ED1AAF34C25/Documents/wristaroo.csv
error outside
Optional(<NSHTTPURLResponse: 0x7fe648f1eae0> { URL: http://wristaroo.com/schedule/wristaroo.csv } { status code: 200, headers {
    "Accept-Ranges" = "bytes, bytes";
    Age = 0;
    Connection = "keep-alive";
    "Content-Length" = 6909;
    "Content-Type" = "text/plain";
    Date = "Wed, 27 Apr 2016 01:40:11 GMT";
    "Keep-Alive" = "timeout=30";
    Server = "Apache/2";
} })

A: Alamofire.download() method download the file asynchronously. So the method returns immediately before downloading the file completed. So you try to read the file before the file will be downloaded.
To fix the behavior that you expected is move parsing CSV logic to callback closure of download() method.
Like the following:
Alamofire.download(.GET, "http://wristaroo.com/schedule/wristaroo.csv") { (temporaryURL, response) in
    do {
        let csv = try CSV(url: temporaryURL, encoding: NSASCIIStringEncoding)
        print("test")

        csv.enumerateAsArray { (array) in
            print(array.first)
        }
    } catch {
        print("error outside")
    }

    let fileManager = NSFileManager.defaultManager()
    let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    let pathComponent = response.suggestedFilename

    return directoryURL.URLByAppendingPathComponent(pathComponent!)
}

Also, a character encoding of the file is ASCII, so you should specify encoding when reading the file.


text:
Q: Account merge unsuccessful I created a new account on Ask Different this morning. I want to merge it into my main account. I used the "I want to merge my profiles" option of the Contact Us form in the Help Center.
It sent emails to both of my accounts. I clicked the links in both emails, and confirmed that I wanted to merge the accounts:

Thank you for confirming ownership of your accounts. The account user134206 will be removed, and all rep and votes will be transferred to account Jeremy Banks as a result of this merge:
Please click OK to confirm.

After I clicked OK, I was redirected to my old profile, but it didn't contain any content from the new profile. The links in the emails are now 404, so they were processed in some capacity, but the merge seems to have failed.
I tried again and it produced the same result.

A: If you have lots of reputation, the automated merge bots tend to get intimidated. "What if this is someone trying to STEAL HIS REPS?" they think; "WE'D GET FIRED!"
They're not the smartest of bots.
So they put them in a queue and wait for someone to come along and approve them. Which I occasionally remember to do.
And just did.


text:
Q: problem with delay function void Timer1Init(void)
_T1IP = 4; // this is the default value anyway
TMR1 = 0; // clear the timer
PR1 =0x0139 ;
T1CON = 0x8030;
_T1IF = 0;
 _T1IE = 1;

void attribute((interrupt, no_auto_psv)) _T1Interrupt(void)
 LATAbits.LATA0 = ~LATAbits.LATA0;  //Toggle output to LED
_T1IF = 0;

void Timer2Init(void)
_T2IP = 4; // this is the default value anyway
TMR2 = 0; // clear the timer
PR2 = 0x1E85;
T2CON = 0x8030;
_T2IF = 0;

void attribute((interrupt, no_auto_psv)) _T2Interrupt(void)
 LATAbits.LATA1 = ~LATAbits.LATA1 ;
 DELAY_MS (6000);
_T2IF = 0;

int main(void)
    TRISAbits.TRISA0 = 0;
TRISAbits.TRISA1 = 0;
ANSELA = 0x0000;
_RCDIV=0;

Timer1Init();
Timer2Init();
  while (1)  {}

above written program is not working correctly i have given a delay in timer 2 interrupt routine that means there should be delay of 6s for led to blink connected to A1 pin and its working but the problem is that there is also a delay happening while blinking the led connected to pin A0 can anybody help me to tell whats wrong here ?

A: You have a delay in your interrupt routine - this stops any further interrupts (so stopping the other LED from changing state) until it has expired. Interrupt routines should execute as fast as possible and certainly should never* contain delays.
*never say never, but it would be a very unusual application that did


text:
Q: Dynamic Shortcode in WooCommerce Downloads I'm selling unique, custom files in Woocommerce, and currently link to the final files with a shortcode that dynamically links to the final file. The shortcode doesn't register in Woocommerce's Product Downloads Settings (Woo doesn't recognize "[]").
Is it possible to have a shortcode link in Woocommerce's Downloadable Files settings?


text:
Q: Trying to make a "solid" block in pygame but it doesnt work Hopefully you can help me,
i have been struggling with this problem for the last few days.
I want to make a "solid" block for my 2d platformer game that i am working on but when i go into that "solid" block i teleport to the other side or to the bottom of the block, i dont know why, hopefully you know why
So here is my code:
class Block(pygame.sprite.Sprite):

    def __init__(self, color = blue,widht = 64, height = 64):

        super(Block, self).__init__()

        self.image = pygame.Surface((widht, height))
        self.image.fill(color)
        self.rect = self.image.get_rect()

        self.sound = pygame.mixer.Sound("2dSounds/Walk.wav")

        self.hspeed = 0
        self.vspeed = 0
    def update(self, collidable):
        self.rect.x += self.hspeed

        collision_list = pygame.sprite.spritecollide(self, collidable, False)
        for collided_object in collision_list:
            if (self.hspeed > 0):
                # right direction
                self.rect.right = collided_object.rect.left

            elif (self.hspeed < 0):
                # left direction
                self.rect.left = collided_object.rect.right

        self.rect.y += self.vspeed

        collision_list = pygame.sprite.spritecollide(self, collidable, False)
        for collided_object in collision_list:
            if (self.vspeed > 0):
             # down direction
                self.rect.bottom = collided_object.rect.top

            elif (self.vspeed < 0):
                # up direction
                self.rect.top = collided_object.rect.bottom
    def change_speed(self, hspeed, vspeed):
        self.hspeed += hspeed
        self.vspeed += vspeed
    def set_position(self, x, y):
        self.rect.x = x
        self.rect.y = y

Thanks alot! :)

A: Sorry about the fact that my code isn't based off your's, I literally just threw it together in the past 5 minutes so it isn't very pretty, but here it is:
from pygame.locals import *

import pygame
import sys

GRAVITY = 1.2

class Player:
    def __init__(self, x, y):
        self.rect = pygame.Rect(x, y, 25, 25)
        self.yvel = 0

    def tick(self):
        self.yvel += GRAVITY

        self.rect.y += int(self.yvel)

        if self.rect.y >= 475:
            self.rect.y = 475
            self.yvel = 0

    def set(self, y):
        if y:
            self.yvel = y

class Block:
    def __init__(self, x, y, w, h):
        self.rect = pygame.Rect(x, y, w, h)

class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((500, 500))
        self.player = Player(0, 0)
        self.block = Block(225, 400, 50, 50)

    def main(self):
        right = left = False
        while True:
            self.screen.fill((230, 230, 230))
            pygame.draw.rect(self.screen, (40, 40, 40), self.block.rect)
            pygame.draw.rect(self.screen, (100, 200, 100), self.player.rect)

            pygame.display.flip()
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                    sys.exit(0)
                elif event.type == KEYDOWN:
                    if event.key == K_SPACE:
                        self.player.set(-20)
                    elif event.key == K_RIGHT:
                        right = True
                    elif event.key == K_LEFT:
                        left = True
                elif event.type == KEYUP:
                    if event.key == K_RIGHT:
                        right = False
                    elif event.key == K_LEFT:
                        left = False

            if right:
                self.player.rect.x += 5
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.x -= 1
            if left:
                self.player.rect.x -= 5
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.x += 1
            self.player.tick()
            if self.player.yvel > 0:
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.y -= 1
                    self.player.yvel = 0
            elif self.player.yvel < 0:
                while self.player.rect.colliderect(self.block.rect):
                    self.player.rect.y += 1
                    self.player.yvel = 0

game = Game()
game.main()

The player speed is quite fast, but that can be changed at the lines:
self.player.rect.x -= 5

and
self.player.rect.x += 5

near the bottom.
The way it works is whenever you go to move, it moves the player, then looks to see if if collided with the block. If it did, the player moves in the opposite direction until is is satisfied that it isn't colliding any more.
Jumping is accomplished using velocity, hence Player.yvel and GRAVITY. GRAVITY can be changed but if it it higher, jumps will be shorter and vice-versa.

Have a play around with the code and experiment with things like the blocks position (self.block = Block(225, 400, 50, 50)) and the player's staring position (self.player = Player(0, 0))

If you do find any errors in the code, just let me know and I'll try to fix them.