text:
Q: Get connection IP of WebSocket connection Once I've opened a web socket like so:
m_ws = new WebSocket(127.0.0.1);

Is it possible to get the IP that was just used to open? Something like m_ws._websocket.address?
I've seen numerous examples but none of them worked as I think they apply to WebSocketServer instances.

A: Do you use the ws library?
If you use ws to get IP Connection :
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', function connection(ws, req) {
  const ip = req.connection.remoteAddress;
});


text:
Q: How to pass data source to sub report and load sup report in jasper report using JSP Please help.
I create Jasper Report only Main report it's worked fine.
But when I add sub-report to it. It cause error.
It cannot Evaluate Parameter I put. I also try use (JasperReport) JRLoader.loadObjectFromFile(jrxmlFile_Jasper) but it cause error cannot load file, too.
Here is my JSP:
try{

    List<Map<String, ?>> dataSource = (List<Map<String, ?>>) request.getAttribute("listProducts");
    JRDataSource jrDataSource = new JRBeanCollectionDataSource(dataSource);

    List<Map<String, ?>> dataSource_sub = (List<Map<String, ?>>) request.getAttribute("listProducts");
    JRDataSource jrDataSource_sub = new JRBeanCollectionDataSource(dataSource);

    /*
    String jrxmlFile_Jasper = session.getServletContext().getRealPath("reports/productreport.jasper");
    JasperReport jasperReport_onLoad = (JasperReport) JRLoader.loadObjectFromFile(jrxmlFile_Jasper);
    */

    String jrxmlFile = session.getServletContext().getRealPath("reports/productreport.jrxml");
    InputStream input = new FileInputStream(new File(jrxmlFile));
    JasperReport jasperReport = JasperCompileManager.compileReport(input);

    String jrxmlFile_Sub = session.getServletContext().getRealPath("reports/sub_productreport.jrxml");
    InputStream input_sub = new FileInputStream(new File(jrxmlFile_Sub));
    JasperReport jasperReport_Sub = JasperCompileManager.compileReport(input_sub);

    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("SUBREPORT_DIR", jasperReport_Sub);

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jrDataSource);

    JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
    response.getOutputStream().flush();
    response.getOutputStream().close();

}catch(Exception e){
    e.printStackTrace();
}

Here is sub-report in Jasper Main report:
         <subreport>
            <reportElement x="150" y="22" width="200" height="30" uuid="d1150b63-2c7b-4dcc-858c-b73dbe178455"/>
            <subreportParameter name="SUBREPORT_DIR">
                <subreportParameterExpression><![CDATA[""]]></subreportParameterExpression>
            </subreportParameter>
            <subreportExpression><![CDATA[$P{SUBREPORT_DIR}]]></subreportExpression>
        </subreport>

Here is Error which I got:
20:57:09,547 ERROR [stderr] (default task-1) net.sf.jasperreports.engine.fill.JRExpressionEvalException: Error evaluating expression for source text: $P{SUBREPORT_DIR}
20:57:09,548 ERROR [stderr] (default task-1)    at deployment.helloworld.war//net.sf.jasperreports.engine.fill.JREvaluator.handleEvaluationException(JREvaluator.java:287)
20:57:09,548 ERROR [stderr] (default task-1)    at deployment.helloworld.war//net.sf.jasperreports.engine.fill.JREvaluator.evaluate(JREvaluator.java:319)
20:57:09,548 ERROR [stderr] (default task-1)    at deployment.helloworld.war//net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:671)
20:57:09,549 ERROR [stderr] (default task-1)    at deployment.helloworld.war//net.sf.jasperreports.engine.fill.JRCalculator.evaluate(JRCalculator.java:639)
And I also got Error when I try to use : (JasperReport) JRLoader.loadObjectFromFile(jrxmlFile_Jasper)
    String jrxmlFile_Jasper = session.getServletContext().getRealPath("reports/productreport.jasper");
    JasperReport jasperReport_onLoad = (JasperReport) JRLoader.loadObjectFromFile(jrxmlFile_Jasper);

Error of (JasperReport) JRLoader: I saw the last location on error show has ".", I don't knwo why it auto add ".". I'm a new of Jasper Report I try search for solution two day already, but I cannot fix it. please help.
21:12:47,644 ERROR [stderr] (default task-1) net.sf.jasperreports.engine.JRException: Class not found when loading object from file: D:\Working\WebServer\wildfly-21.0.0.Final\standalone\deployments\helloworld.war\reports\productreport.jasper.
21:12:47,645 ERROR [stderr] (default task-1)    at deployment.helloworld.war//net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:152)
21:12:47,645 ERROR [stderr] (default task-1)    at deployment.helloworld.war//net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:116)
21:12:47,645 ERROR [stderr] (default task-1)    at deployment.helloworld.war//net.sf.jasperreports.engine.util.JRLoader.loadObjectFromFile(JRLoader.java:107)

A: After research for several days, I can fix it and it's worked.

*

*We need to update version of both JSP Jasper Dependency and Jasper Studio (Report Design tool) to be the same.

*Make sure, we create Fields and Parameters correctly in Jasper Report and its same as we assign from JSP.

*If we use JRBeanCollectionDataSource, we have to use only one dataSource pass throw to sub-report. It mean we must use ArrayList in ArrayList.

*In sub-report, we have to use dataSourceExpression: new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource
($Field_dataSource_to_Sub-Report_that_class_is_ArrayList)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aggregate function $lookup in mongoose Below 2 collections: tickets & stocks
tickets
Pharma: HEA00004
TxtDtVts: 21112017
ID_REGROUP: 20003000           Int64
Cip7: 787853
Designation: Doliprane

stocks

ICat_id:20003000                     Int64
art_st0: 4

And the 2 schemas
var ticketSchema = mongoose.Schema({
      NumVts: Number,
      Pharma: String,
      TxtDtVts: Number,
      ID_LGN: Number,
      ID_REGROUPEMENT: Number,
});
 var Ticket = mongoose.model('Ticket', ticketSchema,'tickets');

var stockSchema = mongoose.Schema({
ICat_ID: Number,
art_st0: Number,
});
 var Stock = mongoose.model('Stock', stockSchema,'stocks');

I'm trying to make a "$lookup" to get the the stock of product like that:
app.get('/join/:pharma/:jour',function(req,res){

              var jour = Number(req.params.jour);

            Ticket.aggregate([

          {"$match":{"Pharma": req.params.pharma}},
          {"$match":{"TxtDtVts": jour}},
          { $group : {_id : {Pharma : "$Pharma"}}},

          { $lookup:
        {
          from: "stocks",
          localField: "ID_REGROUP",
          foreignField: "ICat_ID",
          as: "stock"
        }}, ]

            ,function(err, ticket) {
            if (err)
                res.send(err);
                    res.header("Access-Control-Allow-Origin", "*");
                    res.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
                    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                    res.json(ticket);
        });
});

Below the response..and the stock field still empty
[
    {
        "_id":
    {
 "Pharma": "HEA00004"
        },

      "stock": []

}
]

Why the lookup dont work with this fields ? Is there a problem with data types (int64) ?
Thanks for advance


text:
Q: Angular ngFor adicionar condicional usnado ng-content Estou usando primeng para renderizar dados numa tabela, segue conforme documentação meus dados e minha config de colunas
   API {
      id: 1,
      nome: "Test 1",
      moeda: "Euro",
      status: "Recebido",
      data: "01/01/1999",
    }

 ngOnInit {
   this.col = [
     {field: 'nome', header: 'Nome'},
     {field: 'moeda',  header: 'Moeda'},
     {field: 'status', header: 'Status'},
     {field: 'data', header: 'Data'}
   ]
}

Bom, faço um ngFor e renderinzo cada coluna e seus respectivos dados com sucesso
<td *ngFor="let col of column">
    {{rowData[col.field]}}
</td>

Agora o problema, para cada coluna de dados na inha tabela preciso formatar de acordo, por exemplo, a coluna Data precisa usar um pipe para formar da data, para outros campos preciso fazer outras alterações, podendo usar pipe.
<td *ngFor="let col of columns | keyvalue">
  <ng-container *ngIf="rowData[col.field] !== 'data'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'data'"> {{rowData[col.field] | date: 'dd/MMM/yyyy'}}</ng-container>
</td>

Como que eu faço por exemplo nesse contexto acima se eu tiver que também usar pipe de uppercase na coluna nome, ou tiver que usar pipe de currency na coluna moeda como que faço par renderizar tudo isso dentro de um ng-container.
Se for data teria que vir com data formatada, se for nome em uppercase, se for moeda com currency, enfim como faço refactoy desse codigo abaixo?
<td *ngFor="let col of columns | keyvalue">
  <ng-container *ngIf="rowData[col.field] !== 'data'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'data'"> {{rowData[col.field] | date: 'dd/MMM/yyyy'}}
  <ng-container *ngIf="rowData[col.field] !== 'moeda'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'moeda'"> {{rowData[col.field] | currency:'CAD':'code'}'}}
  <ng-container *ngIf="rowData[col.field] !== 'nome'"> {{rowData[col.field]}}</ng-container>
   <ng-container *ngIf="rowData[col.field] === 'nome'"> {{rowData[col.field] | uppercase}}</ng-container>
</td>


text:
Q: Automatically converted characters for question title don't appear in page title First seen in a Stack Overflow question, but re-created here for testing purposes. The page title and the header displaying the question title above the question disagree on some character replacements. In my testing this included:

*

*Many (yes, even more than three) consecutive full-stops get collapsed into one U+2026 Horizontal Ellipsis

*Two dashes get replaced by U+2013 En Dash

*Straight quotes (U+0022) get replaced by "curly" quotes (U+201C and U+201D, respectively)

All these replacements don't happen in the page title, which makes for funny page titles if you actually include, like, 100 full-stops which get collapsed into a single U+2026 on the page itself.

A: Don't post questions with titles containing 100 consecutive full-stops.

A: Not all browsers can render "special" characters in page titles, so we stick with ASCII there.
(for example, some browsers will even render actual HTML in the title, such as <b> and so on)


text:
Q: Synchronize drawing a rectangle using mouse event propagation I have a base class MainWidget which inherites QOpenGLWidget. MainWidget has 2 child classes ColorWidget and BWWidget. I wish to synchronize drawing a rectangle between both the child widgets i.e. when i start drawing a shape on ColorWidget the shape should show up on BWWidget. I have overwritten mouseMoveEvent for base class to draw rectangles.
void MainWidget::mouseMoveEvent(QMouseEvent* event)
{
    if(m_mousePressed && event->type() == QEvent::MouseMove)
    {
        // check some conditions
        if (/*conditions*/)
        {
            m_activeItem.reset(new Rectangle(this));

            m_activeItem->show();
        }
    }
}

I am able to draw rectangles on the child classes individually. But i want them to be drawn simultaneously. I have tried to overwrite mouseMoveEventfor both child classes but it seems calling MainWidget::mouseMoveEvent() from child classes will lead to infinite loop and a crash.
In my case, parent to ColorWidget and BWWidget is a QDockWidget and my Rectangle class inherits QLabel.
Not sure how can i implement this.

A: I'm not sure I understand 100% what you are asking here (mainly because you didn't provide a minimal compilable example), this is what I understood:

*

*You have two widgets,

*

*one of type class ColorWidget : public MainWidget

*one of class BWWidget : public MainWidget

*with class MainWidget : public QOpenGLWidget

*These two widgets are visible side-by-side.

*When either one of your two widgets receives a mouseMoveEvent(), both should display something.

If that's what you have, these are your options:

*

*First of all, you should move functionality to create a rectangle out of your mouse move event handler (e.g. into a function MainWidget::DrawMouseMoveRectangle(QPoint pos).

*

*Doing so already makes accidental recursive calls less likely.

*(possible:) Make both widgets known to each other (e.g. via QPointer<MainWidget> pOther).

*

*Override mouseMoveEvent() and call DrawMouseMoveRectangle(QPoint pos) for this and pOther.

*(better:) Since you're already using Qt, create a signal MainWidget::SignalMouseMove(QPoint p) and slot MainWidget::MouseMovedSlot(QPoint p).

*

*In your common parent widget's initilization you connect both widgets' slots to each widgets' signal (see below).

*In MainWidget's mouseMoveEvent() do emit SignalMouseMove(evt->pos)*

*

*(*) Probably you need to pass some context for correct interpretation of the geometry.

*Now both functions get called independent of the widget which received the event.

How to make the connections:
bool ok = true;
ok = ok && connect(w1, &MainWidget::SignalMouseMove, w1, &MainWidget::MouseMovedSlot);
ok = ok && connect(w1, &MainWidget::SignalMouseMove, w2, &MainWidget::MouseMovedSlot);
ok = ok && connect(w2, &MainWidget::SignalMouseMove, w1, &MainWidget::MouseMovedSlot);
ok = ok && connect(w2, &MainWidget::SignalMouseMove, w2, &MainWidget::MouseMovedSlot);
Q_ASSERT(ok);

EDIT
Answering your comment:

What i want is i should be able to draw 1 Rectangle and pass it on to every other widget to show it (with appropriate geometry) because it will enable me for moving and resizing will reflect on all widgets.

Displaying the same instance of a widget in two different parent widgets may be possible, but definitely feels like a kludge and is not how Qt is designed.
You should take a look at Qt's model-view-programming, because this is essentially what you want to achieve:

*

*Have a single model displayed in two views.

*Update both views on any change of the model.

Because implementing QAbstractItemModel is a bit overkill for that, here are some alternatives:

*

*Use Qt's Graphics View Framework: Display the same QGraphicsScene in two QGraphicsViews and put some QGraphicsRectItem into the scene.

*Use Qt's parameter support for semi-automatic data binding.

*Roll your own, it isn't that hard:

*

*Basically, you have to separate your view logic from your model logic into e.g. RectangleView and RectangleModel.

*Then make the two connectable, e.g. via Signals in the model and Slots in the view(s).

*Create a view in both your widgets.

*Give each widget a shared pointer to a model.

*Connect the model with both views.

*Result: Whenever you change the model (from which widget doesn't matter), both views will be updated.

EDIT 2: very simple example using a shared QGraphicsRectItem
// this is a minimal compilable example of two views sharing the same model, with automatic update on mouse events
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
#include <QMouseEvent>
#include <QHBoxLayout>

class TestWidget : public QWidget
{
    //Q_OBJECT // Not neccessary here because we don't use and don't need moc for this example. -> Don't try this at home!
public:
    TestWidget() : QWidget(Q_NULLPTR),
        lt(new QHBoxLayout(this)),
        v1(new QGraphicsView(this)),
        v2(new QGraphicsView(this)),
        s(new QGraphicsScene(this)),
        r(Q_NULLPTR)
    {
        // initialization
        r = s->addRect(0, 0, 10, 10, QPen(Qt::red), Qt::yellow);

        lt->addWidget(v1);
        lt->addWidget(v2);

        // sharing the same model:
        v1->setScene(s);
        v2->setScene(s);
        // in reality, you need to share QGraphicsRectItem *r, too.
        // (it would actually be sufficient to share *r only)

        // very simple mouse interaction:
        v1->viewport()->installEventFilter(this);
        v1->viewport()->setMouseTracking(true);
        v2->viewport()->installEventFilter(this);
        v2->viewport()->setMouseTracking(true);
    }

    bool eventFilter(QObject *o, QEvent *evt) Q_DECL_OVERRIDE
    {
        QGraphicsView *gv = Q_NULLPTR;
        if(o == v1->viewport())
        {
            gv = v1;
        }
        else if(o == v2->viewport())
        {
            gv = v2;
        }

        if(gv != Q_NULLPTR)
        {
            QPointF p;
            switch(evt->type())
            {
            case QEvent::MouseMove:
                p = static_cast<QMouseEvent*>(evt)->pos();
                evt->accept();
                break;
            default:
                break;
            }
            if(p != QPoint())
            {
                // do something different depending on interacting view - just for demonstration
                if(gv == v1)
                {
                    r->setRect(QRectF(p, r->rect().bottomRight()));
                }
                else
                {
                    r->setRect(QRectF(r->rect().topLeft(), p));
                }
            }
        }
        return QWidget::eventFilter(o, evt);
    }

private:
    QHBoxLayout *lt;
    QGraphicsView *v1;
    QGraphicsView *v2;
    QGraphicsScene *s;
    QGraphicsRectItem *r;
};

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    TestWidget w;
    w.show();
    return a.exec();
}


text:
Q: Reducing Gaps in dynamically generated TreeView I'm working on a ASP.NET application that uses the in-built Treeview. For some reason, the vertical space between the nodes will not reduce no matter what I try in the CSS.
The nodes are dynamically generated, see the example bellow:

The tree is generated using:
<asp:TreeView ID="rcmTree" runat="server" CssClass="treeView" ShowLines="true"></asp:TreeView>

And then the CSS Code I have is:
.treeNode {
  text-indent: 2px;
  font-size: 13px;
}

.treeNode a {
  text-decoration: none;
  color: #000;
  vertical-align: middle;
}

.treeView tr {
  margin-top: -25px;
}

.treeView {
  margin-top: 6px;
}

#rcmTree td div {
  height: 20px !important;
}

A: Found the answer - I had to change the Doctype to:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


text:
Q: Get all DocuSign EnvelopeIds that originated from a powerform Using DocuSign's REST API, is there a way to retrieve a list of all envelope Ids from an account where the envelopes have a completed status and originated from a specific power form?
I've tried using the follow call and still see all completed envelopes after 9/12 regardless of where they originated from:
GET https://demo.docusign.net/restapi/v2/accounts/1655678/envelopes?from_date=2016-09-12&powerformids=2fc0a56d-f6c7-4e96-be93-258d0c038e3c&status=completed HTTP/1.1
The best working solution I have now is to add a custom field to the envelope and filter on it using the custom_field parameter. This requires additional setup from users and is not optimal.
Thanks.

A: Have you looked at DocuSign Connect for this?  If you setup a specific user for your Powerform, Connect can publish events to you for just the envelopes created from that user.  Then you wouldn't even need to make calls to get the Envelope IDs (or even other information).

A: *

*Your idea of adding a custom field on the template level is the best way to go. It will help return accurate results, though I would agree it adds some overhead/upkeep during template/powerform creation.

*The powerformids parameter you are including in your sample is not a supporter parameter and is simply being ignored.


text:
Q: Randomly divide a square into smaller squares in Netlogo Is there a way to divide a rectangle into smaller, random size rectangles in Netlogo? Like the following image with 6 rectangles, one which has been subdivided, and the subdivision painted black:

This question is because I have a shp file of farmland loaded in Netlogo composed of regular rectangles, and want to simulate how they are subdivided and occupied by urban development. Size of subdivisions can be a range between 1/3 to 1/8 of total square. Thanks.

A: I think that's pretty tricky, especially if you want specific minimum dimensions. Maybe play around with the code below to see if it gets you started? It basically takes a rectangle input (a farm plot, potentially) and generates a whole bunch of overlapping rectangles. The problem with the random bit is that you can (as is) get sections that are narrower or taller than your 1/8 since you get overlap. Play around with the counter to increase or reduce the number of rectangles it makes- fewer means that the entire patch may not be subdivided, more means longer run time and potentially more small subdivisions.
patches-own [ id ]

to setup
  ca
  resize-world -50 50 -50 50
  set-patch-size 4
  ask patches [ set id -1 ]
  ask rectangle -20 20 -40 40 [
    set pcolor red
  ]
  reset-ticks
end

to go
  rectangle-sub -20 20 40 -40
  tick
end

to rectangle-sub [ x0 x1 y0 y1 ]

  ; Make sure the x0 x1 / y0 y1 order is correct
  let xp0 min (list x0 x1)
  let xp1 max (list x0 x1)
  let yp0 min (list y0 y1)
  let yp1 max (list y0 y1)

  ; Define the rectangle to subdivide
  let main_rect rectangle xp0 xp1 yp0 yp1

  ; Define width and height
  let width xp1 - xp0
  let height yp1 - yp0
  let w3 round ( width / 3 )
  let w8 round ( width / 8 )
  let h3 round ( height / 3 )
  let h8 round ( height / 8 )

  ; Set a while loop to make mini rectangles, with
  ; a counter to stop the loop after too many tries
  let counter 0
  while [ counter < 100 and any? main_rect with [id = -1 ] ] [
    let newx0 xp0 + ( random width )
    let newx1 newx0 + ( ceiling width / ( random  6 + 3 ) )
    let newy0 yp0 + ( random height )
    let newy1 newy0 + ( ceiling height / ( random 6 + 3 ) )

    ; define a sub rectangle
    let newrect rectangle newx0 newx1 newy0 newy1

    ; remove any patches from the sub rectangle that are not
    ; also part of the main rectangle
    set newrect newrect with [ member? self main_rect ]
    if any? newrect [

      ; Make sure the dimensions aren't too small or big
      let nwidth ( max [pxcor] of newrect - min [pxcor] of newrect )
      let nheight ( max [pycor] of newrect - min [pycor] of newrect )
      if  nwidth < w3 and nwidth > w8 and  nheight < h3 and nheight > h8 [

        ; Choose a random patch and assign its id to all others
        ; in the same newrect patch-set
        let groupid random 10000
        ask newrect [
          set id groupid
          set pcolor id / 100
        ]
      ]
    ]
    set counter counter + 1
  ]
  print counter

end

to-report rectangle [ x0 x1 y0 y1 ]
  ; reports a patch-set bounded by
  ; the coordinate arguments passed
  report patches with [
    pxcor > x0 and pxcor < x1 and
    pycor > y0 and pycor < y1
  ]
end

EDITS:
Ok- I may have gone a bit overboard here but I like this problem. Here is an alternative solution that has turtles draw the rectangles- that way there is no overlap. Additionally, rectangles have to build off the outside or previously id-d rectangles, so you don't get random disconnected rectangles. However, it can leave one-patch squares with no id within the rectangle, so you'll have to sort those out as you like.
To see what how it works, put the display to continuous and slow it way down. In essence, a turtle sprouts on a patch without an id, hatches a partner who travels away some distance before they both turn the same direction and move forward and move some distance. The x and y coordinates of each corner patch are stored in a list then used to assign an id to the rectangle they define.
patches-own [ id ]

to setup
  ca
  resize-world -50 50 -50 50
  set-patch-size 5
  ask patches [ set id -1 ]
  ask rectangle -20 20 -40 40 [
    set pcolor red
  ]
  reset-ticks
end

to go
  turtle-define-rect -20 20 40 -40
  tick
end

to turtle-define-rect [ x0 x1 y0 y1 ]

  ; Make sure the x0 x1 / y0 y1 order is correct
  let xp0 min (list x0 x1)
  let xp1 max (list x0 x1)
  let yp0 min (list y0 y1)
  let yp1 max (list y0 y1)

  ; Define the rectangle to subdivide
  let main_rect rectangle xp0 xp1 yp0 yp1

  let xlist []
  let ylist []
  let possible_area one-of main_rect with [
    id = -1 and
    any? neighbors4 with [id = -1] and
    any? neighbors4 with [not member? self main_rect or id != -1]
  ]
  if possible_area != nobody [
    ask possible_area [
      let w random 5 + 5
      let h random 10 + 10
      sprout 1 [
        set color blue
        set size 3
        let start-patch patch-here
        let id_temp [id] of patch-here
        face one-of neighbors4 with [not member? self main_rect or id != -1]
        rt 180
        hatch 1 [
          create-link-with one-of other turtles-here
          repeat w [
            if ( [id] of patch-ahead 1 = -1 ) and ( [ member? self main_rect] of patch-ahead 1 ) [
              fd 1
            ]
          ]
        ]
        set xlist lput xcor xlist
        set ylist lput ycor ylist
        ask link-neighbors [
          set xlist lput xcor xlist
          set ylist lput ycor ylist
        ]
        let turn one-of [ 90 -90 ]
        rt turn
        ask link-neighbors [
          rt turn
        ]
        ask my-links [
          tie
        ]
        repeat h [
          if (
            ( [id] of patch-ahead 1 = -1 ) and
            ( [ member? self main_rect] of patch-ahead 1 ) and
            ( [ [id] of patch-ahead 1 = -1 ] of link-neighbors = [true] ) and
            ( [ [ member? self main_rect] of patch-ahead 1  ] of link-neighbors = [true] )
          )
          [
            fd 1
          ]
        ]
        set xlist lput xcor xlist
        set ylist lput ycor ylist
        ask link-neighbors [
          set xlist lput xcor xlist
          set ylist lput ycor ylist
        ]
        ask link-neighbors [ die ]
        die
      ]
    ]
    let xt0 min xlist
    let xt1 max xlist
    let yt0 min ylist
    let yt1 max ylist
    let new_id random 10000

    ask rectangle xt0 xt1 yt0 yt1 [
      set id new_id
    ]
  ]

  ask main_rect with [ id != -1 ] [
    set pcolor id / 100
  ]
end

to-report rectangle [ x0 x1 y0 y1 ]
  ; reports a patch-set bounded by
  ; the coordinate arguments passed
  report patches with [
    pxcor >= x0 and pxcor <= x1 and
    pycor >= y0 and pycor <= y1
  ]
end

Output looks something like:

Where colors other than red indicate rectangles with different ids.


text:
Q: Zapier's JavaScript function "btoa" is not defined I am trying to make use of existing sample code for PassKit to create a JWT token with "Run JavaSript by Zapier". But the Zapier does not recognized the btoa function.

ReferenceError: btoa is not defined

According to this website, this function can be called directly. Any idea?
var b64data = btoa("this is my string to turn into base64");

Below is the code that I have written.
var Zap = {
  base64url:function(input){
    var base64String = btoa(input); //<--error here
    return urlConvertBase64(base64String);
  },
  urlConvertBase64:function(input){
    var output = input.replace(/=+$/, '');
    output = output.replace(/\+/g, '-');
    output = output.replace(/\//g, '_');
    return output;
  },
  generateJWT:function(key){
    var header = {
      "alg": "HS256",
      "typ": "JWT"
    };
    var time_now = Math.floor(new Date().getTime()/1000);
    var exp = time_now + 30;
    var body = {
      "exp": exp,
      "key": key
    };
    var token = [];
    token[0] = Zap.base64url(JSON.stringify(header));
    return body;
  }
};
output = [{body: Zap.generateJWT(inputData.Api_key)}]

A: You can use the following:
var b64data = Buffer.from('this is my string to turn into base64').toString('base64');

Node.js doesn't seem to support the atob() and btoa() methods.


text:
Q: DocuSign API Carbon Copy Currently using the DocuSign API, I have a signer and an email to cc the completed documents to. Is it possible to send the completed documents to the docusign account of the (cc person)? For example, if I'm being cc'd the emails, I want my docusign account which is registered with the same email to be able to view my documents on the website. Can the API achieve this? I have already completed the part where the signer and the cc receives emails so for the most part everything is already working.

A: Yes, if the cc person has a DocuSign account, then they should be able to see the envelopes with their documents in it for envelopes they were cc'd on.
You can try this in the developer sandbox by adding a second user to your account. You can make the second user an admin or not.

A: I would second Larry's response, but point out that it's not enough for the email address to match exactly, but the full name must also match exactly what's in the DocuSign account. Otherwise - it will not be tied to the other account for this person.


text:
Q: $\exp\left({\frac{-1}{(x-a)(b-x)}}\right) $ is infinitely differentiable on $(a,b)$ Let $a<b$. I'm trying to prove that $$\exp\left({\frac{-1}{(x-a)(b-x)}}\right) $$ is infinitely differentiable in the open interval $(a,b)$. Induction seems like a good way to proceed, and I know that $\exp(-1/x)$ is infinitely differentiable everywhere except at $x = 0$. But I'm not sure if this helps me in the proof. Any clues on how to proceed?

A: Make $y=(x-a)(b-x)$, then your function trasforms to $exp(-\frac{1}{y})$ and it's infinitely differentiable except points where $y = 0$, e.g. $x = a$ or $x=b$. But $a$ and $b$ aren't included in interval $(a,b)$ so your function is infinitely differentiable.


text:
Q: CSS select element based on fragment identifier in href attribute I am using the tabview, which is part of the YUI3 library.
The markup basically looks like this:

      foo

        foo content

A fiddle of the markup: http://jsfiddle.net/zb6su/
Problem: I am writing some javascript code and would like to select a tab given the tabview-panel. Let's say I was able to get the id, foo, in this case. I would like to select the tab with a[href=#foo].
The problem is that a[href=#foo] does not work at all, because # is used to select Ids. I have also tried a[href="#foo"] to no avail. Is there a css selector to select a link based on a URL fragment in the href attribute?
I know that with javascript, I can iterate through all the nodes and check the href attribute, but I would prefer to use a CSS selector where possible.

Update: The selector does work. It looks like it's a bug in FireFinder (an extension I am using to test the selectors).

A: It works fine with the same selector, but using jQuery (fiddle).
$('a[href="#foo"]').text();

Returns "foo". Same with CSS:
a[href="#foo"] {
    color:red;
}

It seems that the problem was more with F21's FireFinder, not the usage of a[href="#foo"]. Case closed.


text:
Q: Loading double to FPU with GCC (Inline assembler) I've been trying to load a double to the FPU with FLD using GCC inline assembly.
Being not that familiar with the AT&T syntax and not having found anything on the web, I'd greatly appreciate your help.
My intention was to load the address of a to EAX and then do FLD [EAX]...
double atl(double a, int adr) {
    __asm ("movl ptr %0,%%eax"::"r"(a));
    __asm ("fld qword (%eax)");
    //.... some other code here
    __asm("movl ptr %0,%%eax"::"r"(a));
    __asm("fst qword (%eax)");
    return a;
}

A: The easiest is to use the constraint "m", to load from/save to a memory location:
#include <stdio.h>
int main (void) {
    double a = 0.78539816339744;
    asm ("fldl %0;"
         "fsin;"
         "fstpl %0" : "+m"(a));
    printf("sin(45°) = %f\n", a);
    return 0;
}

The modifier "+" tells the compiler that you want your input in that memory location and to output to the same location.
GCC is allowed to reorder your lines, but it will know the semantics of that line, and it will optimize accordingly.
A more difficult example, employing loading from other variables than that are to be written to:
#include <stdio.h>
int main (void) {
    double sin_a, cos_a, a = 0.5;
    asm ("fldl %2;"
         "fsincos;"
         "fstpl %1;"
         "fstpl %0;" : "=m"(sin_a), "=m"(cos_a) : "m"(a));
    printf("sin(29°) = %f, cos(29°) = %f\n", sin_a, cos_a);
    return 0;
}

Live demo: http://ideone.com/SuvpM.
PS: I could not get GCC to load a double value, though, so I don't know if my answer is any use to you. :-(
Update:
Got it: you need to append s (for single [32 bits], as in flds, floating-point load single), l (for double [64 bits]), or t (for long double [80 bits]) explicitely. My GCC 4.6.3 assumes a single value for every memory operand …


text:
Q: pymysql-ProgrammingError(1064, "You have an error in your SQL syntax; I am running this on pymysql and it appears to have a syntax problem although on workbench if i repace %s with a random value it works fine.What am I doing wrong?Also the full error row is this ProgrammingError(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3226'') \n    GROUP BY a2.actor_id=''3226'',a1.actor_id \n    HAVING count(DISTINC' at line 9")
sql_query='''SELECT a1.actor_id as i8opoios1 FROM actor as a1
INNER JOIN actor as a2 on a1.actor_id != a2.actor_id
INNER JOIN role as r1 on a1.actor_id = r1.actor_id
INNER JOIN movie as m1 on m1.movie_id = r1.movie_id
INNER JOIN movie_has_genre as mg1 on mg1.movie_id = m1.movie_id
INNER JOIN role as r2 on a2.actor_id = r2.actor_id
INNER JOIN movie as m2 on m2.movie_id = r2.movie_id
INNER JOIN movie_has_genre as mg2 on mg2.movie_id = m2.movie_id
WHERE (a2.actor_id='%s')
GROUP BY a2.actor_id='%s',a1.actor_id
HAVING count(DISTINCT mg1.genre_id) + count(DISTINCT mg2.genre_id)>=7
AND SUM(mg1.genre_id = mg2.genre_id) = 0'''
cur.execute(sql_query,(actorId,actorId))
results=cur.fetchall()


text:
Q: How do I make a loaded .txt file include the increments in text between lines? Using the following code, I'm loading a local file on a webserver and printing its result to a
 tag, but when I load the file it just dumps all the text onto the page without any consideration to the gaps between lines, it includes the spaces between words but not lines, making it look extremely messy and unreadable (as an Admin
setInterval(function readFile() {
    var client = new XMLHttpRequest();
    client.open('GET', '/logs.txt');
    client.onreadystatechange = function() {
    document.getElementById("log").innerHTML = client.responseText;
    }
    client.send();
    }, 1);

Is there any way I can include the gaps between lines?

A: The current content of your client.responseText is something like the following :
log1
log2
log3

where linefeeds are \n or some other line terminator depending on the source OS.
Since you're overwriting the innerHTML of your
 with that data, it produces this HTML :

log1
log2
log3

where the \n linefeed are meaningless and won't be rendered.
You have two options to achieve your goal :

*

*reformat the data so that it contains "HTML linefeeds". Ideally that would mean multiple
 contained in a
, or probably better multiple
 contained in a
 Using
 tags at the end of each line is another alternative. You can reformat the data using regex, e.g. input.replace(/^.*$/mg, "
$&
") which creates a
 for each line

*make the \n linefeeds matter. This can be achieved by specifying the white-space: preserve CSS attribute, which is set by default for
 tags.


text:
Q: Transitive action of SL(2,R) on the circle Is the circle a homogeneous space for G=SL(2,R)? I think G/B is real analytically isomorphic to the circle where B is Borel  subgroup of G. Is there a transitive algebraic action of G on the circle? Can someone give that action with formulas for every entry given as rational functions in the entries of g and the circle (take circle as unit circle in the plane).
I tried projecting onto the K circle in the KAN=KB decomposition and then multiplying by that rotation but it didn't work.
Maybe something with Möbius transformation acting on the circle bounding the upper half plane viewed as a subset of the Reimannian sphere?
Note: the action cannot be an action by isometries the circle is not a symmetric space for SL(2,R) basically because SO(2,R) is not a group quotient of SL(2,R)

A: Yes, actually in (essentially) two distinct ways.
$G=\mathrm{SL}_2(\mathbf{R})$ acts transitively on the circle $\mathbb{P}^1_\mathbf{R}$; the stabilizer of $\infty$ is $B$ (group of upper triangular matrices), so $G/B$ is homeomorphic to the circle. In this case, the action of $G$ on $B$ is not faithful: the kernel is $\{\pm \mathrm{id}\}$.
Also, $G$ acts on the circle $(\mathbf{R}^2\smallsetminus\{0\})/\mathbf{R}_{>0}$, and the stabilizer of $(1,0)$ for this action is $B^+$, the subgroup of index 2 of $B$ with positive diagonal. In this case, the action of $G$ on $G/B^+$ is faithful.
Note that there's a continuous $G$-equivariant surjection $G/B^+\to G/B$, which is a connected 2-fold covering.


text:
Q: Abraham Williams Twitter OAuth 303 Error EDIT:
I'm sorry for making this thread as I've figured out the problem.
Here's what happened:
First, I noticed that the URL being sent lacked a "/" between .com and account/verify_credentials. When I updated that, I got a 404 error. Then I looked at the twitteroauth.php and I noticed that the top one:
/* Set up the API root URL. */
public $host = "https://api.twitter.com/1/";
//  public $host = "https://dev.twitter.com";

was commented out. I uncommented it, and commented out the lower one (which I'm guessing is no defunct or not used?) and now it works perfectly fine!
Thanks everybody, and thanks Mr. Williams for a great Oauth library!

I've been implementing Abraham Williams Twitter OAuth library and it's been going well so far until I tried to do something with it after connecting to Twitter. That's when I was getting a 303 HTTP code. I then changed my implementation to the way he implements it on his github site, and I still get the same issue. Does anyone have an idea of what's happening?
apitest.php is where the problem occurs, where the $connection variable has a 303 HTTP code. The corresponding $connection variables in redirect.php and callback.php both return a 200. By the way, all of the files are in the same directory.
Here's the code:
connect.php (The HTML on this page has a button that goes to redirect.php)
<?php
/**
* @file
* Check if consumer token is set and if so send user to get a request token.
*/

/**
* Exit with an error message if the CONSUMER_KEY or CONSUMER_SECRET is not defined.
*/
require_once('twitconfig.php');
if (CONSUMER_KEY === '' || CONSUMER_SECRET === '') {
  echo 'A consumer key and secret are required.';
  exit();
}

?>

redirect.php
<?php

/* Start session and load library. */
session_start();
require_once('twitteroauth.php');
require_once('twitconfig.php');

/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);

/* Get temporary credentials. */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);

/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];

/* If last connection failed don't display authorization link. */
switch ($connection->http_code) {
  case 200:
    /* Build authorize URL and redirect user to Twitter. */
    $url = $connection->getAuthorizeURL($token);
    header('Location: ' . $url);
    break;
  default:
    /* Show notification if something went wrong. */
    echo 'Could not connect to Twitter. Refresh the page or try again later.';
}

?>

callback.php
<?php

/**
 * @file
 * Take the user when they return from Twitter. Get access tokens.
 * Verify credentials and redirect to based on response from Twitter.
 */

/* Start session and load lib */
session_start();
require_once('twitteroauth.php');
require_once('twitconfig.php');

/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
  $_SESSION['oauth_status'] = 'oldtoken';
  header('Location: ./clearsessions.php');
}

/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);

/* Request access tokens from twitter */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);

/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;

/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);

/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
  /* The user has been verified and the access tokens can be saved for future use */
  $_SESSION['status'] = 'verified';
  header('Location: ./apitest.php');
} else {
  /* Save HTTP status for error dialog on connnect page.*/
  header('Location: ./clearsessions.php');
}

?>

apitest.php (where the problem is seen via a print_r)
<?php

session_start();
require_once('twitteroauth.php');
require_once('twitconfig.php');

if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
    header('Location: ./clearsessions.php');
}

/* Get user access tokens out of the session. */
$access_token = $_SESSION['access_token'];

/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);

/* Get logged in user to help with tests. */
$user = $connection->get('account/verify_credentials');

print_r($connection);

print_r($_SESSION);

?>

The output of the first print statement is:
TwitterOAuth Object (
[http_code] => 303
[url] => https://dev.twitter.comaccount/verify_credentials.json?oauth_consumer_key=UoXXKdfnVHh2fYD8Csw&oauth_nonce=09bc369393a8eab3a1dc36eaa6230b45&oauth_signature=pe5dYtYq%2FvlGb0c%2BnRR%2BQAXI0Ec%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1314249851&oauth_token=351699791-F6stFFk81poF8ooORgLLxaE2cpSdDT2Vr0Tz9yJm&oauth_version=1.0
[host] => https://dev.twitter.com
[timeout] => 30
[connecttimeout] => 30
[ssl_verifypeer] =>
[format] => json
[decode_json] => 1
[http_info] => Array ( [url] => https://dev.twitter.comaccount/verify_credentials.json?oauth_consumer_key=UoXXKdfnVHh2fYD8Csw&oauth_nonce=09bc369393a8eab3a1dc36eaa6230b45&oauth_signature=pe5dYtYq%2FvlGb0c%2BnRR%2BQAXI0Ec%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1314249851&oauth_token=351699791-F6stFFk81poF8ooORgLLxaE2cpSdDT2Vr0Tz9yJm&oauth_version=1.0
[content_type] =>
[http_code] => 303
[header_size] => 565
[request_size] => 401
[filetime] => -1
[ssl_verify_result] => 1
[redirect_count] => 0
[total_time] => 0.053773
[namelookup_time] => 0.003355
[connect_time] => 0.006399
[pretransfer_time] => 0.047636
[size_upload] => 0
[size_download] => 0
[speed_download] => 0
[speed_upload] => 0
[download_content_length] => 0
[upload_content_length] => 0
[starttransfer_time] => 0.053629
[redirect_time] => 0
[certinfo] => Array ( ) )
[useragent] => TwitterOAuth v0.2.0-beta2
[sha1_method] => OAuthSignatureMethod_HMAC_SHA1 Object ( )
[consumer] => OAuthConsumer Object ( [key] => UoXXKdfnVHh2fYD8Csw [secret] => SyKfxRorvUs6THwj5l26TGEkFOCGf1vG86N7PoS97o [callback_url] => ) [token] => OAuthConsumer Object ( [key] => 351699791-F6stFFk81poF8ooORgLLxaE2cpSdDT2Vr0Tz9yJm [secret] => q8fHaTaFvOUL8XKYX89LSgubr2fSl1xHBUAi8MUqIc [callback_url] => )

[http_header] => Array ( [location] => http://guide.a.id.opendns.com/?url=dev%2Etwitter%2Ecomaccount%2Fverify%5Fcredentials%2Ejson%3Foauth%5Fconsumer%5Fkey%3DUoXXKdfnVHh2fYD8Csw%26oauth%5Fnonce%3D09bc369393a8eab3a1dc36eaa6230b45%26oauth%5Fsignature%3Dpe5dYtYq%252FvlGb0c%252BnRR%252BQAXI0Ec%253D%26oauth%5Fsignature%5Fmethod%3DHMAC%2DSHA1%26oauth%5Ftimestamp%3D1314249851%26oauth%5Ftoken%3D351699791%2DF6stFFk81poF8ooORgLLxaE2cpSdDT2Vr0Tz9yJm%26oauth%5Fversion%3D1%2E0
[content_length] => 0
[connection] => close
[date] => Thu, 25 Aug 2011 05:24:50 GMT
[server] => OpenDNS Guide ) )

The output of the second print statement is:
Array (
[access_token] => Array (
[oauth_token] => 351699791-F6stFFk81poF8ooORgLLxaE2cpSdDT2Vr0Tz9yJm
[oauth_token_secret] => q8fHaTaFvOUL8XKYX89LSgubr2fSl1xHBUAi8MUqIc
[user_id] => 351699791
[screen_name] => jibjib21 )
[status] => verified )

Does anyone have an idea of what's going on with this 303 error and how to resolve it? Any help would be greatly appreciated. Thanks!

A: A 303 response is a redirect. My guess is you need to add .json (or whatever format you are using) to the end of the URL you are requesting.
I.e. instead of 'account/verify_credentials', you need to request 'account/verify_credentials.json'.


text:
Q: Do we use try,except in every single function? Should we always enclose every function we write with a  try...except  block?
I ask this because sometimes in one function we raise Exception, and the caller that calls this function doesn't have exception
def caller():
   stdout, stderr = callee(....)

def callee():
   ....
    if stderr:
       raise StandardError(....)

then our application crash. In this obvious case, I am tempted to enclose callee and caller with try..except.
But I've read so many Python code and they don't do these try..block all the time.

def cmd(cmdl):
    try:
        pid = Popen(cmdl, stdout=PIPE, stderr=PIPE)
    except Exception, e:
        raise e
    stdout, stderr = pid.communicate()
    if pid.returncode != 0:
        raise StandardError(stderr)
    return (stdout, stderr)

def addandremove(*args,**kwargs):
    target = kwargs.get('local', os.getcwd())
    f = kwargs.get('file', None)
    vcs = kwargs.get('vcs', 'hg')

    if vcs is "hg":
        try:
            stdout, stderr = cmd(['hg', 'addremove', '--similarity 95'])
        except StandardError, e:
            // do some recovery
        except Exception, e:
            // do something meaningful
    return True

The real thing that bothers me is this:
If there is a 3rd function that calls addandremove() in one of the statements, do we also surround the call with a try..except block? What if this 3rd function has 3 lines, and each function calls itself has a try-except? I am sorry for building this up. But this is the sort of problem I don't get.

A: You should use a try catch block so that you can specifically locate the source of the exception. You can put these blocks around anything you want, but unless they produce some sort of useful information, there is no need to add them.

A: try/except clauses are really only useful if you know how to handle the error that gets raised.  Take the following program:
while True:
    n=raw_input("Input a number>")
    try:
       n=float(n)
       break
    except ValueError:
       print ("That wasn't a number!")  #Try again.

However, you may have a function like:
def mult_2_numbers(x,y):
    return x*y

and the user may try to use it as:
my_new_list=mult_2_numbers([7,3],[8,7])

The user could put this in a try/except block, but then my_new_list wouldn't be defined and would probably just raise an exception later (likely a NameError).  In that case, you'd make it harder to debug because the line number/information in the traceback is pointing to a piece of code which isn't the real problem.

A: Exceptions are, as the name implies, for exceptional circumstances - things that shouldn't really happen
..and because they probably shouldn't happen, for the most part, you can ignore them. This is a good thing.
There are times where you do except an specific exception, for example if I do:
urllib2.urlopen("http://example.com")

In this case, it's reasonable to expect the "cannot contact server" error, so you might do:
try:
    urllib2.urlopen("http://example.com")
except urllib2.URLError:
    # code to handle the error, maybe retry the server,
    # report the error in a helpful way to the user etc

However it would be futile to try and catch every possible error - there's an inenumerable amount of things that could potentially go wrong.. As a strange example, what if a module modifies urllib2 and removes the urlopen attribute - there's no sane reason to expect that NameError, and no sane way you could handle such an error, therefore you just let the exception propagate up
Having your code exit with a traceback is a good thing - it allows you to easily see where the problem originate, and what caused it (based on the exception and it's message), and fix the cause of the problem, or handle the exception in the correct location...
In short, handle exceptions only if you can do something useful with them. If not, trying to handle all the countless possible errors will only make your code buggier and harder to fix

In the example you provide, the try/except blocks do nothing - they just reraise the exception, so it's identical to the much tidier:
def cmd(cmdl):
    pid = Popen(cmdl, stdout=PIPE, stderr=PIPE)
    stdout, stderr = pid.communicate()
    if pid.returncode != 0:
        raise StandardError(stderr)
    return (stdout, stderr)

# Note: Better to use actual args instead of * and **,
# gives better error handling and docs from help()
def addandremove(fname, local = None, vcs = 'hg'):
    if target is None:
       target = os.getcwd()

    if vcs is "hg":
        stdout, stderr = cmd(['hg', 'addremove', '--similarity 95'])
    return True

About the only exception-handling related thing I might expect is to handle if the 'hg' command isn't found, the resulting exception isn't particularly descriptive. So for a library, I'd do something like:
class CommandNotFound(Exception): pass

def cmd(cmdl):
    try:
        pid = Popen(cmdl, stdout=PIPE, stderr=PIPE)
    except OSError, e:
        if e.errno == 2:
            raise CommandNotFound("The command %r could not be found" % cmdl)
        else:
            # Unexpected error-number in OSError,
            # so a bare "raise" statement will reraise the error
            raise

    stdout, stderr = pid.communicate()
    if pid.returncode != 0:
        raise StandardError(stderr)
    return (stdout, stderr)

This just wraps the potentially confusing "OSError" exception in the clearer "CommandNotFound".
Rereading the question, I suspect you might be misunderstanding something about how Python exceptions work (the "and the caller that calls this function doesn't have exception" bit, so to be hopefully clarify:
The caller function does not need any knowledge of the exceptions that might be raised from the children function. You can just call the cmd() function and hope it works fine.
Say your code is in a mystuff module, and someone else wants to use it, they might do:
import mystuff

mystuff.addandremove("myfile.txt")

Or, maybe they want to give a nice error message and exit if the user doesn't have hg installed:
import mystuff

try:
    mystuff.addandremove("myfile.txt")
except mystuff.CommandNotFound:
    print "You don't appear to have the 'hg' command installed"
    print "You can install it with by... etc..."
    myprogram.quit("blahblahblah")

A: There are a couple of programming decisions for your coding team to make regarding introspection type tools and "exception" handling.
One good place to use exception handling is with Operating System calls such as file operations. Reasoning is, for example, a file may have it's access restricted from being accessed by the client appliction. That access restriction is typically an OS-admin task, not the Python application function. So exceptions would be a good use where you application does NOT have control.
You can mutate the previous paragraph's application of exceptions to be broader, in the sense of using Exceptions for things outside the control of what your team codes, to such things as all "devices" or OS resources like OS timers, symbolic links, network connections, etc.
Another common use case is when you use a library or package that is -designed- to through lots of exceptions, and that package expects you to catch or code for that. Some packages are designed to throw as few exceptions as possible and expect you to code based on return values. Then your exceptions should be rare.
Some coding teams use exceptions as a way to log fringe cases of "events" within your application.
I find when desiding whether to use exceptions I am either programing to minimize failure  by not having a lot of try/except and have calling routines expect either valid return values or expect an invalid return values.  OR I program for failure. That is to say, I program for expected failure by functions, which I use alot of try/except blocks. Think of programming for "expected" failure like working with TCP; the packets aren't garenteed to get there or even in order, but there are exception handling with TCP by use of send/read retrys and such.
Personally I use try-except blocks around the smallest possible block sizes, usually one line of code.

A: It's up to you; the main exceptions' roles involve (a quote from this splendid book):

*

*Error handling

*Event notification

*Special-case handling

*Termination actions

*Unusual control flows

A: When you know what the error will be, use try/except for debugging purpose. Otherwise, you don't have to use try/except for every function.


text:
Q: rails postgreSQL cannot get this query to work (SUM, Group Order) This query work when I try it in SQLite:
Transaction.where(:paid => true).select("created_at, SUM(amount) amount").group("DATE(created_at)").order('created_at')

But when I run it with postgreSQL it doesn'y work.
Heres the error message:
ActiveRecord::StatementInvalid: PGError: ERROR:  column "transactions.created_at" must appear in the GROUP BY clause or be used in an aggregate function : SELECT created_at, SUM(amount) as amount FROM "transactions" WHERE ("transactions"."paid" = 't') GROUP BY DATE(created_at) ORDER BY created_at

Anyone who can help me?
Thanks in advance

A: You have to either use DATE(created_at) in the select clause, or use created_at in the group by clause.

A: You're selecting created_at, sum(amount), ordering by created_at, but are grouping by  date(created_at). The latter will disallow the use of anything but the grouped by fields and aggregates except in the join/where clause.
To fix, either group by created_at, or select and order by date(created_at) instead of created_at.


text:
Q: Azure Mobile Services - custom authentication provider for all our apps We plan to use Windows Azure Mobile Services for several of our commercial apps and would like to create a single data store for users instead of creating it for every mobile service. We don't want to use Microsoft or Facebook... providers due to this issue Multiple apps using a single Azure Mobile Service for Live Authentication?
This way, the user data for all our apps is stored in single separate Custom_Auth database and the users won't need to Register again for our other apps. Should we create a separate mobile service that basically enables custom authentication and acts as a provider for other apps?
Do you see any pitfalls with this approach and what steps would I need to take for creating this custom provider as a separate mobile service?
Basically, we want to create our own provider so that user of one our apps can login to the other apps using the same credentials.
I have read through the following links. Posting them here as they may be useful for others starting out with Authentication and Azure Mobile Services.
http://www.thejoyofcode.com/Generating_your_own_ZUMO_auth_token_Day_8_.aspx
http://www.thejoyofcode.com/Fetching_a_basic_user_profile_in_Mobile_Services_Day_9_.aspx
http://www.thejoyofcode.com/Exploring_custom_identity_in_Mobile_Services_Day_12_.aspx
http://chrisrisner.com/Authentication-with-Windows-Azure-Mobile-Services
Thanks in advance

A: Hope this helps you
http://chrisrisner.com/Authentication-with-iOS-and-Windows-Azure-Mobile-Services
Someone created a custom authentication API using AZURE
with Parse.com, you are limited to their backend and unfortunately it doesn't have all the nice features as Azure
MS really messed us around with this


text:
Q: NHibernate: How to load only specific properties in a list of entities (instead of full object)? I have been using NHibernate in my project and it is working very good until the time.
Now I am facing one problem and don't know how to solve it.
Problem is I want to fetch only x columns from table instead of all and then bind this to original entity with fetched columns assigned values where for others should show null.
e.g. I have table Employee as
FieldName DataType
ID        int
FName     nvarchar(500)
LName     nvarchar(500)
Resume    nvarchar(max)
From above I want to fetch only Id, FName, LName only and bind it to Employee entity and then we would like to load Resume by making separate database call using NHibernate.
I tried
var list = session
    .CreateCriteria(typeof (Employee))
    .SetProjection(Projections
                       .ProjectionList()
                       .Add(Projections.Property("Id"))
                       .Add(Projections.Property("FName"))
                       .Add(Projections.Property("LName")))
    .List();

but above code returns restricted column data but in form of array of object.
I wanted this to get bind to entity instead of object array.
So, please share your thoughts on this

A: You need to set the ResultTransformer and call ToList() with the type, otherwise NHibernate didn't know what to do with the projections. And you need also to specifiy the target property names in your Employee type.
Your query can look simething like this:
var list = session
    .CreateCriteria(typeof (Employee))
    .SetProjection(Projections
                   .ProjectionList()
                   .Add(Projections.Property("Id"), "Id")
                   .Add(Projections.Property("FName"), "FirstName")
                   .Add(Projections.Property("LName"), "LastName"))
    .SetResultTransformer(Transformers.AliasToBean<Employee>())
    .List<Employee>();

Please note: "Id", "FirstName" and "LastName" must be properties in the Employee type.

A: Answer from @Rabban explains it well; +1 to him. I am just putting it differently.
As you observed, SetProjection will return array of objects. To convert objects to entities, you need to call SetResultTransformer(Transformers.AliasToBean<Entity>(). The code sample is already given in other answer; I will not repeat it.
Problem with your current code is that, you need to type in column names as string. I generally avoid this approach. I prefer to use strongly typed version of same with IQueryOver as below:
public IList<TEntity> GetList<TEntity>(ProjectionList columnList, Junction where, int top) where TEntity : BaseEntity
{
    IQueryOver<TEntity> query = null;
    if((columnList != null) && (where != null))
    {
        query = session.QueryOver<TEntity>()
                .Select(columnList)
                .TransformUsing(Transformers.AliasToBean<TEntity>())
                .Where(where);
    }
    else if((columnList != null) && (where == null))
    {
        query = session.QueryOver<TEntity>()
                .Select(columnList)
                .TransformUsing(Transformers.AliasToBean<TEntity>());
    }
    else if((columnList == null) && (where != null))
    {
        query = session.QueryOver<TEntity>()
                .Where(where);
    }
    else
    {
        query = session.QueryOver<TEntity>();
    }

    IList<TEntity> result = query.Take(top).List();
    return result;
}

You can pass strongly typed list of columns to this method as below:
ProjectionList columnList = Projections.ProjectionList();
columnList.Add(Projections.Property<Employee>(x => x.Id));
...
...


text:
Q: context switch in Linux hello everyone I found this function in Kernel of the Linux:
inline task_t *context_switch(task_t *prev, task_t *next) {
...

switch_to(prev, next, prev);
return prev;
}

this function is making context switch, my question is why this function should be inline and not macro for example, thanks in advance...

A: It may not be a macro because a macro to do this would evaluate prev and next twice each, when they may be expressions with side effects. Also, after some searching I found that switch_to is (on some platforms) a macro that is a statement in braces, and therefore cannot return a value to be used in an expression.
I found some of this info here: https://docs.blackfin.uclinux.org/doku.php?id=linux-kernel:task_switching

A: Macros are a way to make inline functions, when your C compiler does not do inline functions. A macro, contrary to inline functions, won't do compile-time parameters verification. So inline function are better for maintenance.


text:
Q: Cannot post to Sinatra but get works I am writing an app that runs Sinatra as a background thread to provide an API.
I defined a route for a GET that works ok but when I try  post I keep seeing it fail in WEBrick at the same place. The error is:
[2018-01-18 20:43:05] ERROR NoMethodError: undefined method `each' for nil:NilClass
/Users/atkinsb/.gem/ruby/2.4.0/gems/rack-2.0.3/lib/rack/handler/webrick.rb:90:in `service'
/Users/atkinsb/.rbenv/versions/2.4.2/lib/ruby/2.4.0/webrick/httpserver.rb:140:in `service'
/Users/atkinsb/.rbenv/versions/2.4.2/lib/ruby/2.4.0/webrick/httpserver.rb:96:in `run'
/Users/atkinsb/.rbenv/versions/2.4.2/lib/ruby/2.4.0/webrick/server.rb:290:in `block in start_thread'
::1 - - [18/Jan/2018:20:43:05 GMT] "POST /message HTTP/1.1" 500 320
- -> /message

I think the problem is on line 86:
status, headers, body = @app.call(env)

This always returns nil for all three variables when I do the post.
post '/message' do
  ApiServer::Base::SM.message(JSON.parse(request.body.read))
end

The post body:
{
  "id": "1",
  "sender": "localhost",
  "action": "SYS_NORMAL_SHUTDOWN",
  "payload": "",
  "ack": "0",
  "date_time": "2018-01-18 08:58:50 +0000"
}

I'm posting with a header in postman:
Content-Type application/json

I'm stumped by this. Any idea what I am doing wrong?
PS. I forgot to mention that the json body is parsed ok in the route...
Also the body returned from the post is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">

        <TITLE>Internal Server Error</TITLE>

Internal Server Error

           undefined method `each' for nil:NilClass

        <ADDRESS>
           WEBrick/1.3.1 (Ruby/2.4.2/2017-09-14) at
           localhost:4567
        </ADDRESS>

A: Well, after all that. It seems that the problem was I needed to return some sort of response.
  # Server API route '/message'
  def message(params)
      js = build_message(params['action'], params['payload'])
      write_message_to_file(js)
      '{ "status": "Message Received" }'
  end


text:
Q: What is the need to Cache a DataFrame when data already cached in local variable per session? I am new to Spark. Trying to understand how Cache and Persist works.
I understand the need to cache any DataFrame if that data is referenced by other spark operations.
BUT..
I performed WordCount on 11GB file:
spark.read.textFile("file:///g:/dummy.txt")
 res1.flatMap(_.split(" ")).map(word => (word,1))
 res3.rdd.reduceByKey.toDF

and got:
res4: org.apache.spark.sql.DataFrame = [_1: string, _2: int]

When I call res4.show spark starts the execution and all tasks are executed.
After its completion I call res4.show again but this time it directly returns me the data in console.
Question is : If res4 is available in current spark session, then do I want to do res4.cache even if it is readily available? If yes then what is the scope  of res4?
Thanks!

A: Cache/Persist  are useful when you want the data(res4) to be used in computing any other output.
Say if I have a scenario, I want to identify the words which are of 5 letters then res4 can be used directly , if it is cached or whenever you will call an action, it is recomputed.
And now  I have a request to fetch words with 10 letters then if res4 is cached , speed will be much faster as spark engine already have res4 in memory.
If it is not cached, then will each action it will be recomputed.
For more details , please refer https://spark.apache.org/docs/latest/rdd-programming-guide.html

A: This question is a little unclear, but let us try and bring some clarity with the simple example.
1) This is how you do reduceByKey:
val f = spark.read.textFile("/FileStore/tables/jjj.txt")
val g = f.flatMap(_.split(" ")).map(word => (word,1))
val h = g.rdd.reduceByKey((a, b) => a + b).toDF()
h.show()
h.show()

2) h.show() is a special Action, but an Action none-the-less.
   The second time it can use skipped processing, the results that are already there on disk/memory and can be accessed immediately without a re-computation. E.g.:
(2) Spark Jobs
Job 4 View(Stages: 2/2)
Job 5 View(Stages: 1/1, 1 skipped)

A more thorough explanation
Skipped means that data can be gotten from cache(memory or disk), so no new separate Action necessary i.e. re-execution (of Stage). It depends on what you code.
There is a case of "shuffling" going on, which means caching or writing intermediate files to disk. In latter case these will be kept around until no longer req'd - e.g. RDD expires and are removed via Garbage Collection.
It's a bit more advanced, but I leave it at this as it covers the gist of it all.


text:
Q: SSL Error "unexpected message" When I tested some Python code for different scenarios, I received the following error for the correct port, URL, username, and password:
SSL23_GET_SERVER_HELLO:sslv3 alert unexpected message

I got the exact same error and traceback when I used a bogus username, and also when I used the correct username but the wrong password.  Could it be expecting SSL v3, and the version that is installed is older?  Just a guess.  I didn't see anything in the Python code that set the SSL version number.

A: Please can you post the code so that It is easy to resolve the problem.
This link may help you [SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert unexpected message

A: You can use SSLAdapter to set the SSL and TLS versions.
I was getting a similar error and it was caused by the server using TLS 1.3, but I only have TLS 1.2 installed. So I had to do the following:
from requests_toolbelt import SSLAdapter
import ssl
import requests

session = requests.Session()
session.mount('https://', SSLAdapter(ssl.PROTOCOL_TLSv1_2))
session.get(myurl)

If you can reach the server with a browser, you can check the SSL and TLS version by clicking on the lock or shield symbol next to the url.


text:
Q: GDB Switch Between Debugging and Program Input So I'm trying to debug a program that takes user input through the terminal. I'm using the GNU Debugger (gdb) to do so. When I reach the point where the program is waiting for user input it no longer allows me to control gdb and instead forces me to give input to the program.
The difficulty is, I want to debug the program at this exact point, but before there is any input given. So how do I switch between giving input to the program and controlling gdb? I've tried googling and searching through the manual for gdb but can't seem to find anything on switching between input to the program and input to gdb.

A:
When I reach the point where the program is waiting for user input it no longer allows me to control gdb and instead forces me to give input to the program.

If you hit Control-C at that point, the inferior (being debugged) program should get interrupted, you should get a (gdb) prompt, and you should be able to control GDB all you want.
Once you are done, use continue GDB command to go back and resume the inferior reading its input.


text:
Q: Why doesn't passing toUpperCase to map work I was looking at a question yesterday in which the poster was asking how to convert the case of an array's contents. I know that I can pass a reference to a function to map like:
function appendText (el){
    return el += ' - appended text';
}

['a','b'].map(appendText);  //["a - appended text", "b - appended text"]

But when I tried with
array.map(String.toUpperCase);
array.map(String.prototype.toUpperCase);

I get the error

Uncaught TypeError: String.prototype.toUpperCase called on null or undefined

Which makes it sound like the method isn't getting passed the element map would, as I understand it, be passing. Why doesn't this work?

A: You are not passing anything to the prototype / extension method. Simply use an arrow function to pass in the value of the array item.
To answer the logic behind the question, you simply can't pass the context-less (e.g. no this) prototype method (that is, from the base String class). map will run the function by name with the value as the first parameter (as shown with appendText(a))

function appendText (el){
    return el += ' - appended text'
}

var array = ['a','b']

console.log(array.map(appendText))
console.log(array.map(a => appendText(a)))
console.log(array.map(a => a.toUpperCase()))


text:
Q: How to convert YearWeek format to date? My data: c("202001", "202002").
It shows Year and the number of the week.  I need to get the first day of the week added to my data.
How can I get it?
Desired output: 2020-01-06 and 2020-01-13.
Original data, for which the code should work
c(
"202001", "202002", "202003", "202004", "202005", "202006", "202007",
"202008", "202009", "202010", "202011", "202012", "202013", "202014",
"202015", "202016", "202017", "202018", "202019", "202020", "202021",
"202022", "202023", "202024", "202025", "202026", "202027", "202028",
"202029", "202030", "202031", "202032", "202033", "202034", "202035",
"202036", "202037", "202038", "202039", "202040", "202041", "202042",
"202043", "202044", "202045", "202046", "202047", "202048", "202049",
"202050", "202051", "202052", "202053", "202101", "202102", "202103")```

A: You can do this with base-r using as.Date and specifying the format.
Week of the year

*

*US convention: Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1): %U

*UK convention: Week of the year as decimal number (00–53) using Monday as the first day of week (and typically with the first Monday of the year as day 1 of week 1): %W

*ISO 8601 definition: Week of the year as decimal number (01–53) as defined in ISO 8601. If the week (starting on Monday) containing 1 January has four or more days in the new year, then it is considered week 1. Otherwise, it is the last week of the previous year, and the next week is week 1: %V which is accepted but ignored on input.
Note that there is also a week-based year (%G and %g) which is to be used with %V as it may differ from the calendar year (%Y and %y).
Numeric weekday

*

*Weekday as a decimal number (1–7, Monday is 1): %u

*Weekday as decimal number (0–6, Sunday is 0): %w
I append 1 to create a date string referencing the first day of the year-week and then specify the format using strptime codes when calling as.date to convert it.
Example with US convention:
dateList <-  c("202001", "202002")

dateList <- paste0(dateList, "1")

dateList <- as.Date(dateList , format = "%Y%W%u")

More information on the formats is available here:
https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/strptime

A: One way would be to use lubridate package like this:
c("202001", "202002") -> x
lubridate::ymd('2019-12-30') + lubridate::weeks(as.numeric(substr(x, 5, 6)))

#"2020-01-06" "2020-01-13"


text:
Q: Splitting a string with no line breaks into a list of lines with a maximum column count I have a long string (multiple paragraphs) which I need to split into a list of line strings.  The determination of what makes a "line" is based on:

*

*The number of characters in the line is less than or equal to X (where X is a fixed number of columns per line_)

*OR, there is a newline in the original string (that will force a new "line" to be created.

I know I can do this algorithmically but I was wondering if python has something that can handle this case.  It's essentially word-wrapping a string.
And, by the way, the output lines must be broken on word boundaries, not character boundaries.
Here's an example of input and output:
Input:
"Within eight hours of Wilson's outburst, his Democratic opponent, former-Marine Rob Miller, had received nearly 3,000 individual contributions raising approximately $100,000, the Democratic Congressional Campaign Committee said.

Wilson, a conservative Republican who promotes a strong national defense and reining in the size of government, won a special election to the House in 2001, succeeding the late Rep. Floyd Spence, R-S.C. Wilson had worked on Spence's staff on Capitol Hill and also had served as an intern for Sen. Strom Thurmond, R-S.C."

Output:
"Within eight hours of Wilson's outburst, his"
"Democratic opponent, former-Marine Rob Miller,"
" had received nearly 3,000 individual "
"contributions raising approximately $100,000,"
" the Democratic Congressional Campaign Committee"
" said."
""
"Wilson, a conservative Republican who promotes a "
"strong national defense and reining in the size "
"of government, won a special election to the House"
" in 2001, succeeding the late Rep. Floyd Spence, "
"R-S.C. Wilson had worked on Spence's staff on "
"Capitol Hill and also had served as an intern"
" for Sen. Strom Thurmond, R-S.C."

A: You probably want to use the textwrap function in the standard library:
http://docs.python.org/library/textwrap.html

A: EDIT
What you are looking for is textwrap, but that's only part of the solution not the complete one. To take newline into account you need to do this:
from textwrap import wrap
'\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()])

>>> print '\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitlines()])

Within eight hours of Wilson's outburst, his
Democratic opponent, former-Marine Rob Miller, had
received nearly 3,000 individual contributions
raising approximately $100,000, the Democratic
Congressional Campaign Committee said.

Wilson, a conservative Republican who promotes a
strong national defense and reining in the size of
government, won a special election to the House in
2001, succeeding the late Rep. Floyd Spence,
R-S.C. Wilson had worked on Spence's staff on
Capitol Hill and also had served as an intern for
Sen. Strom Thurmond


text:
Q: Using Nservice bus to send messages from Web application to Desktop windows application I Have web application and another Desktop application , both are .Net applications. User can add news and upload documents to the web application ,
I need my Desktop application to get Notified about this added things on the web application. I had invistigated in this and i figured out that i should implement a publisher/Subscriber pattern and i found also that this could be implemented using Nservice Bus.
All what i need is to find a good article that implements a sample similar to what i had explained here because i am new in this and i don't kow how to start .

A: I would suggest having another endpoint (on your backend tier) that will process a command from your web application and then publish an event, the desktop application will subscribe to the event published by the backend component.
Here is more information about publishing events from web applications
Hope this helps.


text:
Q: Como comparar duas datas no DatagridView e mudar de cor quando expirar VB.Net Meus codigos
Private Sub CadastroDataGridView_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles CadastroDataGridView.CellFormatting
If Me.CadastroDataGridView.Columns(e.ColumnIndex).Name = "DataGridViewTextBoxColumn15" Then
    If e.Value IsNot Nothing Then
        Dim dgvdate As Date = CDate(e.Value)
        If dgvdate < CDate(Now) Then
            e.CellStyle.BackColor = Color.Red
            e.FormattingApplied = True
        Else
            e.CellStyle.BackColor = Color.Green
            e.FormattingApplied = True
        End If

    End If
    End If

End Sub

A: Deve ficar algo do tipo:
For Each linha As DataGridViewRow In DataGridView_consulta.Rows
     valor_celula = linha.Cells(2).Value

     If valor_celula = "Aberto" Then
          linha.Cells(2).Style.BackColor = Color.Red
End If

Só substituir ai a comparação por data e colocar em um método sendo chamado no load. A ideia é percorrer as linhas do datagrid, pegar o valor da célula, que é uma coluna fixa e seta o estilo dela.


text:
Q: Handle unique number validation on Angular 4? I am having a table with input type number on the loop with total 5 records. If user select values between 1 to 10 on the input box and need a validation "Select Unique values only", if user select same values on the input.
I would like to display the error message outside the ngfor loop. I have a function validateUnique to return the boolean value to display the error message.
My code:
    validateUnique(t, j): boolean {
    let res = true;
    const control = this.testFormControls.controls;

    for (let i = 0; i < control.length; i++) {
        if (t.value.rank === control[i].value.rank) {
            res = false;
            break;
        } else {
            res = true;
        }
    }
    return res;
}

I really appreciate the clue to display the error message outside the loop only one time. if validation fails...


text:
Q: Getting:" Attempted to call function "curl_init" from namespace", even though CURL is installed I am getting the error,

Attempted to call function "curl_init" from namespace

but this is with curl installed and enabled.
The output from php --ini is as follows:
> Configuration File (php.ini) Path: /etc/php/5.6/cli Loaded
> Configuration File:         /etc/php/5.6/cli/php.ini Scan for
> additional .ini files in: /etc/php/5.6/cli/conf.d Additional .ini
> files parsed:      /etc/php/5.6/cli/conf.d/10-mysqlnd.ini,
> /etc/php/5.6/cli/conf.d/10-opcache.ini,
> /etc/php/5.6/cli/conf.d/10-pdo.ini,
> /etc/php/5.6/cli/conf.d/15-xml.ini,
> /etc/php/5.6/cli/conf.d/20-calendar.ini,
> /etc/php/5.6/cli/conf.d/20-ctype.ini,
> /etc/php/5.6/cli/conf.d/20-curl.ini,
> /etc/php/5.6/cli/conf.d/20-dom.ini,
> /etc/php/5.6/cli/conf.d/20-exif.ini,
> /etc/php/5.6/cli/conf.d/20-fileinfo.ini,
> /etc/php/5.6/cli/conf.d/20-ftp.ini, /etc/php/5.6/cli/conf.d/20-gd.ini,
> /etc/php/5.6/cli/conf.d/20-gearman.ini,
> /etc/php/5.6/cli/conf.d/20-gettext.ini,
> /etc/php/5.6/cli/conf.d/20-iconv.ini,
> /etc/php/5.6/cli/conf.d/20-imap.ini,
> /etc/php/5.6/cli/conf.d/20-json.ini,
> /etc/php/5.6/cli/conf.d/20-mbstring.ini,
> /etc/php/5.6/cli/conf.d/20-mcrypt.ini,
> /etc/php/5.6/cli/conf.d/20-mongodb.ini,
> /etc/php/5.6/cli/conf.d/20-mysql.ini,
> /etc/php/5.6/cli/conf.d/20-mysqli.ini,
> /etc/php/5.6/cli/conf.d/20-pdo_mysql.ini,
> /etc/php/5.6/cli/conf.d/20-phar.ini,
> /etc/php/5.6/cli/conf.d/20-posix.ini,
> /etc/php/5.6/cli/conf.d/20-readline.ini,
> /etc/php/5.6/cli/conf.d/20-shmop.ini,
> /etc/php/5.6/cli/conf.d/20-simplexml.ini,
> /etc/php/5.6/cli/conf.d/20-sockets.ini,
> /etc/php/5.6/cli/conf.d/20-sysvmsg.ini,
> /etc/php/5.6/cli/conf.d/20-sysvsem.ini,
> /etc/php/5.6/cli/conf.d/20-sysvshm.ini,
> /etc/php/5.6/cli/conf.d/20-tokenizer.ini,
> /etc/php/5.6/cli/conf.d/20-wddx.ini,
> /etc/php/5.6/cli/conf.d/20-xmlreader.ini,
> /etc/php/5.6/cli/conf.d/20-xmlwriter.ini,
> /etc/php/5.6/cli/conf.d/20-xsl.ini, /etc/php/5.6/cli/conf.d/20-zip.ini

I have even verified that it works by creating a curl request in a new file, and it worked!
This seems to be a problem specific to the Symfony, but I am reaching out to understand if I have missed out anything.
I am currently running Php 5.6.4, and the MVC framework is Symfony 2.8.
The procedure I have followed is

*

*sudo add-apt-repository ppa:ondrej/php

*sudo apt update

*sudo apt install php5.6-curl

*sudo service apache2 restart

This is the code
use CURLFile;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\OptimisticLockException;
use LogicException;
$url = "http://www.google.com";
$ch  = curl_init($url);

Looking for any sort of help.


text:
Q: Broken repository + error based on repo name Background:
I run VisualSVN on a windows server.
Problem:
I started getting errors on my nightly SVN hotcopy (svnadmin: E200002: Serialized hash missing terminator). I tried unsuccessfully to determine the source of the error and SVNADMIN VERIFY/RECOVER were returning no errors so I decided to try a dump & load.
This seemed to work successfully but when I renamed the test repository to the same name as the old one I got the error 'Corrupt node-revision'. I tried not loading the last few revisions (i.e. dumped until a few earlier) and I still get the same problem. When I rename it back to another name the problem stops. See follow-up - I'm not sure why but re-installing a new version of VisualSVN fixed the naming problem; I'm still unsure what caused it.
The questions I am hoping to have answered are:

*

*What was likely to cause the original error?

*Why would the name of a repo impact it's viability? (This may be VisualSVN cache thing - is it possible to fix it so I don't have to switch all the users working copies?)

*Can I do anything to stop either issue happening in the future?

Follow up: After deciding the name change was almost certainly some issue with VisualSVN I uninstalled the version I was running (2.6.5) and moved to the current version (2.7.3). I pointed it to the same repositories folder and after installation everything worked! I'm not sure if re-installing the same version would have fixed the issue but as I haven't put too much time into configuring VisualSVN (since I originally migrated the repositories in) I didn't have much to lose..

A: I experienced the same issue in VisualSVN 3.2.2. While re-installing the application would solve the problem, I was able to solve the problem by restarting the VisualSVN Server service.
I've submitted a bug report to VisualSVN (they don't appear to have a public issue tracker).


text:
Q: Can't reach deeper nodes in FirebaseDatabase.net This is a question about FirebaseDatabase.net library
To put this more specifically, I can't reach nodes that are two or more nodes deeper than the root node.
So this for example, this doesn't work:
var firebase = new FirebaseClient("https://dinosaur-facts.firebaseio.com/");
firebase.Child("dinosaurs").Child("t-rex").PutAsync(new Dinosaur())

Because firebase.Child returns ChildQuery object which doesn't have Child method.
I'm using version 3.0.0 installed via NuGet.
If this really doesn't work, is there another way to get the deeper node?

A: Add this at the top of your class:
using Firebase.Database.Query;


text:
Q: How to represent a 'long' number as nodes in a linked-list [JAVA] I have a pragmatic task to solve:
Int and Long numbers that we can store in memory cells
are limited in size. One way to solve the problem would be to set up a linked-list in which each node in the list will contain one digit from the number so that the number itself will not be kept as a number but as a collection of its' digits- one after the other.
I have to create a Constructor, which gets a 'long' type of number and stores it in a format of a linked list.
By that I mean that if we take the number 233,674,318 , the Constructor would create a representation of this number as the following : 2 -> 3 -> 3 -> 6 -> 7 -> 4 -> 3 -> 1 -> 8
Could you please suggest me how can I approach this?
Thank you in advance!

A: You can extract a number's least significant digit (the one on the right) using the modulo operator. In this case, 233,674,318 % 10 will yield 8 (% signifies modulo). You can get rid of a number's least significant digit using division. 233,674,318 / 10 will yield 23,367,431 which is like removing the 8 from the number. Using these two operations you can extract all the digits from a number and build a list out of them.

A: Convert to String and take each char to create nodes

A: import java.util.*;
import java.util.stream.*

         LinkedList<Integer> getList(long num){
             String[] arr = String.valueOf(num).split("");
             LinkedList<Integer> list = new LinkedList<>();
             list.addAll(Stream.of(arr)
                     .mapToInt(x->Integer.parseInt(x))
                     .boxed()
                     .collect(Collectors.toList()));
             return list;
         }

This is a method you could use. Ultimately, it is a matter of either using the modulus to get every digit or using a split function on the String value of the long number to be then parsed and stored in a LinkedList of Integers.
If you are trying to save memory, as per your question, using integers for the linkedlist would be better as integers only use 32 bits whereas long uses 64 bits.


text:
Q: What is the best way to add BigDecimals in Hadoop? I need to add BigDecimals in Hadoop. I'm currently using Apache Pig BigDecimalWritable but Pig seems to be completely outdated.
<dependency>
  <groupId>org.apache.pig</groupId>
  <artifactId>pig</artifactId>
  <version>0.17.0</version>
</dependency>

This version is 5 years old!!

A: I now use instead:
<dependency>
  <groupId>org.apache.parquet</groupId>
  <artifactId>parquet-hive-storage-handler</artifactId>
  <version>1.11.2</version>
</dependency>

<dependency>
  <groupId>org.apache.hive</groupId>
  <artifactId>hive-serde</artifactId>
  <version>4.0.0-alpha-1</version>
  <exclusions>
    <exclusion>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Parquet contains a BigDecimalWritable and is more up to date.
Would there be a better solution?


text:
Q: Windows 8.1 VPN Connection Crash I am attempting to connect to a VPN that I have used for quite some time.
I followed these instructions to setup my VPN on both my desktop and my surface pro
Both my desktop and surface pro have all of the current updates for Windows 8.1.
However, my surface pro connects to the VPN without issue and my desktop crashes when I attempt to do ANYTHING VPN related.
If I

*

*Attempt to connect to a VPN it freezes and crashes without error as soon as I hit connect

*Attempt to remove a VPN it freezes and crashes without error as soon as I hit remove

*Attempt to connect to a newly created VPN it freezes and crashes without error as soon as I hit connect

I have tried disabling all Windows Firewall proticols.
I have tried disabling the Windows Defender antimalware shenanigans
I have no other antimalware, virus or firewalls on this machine.
I am at a loss on how to fix this so any insight is appreciated.

A: I know this is a year old, but I wanted to share my experience on solving this problem. Your solution led me in the right direction.
After a little digging around, the root cause was a bunch of WAN Miniport devices in Device Manager not being able to start due to a driver issue (031) I think it was.
So I followed this article:
https://support.microsoft.com/en-us/kb/2871372
Doing the manual steps:

Let me fix it myself
If you have already installed the operating system and are currently
  receiving a "code 31" error on the WAN Miniport (Network Monitor)
  device, follow these steps:

*

*Open Device Manager.

*Right-click the WAN miniport (Network monitor) device, and then click Update Driver Software.

*Click Browse my computer for driver software.

*Click Let me pick from a list of device drivers on my computer.

*Clear the Show compatible hardware check box.

*In the column on the left side, select Microsoft, and in the column on the right side, select Microsoft KM-TEST Loopback Adapter.

*In the Update Driver Warning dialog box, click Yes to continue installing this driver.

*After the driver is installed, right-click the device, and then click Uninstall.

*After the device is uninstalled, right-click the computer name in Device Manager, and then click Scan for hardware changes.

*On the View menu, click Show hidden devices.
The WAN Miniport (Network monitor) device should now be started and no
  longer have a yellow exclamation mark next to it.

Scanning for hardware changes immediately after uninstalling still left me with corrupt / missing driver issues on all my WAN Miniport devices (thus reproducing your exact symptoms, and mine, again - locking up, cant remove VPN, can't view properties without crashing).
So I ran DISM /Online /Cleanup-Image /RestoreHealth from magicandre1981's link and viola, the WAN Miniport devices came back without any errors.
Afterwards I was able to successfully connect to my company's VPN.

A: Try a sfc /scannow. You may have some corrupt files.

A: Windows 8.1 eventually fixed itself via a Windows Update.
Only took a year or so.....


text:
Q: Six Wire Servo with Arduino I have a Tamagawa 200 step servo, 6.4V. I want to test it with my Arduino Uno. My only problem is that it has 6 wires (white, red, black, green, blue and yellow) and I can not find a simple way to test it. My Question is:
How/ What do I use to test it and what are the extra wires for?
I belive it is a presison servo? If that makes sense.

A: Please use Google or some other search engine and use the search string "6 wire stepper motor"
The very first link in the list that pops up is Arduino 6 wire Stepper Motor Tutorial.  There are more than a million other hits with that search string.
The key words in your question that makes it clear that this is a stepper motor rather than a servo is "200 steps".  Servo motors are a continuous device rather than having discrete steps like a stepper does.
Many servo motors also have 5 or 6 wires: 2 wires for the motor and 3 or 4 wires for the potentiometer or quadrature encoder that tells the controller how far the motor has moved.  Servo motors require a completely different and much more complicated driver system than a stepper.  The advantage of servo motors over stepper motors are many: higher resolution, capable of MUCH higher power, easily scaled up or down in size.  All of those advantages are offset by the much more complicated controller required.
But you have a stepper motor.


text:
Q: MAAS based on ubuntu18.04, nodes can not connect to the public network MAAS 2.4 is based on Ubuntu 18.04.

*

*I have both my master and nodes, connect to the public network and private network.

*My router provides DHCP on 172.16.199.0/24 (Public Network, Gateway 172.16.199.1, DNS 192.168.111.90).

*MAAS master provide DHCP on 10.1.1.0/24 (Private Network)

Now, I can commission, deploy Ubuntu 18.04 and SSH to my nodes.
But, my nodes can not automatically connect to the public network, I find that all the requests are directed to the private network (10.1.1.100 is my MAAS master).

I must run this command on my nodes to access to the public network:
sh route add default gw 172.16.199.1

Every time when I reboot my nodes, I have to run that command.

A: What is the gw on your 10.0.0.x network used for?
As declaring a gw on both interface will create 2 routes for 0.0.0.0 on your machines.
Try to remove the gw on the 10.0.0.x network and this should work.
If you need to reach specific network via the 10.0.0.x then create the static routes for them.

A: I have solved that problem by:
    sudo maas login username
    maas username interface set-default-gateway nodeID TheInterfaceID


text:
Q: How to retrieve both "associated" records and "associated through" records in a performant way? I am using Ruby on Rails 3.1 and I am trying to improve an SQL query in order to retrieve both "associated" records and "associated through" records (ActiveRecord::Associations) in a performant way so to avoid the "N + 1 query problem". That is, I have:
class Article < ActiveRecord::Base
  has_many :category_relationships

  has_many :categories,
    :through => :category_relationships
end

class Category < ActiveRecord::Base
  has_many :article_relationships

  has_many :articles,
    :through => :article_relationships
end

In a couple of SQL queries (that is, in a "performant way", maybe by using the Ruby on Rails  includes() method) I would like to retrieve both categories and category_relationships, or both articles and article_relationships.
How can I make that?

P.S.: I am improve queries like the followings:
@category = Category.first

articles = @category.articles.where(:user_id => @current_user.id)
articles.each do |article|
  # Note: In this example the 'inspect' method is just a method to "trigger" the
  # "eager loading" functionalities
  article.category_relationships.inspect
end

A: You can do
Article.includes(:category_relationships => :categories).find(1)

Which will reduce this to 3 queries (1 for each table). For performance, also make sure your foreign keys have an index.
But in general, I'm curious why the "category_relationships" entity exists at all, and why this isn't a has_and_belongs_to sort of situation?
Updated
As per your changed question, you can still do
Category.includes(:article_relationships => :articles).first

If you watch the console (or tail log/development) you'll see that when you call the associations, it'll hit the cached values and you're golden.
But I am still curious why you're not using a Has and Belongs To Many association.


text:
Q: .htaccess rewriting $_GET variables I have the following page:
mysite.com/news/index.php?tag=tag&name=name&id=id

I want to rewrite this so that it goes kind of as follows
mysite.com/news/tag/name-id

A full example of this would be.
foobar.com/news/apple/the-new-iphone-5-9001

Also after I rewrite this URL will I still be able to pull data as I would normally for instance:
$_GET['tag'] //would be apple
$_GET['name'] //would be the-new-iphone-5
$_GET['id'] //would be 9001

A: Add this to .htaccess in your web root.
RewriteEngine On
RewriteBase /

RewriteRule ^news/([^/]+)/(.+?)-(\d+)/?$ /news/index.php?tag=$1&name=$2&id=$3