text:
Q: Aceitar centavos no javascript Gostaria que esse codigo pegasse os centavos do valor vindo da variável javascript
preco = parseInt(preco);

ja coloquei assim nada
preco = parseFloat(preco);

Codigo completo abaixo
total = 0;

function adiciona(id) {
    calcula(id, "adicao");
}

function remove(id) {
    calcula(id, "subtracao");
}

function calcula(id, operacao) {
    nomeid = "nome" + id;
    precoid = "preco" + id;
    qtdid = "qtd" + id;
    nome = document.getElementById(nomeid).innerHTML;

    preco = document.getElementById(precoid).innerHTML;
    preco = parseInt(preco);

    qtd = document.getElementById(qtdid).innerHTML;
    qtd = parseInt(qtd);

    //Debug
    //alert("Produto: " + nome + "\n Preço: " + preco);

    if (operacao == "adicao") {
        total = total + preco;
        qtd = qtd + 1;
    } else {
        total = total - preco;
        qtd = qtd - 1;
    }

    document.getElementById(qtdid).innerHTML = qtd;
    document.getElementById("total").innerHTML = total;
}

A: Fala Hemerson,
Tenta o seguinte:
// com preco ainda como string converte vírgula para ponto
preco.replace (", ", ". ");

// depois converte para float
preco = parseFloat(preco);

E no php vai precisar usar number_format para formatar quando quiser exibir float com vírgula como casa decimal.
http://php.net/manual/en/function.number-format.php

A:

 <script>

     total = 0;

        function adiciona(id)
        {
            calcula(id,"adicao");
        }

        function remove(id)
        {
            calcula(id,"subtracao");
        }

        function calcula(id,operacao)
        {
                nomeid  = "nome"+id;
                precoid = "preco"+id;
                qtdid   = "qtd"+id;

                nome  = document.getElementById(nomeid).innerHTML;

                preco = document.getElementById(precoid).innerHTML;
                preco = parseInt(preco);

                qtd   = document.getElementById(qtdid).innerHTML;
                qtd   = parseInt(qtd);

                //Debug
                //alert("Produto: " + nome + "\n Preço: " + preco);

                if(operacao=="adicao")
                {
                    total = total + preco;
                    qtd = qtd + 1;
                }
                else
                {
                    total = total - preco;
                    qtd = qtd - 1;
                }

                document.getElementById(qtdid).innerHTML = qtd;

                document.getElementById("total").innerHTML = total;
        }

    </script>
<script>
   function verifica_e_envia()
   {
    array_dados = new Array();

    colecao = document.getElementsByTagName("tr");

    qtd_blocos = colecao.length - 1; // O último tr da tabela é onde fica o total e está sendo descontado
    // É necessário saber a quantidade de blocos para poder usar em um loop catando os valores

    // Percorre os blocos catando nomes, quantidades e valores dos produtos com quantidade maior que zero
    for(i=1; i<=qtd_blocos ;i++)
    {
     qtdid = "qtd"+i;
     qtd   = document.getElementById(qtdid).innerHTML;
     qtd   = parseInt(qtd);

     if(qtd>0)
     {
      obj_tmp = {};

      nomeid = "nome"+i;
      nome   = document.getElementById(nomeid).innerHTML;

      precoid = "preco"+i;
      preco   = document.getElementById(precoid).innerHTML;
      preco   = parseFloat(preco);

      obj_tmp.nome  = nome;
      obj_tmp.preco = preco;
      obj_tmp.qtd   = qtd;
      obj_tmp.subtotal = qtd*preco;

      // adiciona elemento no array de dados que será enviado
      array_dados.push(obj_tmp);
     }
    }

    // põe o array_dados no input hidden json_dados
    document.getElementById("json_dados").value = JSON.stringify(array_dados);

    // envia o formulário form_pedido_produtos
    document.getElementById("form_pedido_produtos").submit();

   }
  </script>


text:
Q: Realtime scheduling repeated events in nanoseconds I need to create a realtime scheduler in Python that executes a simple function every n nanoseconds.
I tried creating a scheduler via the sched module and giving time.time_ns as timefunction, but I get errors when trying to get a delay function to schedule waits finer than in seconds.
Here is the code I am executing:
import sched
import time

def scheduledPrint():
    print("ScheduledPrinter!")

def run():
    print("Starting")
    # Create an internal scheduler
    scheduler=sched.scheduler(timefunc=time.monotonic_ns, delayfunc=time.sleep)
    exectime=time.time_ns() + 100;
    schedevent=scheduler.enterabs(exectime, 1, 'scheduledPrint')
    scheduler.run();

run()

When I run the code above I get the following error
    delayfunc(time - now)
OverflowError: timestamp too large to convert to C _PyTime_t

What is the finest precision for a Python Scheduler?

A: I believe CPython pytime uses a 64-bit signed integer to store a "time length". The maximum "allowed" number is thus 9223372036.854775.
You can validate this using the following:
import time
time.sleep(9223372036.854775) # this works
time.sleep(9223372036.854775 + 1) # OverflowError (same with adding 0.1, or 0.01, etc)

The latter will result in an OverflowError:
OverflowError: timestamp too large to convert to C _PyTime_t

In your case, time.time_ns() returns a value greater than 9223372036.854775, thus the error.
Regardless, executing events on a nanosecond schedule seems rather ambitious, since the CPU will typically execute the code on a microsecond scale.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Join two tables where all child records of first table match all child records of second table I have four tables: Customer, CustomerCategory, Limit, and LimitCategory. A customer can be in  multiple categories and a limit can also have multiple categories. I need to write a query that will return the customer name and limit amount where ALL the customers categories match ALL the limit categories.
I'm guessing it would be similar to the answer here, but I can't seem to get it right. Thanks!
Edit -  Here's what the tables look like:
tblCustomer
  customerId
  name

tblCustomerCategory
  customerId
  categoryId

tblLimit
  limitId
  limit

tblLimitCategory
  limitId
  categoryId

A: I THINK you're looking for:
SELECT *
FROM CustomerCategory
LEFT OUTER JOIN Customer
    ON CustomerCategory.CustomerId = Customer.Id
INNER JOIN LimitCategory
    ON CustomerCategory.CategoryId = LimitCategory.CategoryId
LEFT OUTER JOIN Limit
    ON Limit.Id = LimitCategory.LimitId

A: Updated!
Thanks to Felix for pointing out a flaw in my existing solution (3 years after I originally posted it, hehe). After looking at it again, I think this might be correct. Here I'm getting (1) the customers and limits with matching categories, plus the number of matching categories, (2) the number of categories per customer, (3) the number of categories per limit, (4) I then ensure the number of categories for customer and limits is the same as the number of the matches between the customers and limits:
UNTESTED!
select
  matches.name,
  matches.limit

from (
    select
      c.name,
      c.customerId,
      l.limit,
      l.limitId,
      count(*) over(partition by cc.customerId, lc.limitId) as matchCount
    from tblCustomer c
    join tblCustomerCategory cc on c.customerId = cc.customerId
    join tblLimitCategory lc on cc.categoryId = lc.categoryId
    join tblLimit l on lc.limitId = l.limitId
) as matches

join (
    select
       cc.customerId,
       count(*) as categoryCount
     from tblCustomerCategory cc
     group by cc.customerId
) as customerCategories
on matches.customerId = customerCategories.customerId

join (
    select
      lc.limitId,
      count(*) as categoryCount
    from tblLimitCategory lc
    group by lc.limitId
) as limitCategories
on matches.limitId = limitCategories.limitId

where matches.matchCount = customerCategories.categoryCount
and matches.matchCount = limitCategories.categoryCount

A: I don't know if this will work or not, just a thought i had and i can't test it, I'm sures theres a nicer way! don't be too harsh :)
  SELECT
   c.customerId
 , l.limitId
FROM
 tblCustomer c
CROSS JOIN
 tblLimit l
WHERE NOT EXISTS
(
 SELECT
  lc.limitId
 FROM
  tblLimitCategory lc
 WHERE
  lc.limitId = l.id
 EXCEPT
 SELECT
  cc.categoryId
 FROM
  tblCustomerCategory cc
 WHERE
  cc.customerId = l.id
)


text:
Q: Determinant of Matrix with each entry being a diagonal matrix Let $\mathbf{I}_n$ be the identity matrix with size $n$ by $n.$
Consider the $n$ by $n$ matrix
$ \mathbf{A} = \begin{pmatrix}
a_{11} & a_{12} & \cdots &a_{1n} \\
a_{21} & a_{22}  &\cdots & a_{2n} \\
 \cdots\\
a_{n1} & a_{n2}  &\cdots & a_{nn}
\end{pmatrix}  $
Define a $n^2$ by $n^2$ matrix as follows:
$ \mathbf{B} = \begin{pmatrix}
a_{11}\mathbf{I}_n & a_{12}\mathbf{I}_n & \cdots &a_{1n}\mathbf{I}_n \\
a_{21}\mathbf{I}_n & a_{22}\mathbf{I}_n  &\cdots & a_{2n}\mathbf{I}_n \\
 \cdots\\
a_{n1}\mathbf{I}_n & a_{n2}\mathbf{I}_n  &\cdots & a_{nn}\mathbf{I}_n
\end{pmatrix}  $
For example when $n = 2,$
$ \mathbf{A} = \begin{pmatrix}
a_{11} & a_{12} \\
a_{21} & a_{22}
\end{pmatrix}  $
and
$ \mathbf{B} = \begin{pmatrix}
a_{11}&0 & a_{12}&0 \\
0&a_{11} & 0 & a_{12}\\
a_{21}&0 & a_{22} &0\\
0&a_{21} & 0& a_{22}
\end{pmatrix}  $
Then, we have $$det(\mathbf{B}) =(a_{11}a_{22}-a_{12}a_{21} )^2=(det(\mathbf{A}))^2$$
The question is that: Do we have that $$det(\mathbf{B}) = (det(\mathbf{A}))^n$$ for any $n = 1, 2, 3, ...$?
I have verified this for $n=2$ and $3$ (of course it trivially holds when $n=1$), but do not have much idea about larger $n.$

A: The answer is yes. One way to see this is as a consequence of the properties of the Kronecker product. The matrix $B$ can be written in the form $B = A \otimes I_n$. From the properties of the Kronecker product, we have
$$
\det(A \otimes I_n) = \det(A)^n \cdot \det(I_n)^{n} = \det(A)^n \cdot 1.
$$
Alternatively, a direct approach is to note that there exists a Permutation matrix $P$ such that $P^TBP$ is the block-diagonal matrix
$$
P^TBP = \pmatrix{A\\ & \ddots \\&& A}.
$$
From there, note that the determinant of a block-diagonal matrix is the product of the determinants of its blocks, which is to say that
$$
\det(B) = \det(P^TBP) = \det(A) \cdots \det(A) = \det(A)^n.
$$


text:
Q: Is it possible to modify the Chrome or Firefox developer tools network page? Both Chrome and Firefox provide "Network" pages in their DevTools, which are very useful. I'm working with software which adds headers to HTTP responses to communicate performance information. I would like to be able to see this information at-a-glance in the Network panel, but looking at the relevant Chrome and MDN docs, I can't see any way to modify existing DevTools panels.
Is it possible to do this? If so, how?

A: Both Google Chrome and Firefox allow you to modify the shown columns and to show specific header values. It seems however that only in Chrome you can also add custom headers.
To do so, open the Network tab in the Dev Tools and make sure there is at least one entry in the list. Then right click on one of the table headers (like Name, Path, Method, etc.) to open the context menu that allows you to select which columns you want to show. From this context menu go to "Response Headers" -> "Manage Header Columns...". Then in the modal that pops up click "Add custom header..." and enter the name of the header you want to show. Click "Add" and it should now be part of the overview table.
In Firefox it works the same, but you can only select one of the predefined headers.


text:
Q: Change Default Pie Chart Color in Apex? I'm wondering is there a way to change the default pie-chart colors? the default random colors does not work in my scenario and we have our own set of colors like to implement in the pie-chart.
Here is my current code looks like:
<apex:pageBlockSectionItem >
   <apex:chart height="300" width="500" data="{!PieChartData}">
     <apex:pieSeries labelField="Colorpicker__c" dataField="data">
        <apex:chartLabel display="rotate" field="Colorpicker__c"/>
      </apex:pieSeries>
        <apex:legend position="right"/>
    </apex:chart>
</apex:pageBlockSectionItem>

A: You can use colorset attribute documented here to provide custom colors
<apex:pageBlockSection title="Simple colorSet Demo">
<apex:chart data="{!pieData}" height="300" width="400" background="#F5F5F5">
    <apex:legend position="left"/>
    <apex:pieSeries labelField="name" dataField="data1"
        colorSet="#37241E,#94B3C8,#4D4E24,#BD8025,#816A4A,#F0E68C"/>
</apex:chart>

A colorSet is a string that is a comma-delimited list of HTML-style hexadecimal color definitions. For example, colorSet="#0A224E,#BF381A,#A0D8F1,#E9AF32,#E07628". Colors are used in sequence. When the end of the list is reached, the sequence starts over at the beginning


text:
Q: update record, or delete and re-insert if the user edits their cart before processing the order I have a table named orders_products which hold all the products associated with each individual orders. Now, if the customer decides to edit the quantity, the attributes, or simply just remove a product, what would be the easiest way to handle this change in the database?
orders_products
id  |  quantity  |  fk_products_id  |  attributes  |  price  |  fk_orders_nr

fk_products_id refers to the actual product id in our products table
attributes is a comma sepparated string with id's refering to our attributes table (attributes can be the angle, lenght, diameter etc. for each product. As in 45 degres, left angeled, 20 cm in length, 43mm in diameter).
fk_orders_nr is the actual order the product belongs to.
Since I have a class that handles this part on the client side. Would it be easier to just DELETE all associated products, based on the order id (fk_orders_nr), and just re-insert and updated the whole set based on what's stored in the class?
Or is there a neat way to handle this directly in MySQL?
I've looked a bit into on duplicate key update, and ignore, but they doesn't seem to fit my needs..
I need to check to see if the actual product id exists, then decide to insert new, or update existing (it could be both the quantity, and/or optional attributes), also the product might be removed if not in the list from the class anymore.
When writing this question. I think deleting the whole set, and reinsert it, might be the easiest way.

A: This database looks badly designed. Firstly I assume by fk_products_id you mean product_id. You do not need to specify that a column is a foreign key in its name.
Secondly, I would advise you to keep all columns atomic, as in, no multi-values. The attributes column keeping a comma-separated list will give you headaches in the future and it also breaks the FIRST normal form (the most basic one).
Thirdly, you don't need (although it could sometimes be useful) an id as a primary key in your junction table. You can just use a compound primary key from your fk_products_id and fk_orders_nr keys.

When writing this question. I think deleting the whole set, and
  reinsert it, might be the easiest way.

Yes, that is the way it's usually done.
But I insist you ignore everything about the current problem you're having and redesign your database from scratch, putting special attention into normalization. These are basic database design standards and they exist for a reason. Hopefully you won't learn about the reason when it's too late.


text:
Q: QT Future Watcher With mail Client Hi I am using the code from here https://github.com/xcoder123/SimpleSmtp_SSL_QT5/tree/master/smtp_attachements to send mail from my qt application and it's work fine, but when I use future wacht to run the mail sender in another thread it does'nt work
QFuture<void> f4 = QtConcurrent::run(this,&MainWindow::sendMail); // this doesnot work
//sendMail(); //this work

Here is the mainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QSettings"
#include "QFuture"
#include "QtConcurrent/QtConcurrent"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(ui->sendBtn, SIGNAL(clicked()),this, SLOT(test()));
    connect(ui->exitBtn, SIGNAL(clicked()),this, SLOT(close()));
    connect(ui->browseBtn, SIGNAL(clicked()), this, SLOT(browse()));
}

void MainWindow::browse()
{
    files.clear();

    QFileDialog dialog(this);
    dialog.setDirectory(QDir::homePath());
    dialog.setFileMode(QFileDialog::ExistingFiles);

    if (dialog.exec())
        files = dialog.selectedFiles();

    QString fileListString;
    foreach(QString file, files)
        fileListString.append( "\"" + QFileInfo(file).fileName() + "\" " );

    ui->file->setText( fileListString );

}
void MainWindow::test(){

    QFuture<void> f4 = QtConcurrent::run(this,&MainWindow::sendMail);
    //sendMail();
}

void MainWindow::sendMail()
{
    Smtp* smtp = new Smtp(ui->uname->text(), ui->paswd->text(), ui->server->text(), ui->port->text().toInt());
    connect(smtp, SIGNAL(status(QString)), this, SLOT(mailSent(QString)));

    if( !files.isEmpty() )
        smtp->sendMail(ui->uname->text(), ui->rcpt->text() , ui->subject->text(),ui->msg->toPlainText(), files );
    else
        smtp->sendMail(ui->uname->text(), ui->rcpt->text() , ui->subject->text(),ui->msg->toPlainText());
}

void MainWindow::mailSent(QString status)
{
    if(status == "Message sent")
        QMessageBox::warning( 0, tr( "Qt Simple SMTP client" ), tr( "Message sent!\n\n" ) );
}

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

and mainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "smtp.h"
#include <QtWidgets/QMessageBox>
#include <QFileDialog>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private slots:
    void sendMail();
    void mailSent(QString);
    void browse();
    void test();

private:
    Ui::MainWindow *ui;
    QStringList files;

};

#endif // MAINWINDOW_H

The smtp class is as shown here, I haven't touch anything
https://github.com/xcoder123/SimpleSmtp_SSL_QT5/blob/master/smtp_attachements/smtp.h
https://github.com/xcoder123/SimpleSmtp_SSL_QT5/blob/master/smtp_attachements/smtp.cpp
Any one know why it's not working when running in a thread using future watcher.
Thanks
Haris

A: The problem is that QtConcurrent::run just runs a single function, in your case sendMail, in a separate thread. As soon as this function returns, the thread is not active anymore and the slots in Smtp will not be called.
Either change your function sendMail to not return until the mail is sent or use a QThread and move Smtp* stmp to it using QObject::moveToThread.


text:
Q: connect groups of marker by polyline I have two groups of markers: pos and dax?
is it possible to connect markers in two groups using google's function Polyline ?
First group : pos1, pos2, pos3, pos4.
Second gropup: dax1, dax2.
The markers on the page are refreshing per 10sec.
I will be very grateful  for any help.
<!DOCTYPE html>

        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

link to jsfiddle example

A: Yes, it is possible.
code snippet:

var centerLat;
var centerLng;
var mapOfSalons;
var markers = [];
var polly = new google.maps.Polyline({
  strokeColor: '#000000',
  strokeOpacity: 1.0,
  strokeWeight: 3
});

var polly2 = new google.maps.Polyline({
  strokeColor: '#FF00CC',
  strokeOpacity: 1.0,
  strokeWeight: 3
});

function ajax() {
  var ajaxArray = [];
  ajaxArray[0] = {
    "lat": "50.22",
    "lng": "19.22",
    "text": "pos1"
  };
  ajaxArray[1] = {
    "lat": "49.00",
    "lng": "19.88",
    "text": "pos2"
  };
  ajaxArray[2] = {
    "lat": "49.40",
    "lng": "21.22",
    "text": "pos3"
  };
  ajaxArray[3] = {
    "lat": "49.90",
    "lng": "21.66",
    "text": "pos4"
  };

  ajaxArray[0].lat = Math.random() * 49;
  ajaxArray[2].lat = Math.random() * 49;

  return ajaxArray;
}

function ajax2() {
  var ajaxArray2 = [];
  ajaxArray2[0] = {
    "lat": "20.22",
    "lng": "19.22",
    "text": "dax1"
  };
  ajaxArray2[1] = {
    "lat": "20.00",
    "lng": "24.88",
    "text": "dax2"
  };

  ajaxArray2[0].lat = Math.random() * 20;
  return ajaxArray2;
}

$(document).ready(function() {
  onStart();
});

function clearOverlays() {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(null);
  }
  marker = [];
}

function onStart() {
  centerLat = 20.22;
  centerLng = 21.22;

  var mapProp = {
    center: new google.maps.LatLng(centerLat, centerLng),
    zoom: 3,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  mapOfSalons = new google.maps.Map(document.getElementById("googleMap"), mapProp);
  initialize();
}

function drwaUserRoad(poly, data, color) {
  if (poly && poly.setMap) {
    poly.setMap(null);
    poly.setPath([]);
  } else {
    poly = new google.maps.Polyline({
      strokeColor: color,
      strokeOpacity: 1.0,
      strokeWeight: 3
    });
  }
  var path = [];
  for (i = 0; i < data.length; ++i) {
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(data[i].lat, data[i].lng),
      map: mapOfSalons,
      title: data[i].text
    });
    path.push(marker.getPosition());
    markers.push(marker);
  }
  poly.setPath(path);
  poly.setMap(mapOfSalons);
}

function initialize() {
  clearOverlays();
  var data = ajax();
  var data2 = ajax2();
  drwaUserRoad(polly, data, '#000000');
  drwaUserRoad(polly2, data2, '#FF00CC');
  setTimeout(initialize, 10000);
}

updated fiddle


text:
Q: how to create a mutlilingual route in Zend Framework? I need a route in Zend Framework that maps the following uri's to EventController > indexAction.
:lang/programma/:name/:page
:lang/programme/:name/:page
:lang/event/:name/:page

The second parameter has to be "programma" OR "programme" OR "event".
 I could simply create 3 different routes for this but I think it is possible to do this in just one.
Any idea how to achieve this?

A: Use Zend_Translate and Zend_Controller_Router_Route::setDefaultTranslator(). A detailed description can be found in the Documentation.


text:
Q: Data Manipulation, Looping to add columns I have asked this question a couple times without any help.  I have since improved the code so I am hoping somebody has some ideas!  I have a dataset full of 0's and 1's.  I simply want to add the 10 columns together resulting in 1 column with 3835 rows.  This is my code thus far:
# select for valid IDs
data = history[history$studyid %in% valid$studyid,]

sibling = data[,c('b16aa','b16ba','b16ca','b16da','b16ea','b16fa','b16ga','b16ha','b16ia','b16ja')]

# replace all NA values by 0
 sibling[is.na(sibling)] <- 0

# loop over all columns and count the number of 174
apply(sibling, 2, function(x) sum(x==174))

The problem is this code adds together all the rows, I want to add together all the columns so I would result with 1 column.  This is the answer I am now getting which is wrong:
b16aa b16ba b16ca b16da b16ea b16fa b16ga b16ha b16ia b16ja
   68    36    22    18     9     5     6     5     4     1

A: In apply() you have the MARGIN set to 2, which is columns.  Set the MARGIN argument to 1, so that your function, sum, will be applied across rows.  This was mentioned by @sgibb.
If that doesn't work (can't reproduce example), you could try first converting the elements of the matrix to integers X2 <- apply(sibling, c(1,2), function(x) x==174), and then use rowSums to add up the columns in each row: Xsum <- rowSums(X2, na.rm=TRUE).  With this setup you do not need to first change the NA's to 0's, as you can just handle the NA's with the na.rm argument in rowSums()


text:
Q: Threejs skybox out of range I am writing a 3d game in javascript with threejs. I made a skybox, and it works, but if I make my cameras near and far distances too small it doesn't show.
I understand why this happens, the camera attached to my player doesn't see as far as the skybox. If I make my cameras "near" and "far" attributes large enough (corresponding to the size of my game map) I can make it so that my skybox is always within range, but I don't want that, since I don't want the camera to see all the objects that far away.
Any ideas of how to force the camera to see the skybox but still have a small "far" attribute so as to no see all the objects in the world?
Any help would be greatly appreciated.

A: There's scene.background, which can be set to a CubeTexture.

A: Just want to add an example, because someone might find it useful here:
var loader = new THREE.CubeTextureLoader();
    loader.load([
        './img/sky/galaxy-X.jpg', './img/sky/galaxy+X.jpg',
        './img/sky/galaxy-Y.jpg', './img/sky/galaxy+Y.jpg',
        './img/sky/galaxy-Z.jpg', './img/sky/galaxy+Z.jpg'
    ]  , function(texture)
    {
        scene.background = texture;
    });


text:
Q: Unable to restore a deleted app from App Store Connect I had deleted an app for our beta bundle ID from App Store Connect a few months ago. Now I am trying to restore it. But I am getting the following error.

Can anyone help me in understanding this or let me know how to restore it back?
Because I really don't want to create a new beta bundle ID now.
I don't know if this is helpful, but here's the API response when the restore call is made:
{
  "errors" : [ {
    "id" : "35b33baf-xxxx",
    "status" : "409",
    "code" : "ENTITY_ERROR.ATTRIBUTE.INVALID.INVALID_STATE",
    "title" : "An attribute value is not acceptable for the current resource state.",
    "source" : {
      "pointer" : "removed"
    }
  } ]
}

Thanks a lot.

A: You want to contact Apple Developer Support in order to get the issue resolved. They can help you getting the right attribute's value changed.


text:
Q: Import Novels/Non-Fiction from txt Files I study literature and am trying to work out how I would go about importing a series of novels from .txt or other formats into python to play around with different word frequencies, similarities, etc. I hope to try and establish some quantitative ways to define a genre beyond just subject matter.
I particularly want to see if certain word strings, concepts, and locations occur in each of these novels. Something like this: (http://web.uvic.ca/~mvp1922/modmac/).  I would then like to focus in on one novel, using the past data as comparison and also analyzing it separately for character movement and interactions with other characters.
I am very sorry if this is vague, unclear, or just a stupid question. I am just starting out.

A: Welcome to StackOverflow!
This is a really, really big topic.  If you're just getting started, I would recommend this book, which walks you through some of the basics of NLP using Python's nltk library.  (If you're already experienced with Python and just not NLP, some parts of the book will be a bit elementary.)  I've used this book in teaching university-level courses and had a good experience with it.
Once you've got the fundamentals under your belt, it sounds like you basically have a text classification (or possibly clustering) problem.  There are a lot of good tutorials out there on this topic, including many that use Python libraries, such as scikit-learn.  For more efficient Googling, other topics you'll want to explore are "bag of words" (analysis that ignores sentence structure, most likely the approach you'll start with) and "named-entity recognition" (if you want to identify characters, locations, etc.).
For future questions, the best way to get helpful answers on SO is to post specific examples of code that you're struggling with - this is a good resource on how to do that.  Many users will avoid open-ended questions but jump all over puzzles with a clear, specific problem to solve.
Happy learning!


text:
Q: Specify the workbook when working on a worksheet in VBA I would like to get the value of cell. I have multiple workbooks, and some of the workbooks have sheets with the same name.
For example, test.xlsx and test2.xlsx both has a sheet named sheet1.xlsx
So, when working on a sheet, I would like to specify the workbook. I use wb.sh.*expression* all the time, and I am surprised that this does not work.
What am I missing here conceptually?
Code:
set wb1 = Workbooks("Test1.xlsx")
Set sh1 = Worksheets("Sheet1")
Debug.Print wb1.sh1.Range("A1").Value

Code which would work, but is not specific enough:
set wb1 = Workbooks("Test1.xlsx")
Set sh1 = Worksheets("Sheet1")
Debug.Print sh1.Range("A1").Value

Note: Test1.xlsx has a sheet named Sheet1

A: When you open the workbook, the Open method gives you the Workbook object reference - hold on to it instead of discarding it:
Dim wb As Workbook
Set wb = Workbooks.Open(path)

That way you never need to query the Workbooks collection and supply a hard-coded file name to get your workbook.
Next up, the Worksheet reference:
Set sh1 = Worksheets("Sheet1")

The Worksheets collection is a property that belongs to a Workbook object. Indeed, that's not "specific" enough: if you don't qualify the property call, then you're implicitly referring to ActiveWorkbook - which may or may not be the workbook you need to be using.
That's where that wb reference comes into play:
Set sh1 = wb.Worksheets("Sheet1")

Lastly, what you have here:
Debug.Print wb1.sh1.Range("A1").Value

Is not only illegal, it's overkill: sh1 already knows what Workbook object it belongs to - you can get that object reference through sh1.Parent and compare it to the wb reference:
Debug.Assert sh1.Parent Is wb

sh1 is a local variable, not a member of the Workbook interface: that's why you can't do wb1.sh1.

I use wb.sh.expression all the time

If your code ever worked, I guarantee you don't.


text:
Q: Best Way To Load Dynamic CSS and JS With Gutenberg / Wordpress I'm creating a block with Gutenberg and I'm looking for a practical and easy way to load CSS and JS files via Gutenberg at the frontend.
My concern is I need to enqueue multiple JS and CSS files on save (frontend) depending on the options of the block. Say if option1 is enabled, I would like to load js1.js and css1.css, and option2 is enabled, load js2.js file only and so on.
I know that I can merge the js and css files while creating the block, but then the file size grows bigger and bigger, and I don't want to make the user load unnecessary code.
What I did is parsed the content via WP_Block_Parser/gutenberg_parse_blocks inside enqueue_block_assets action but I didn't like this way very much even if it works.
I was going to load the CSS and JS files with javascript but I couldn't pass the plugin URL to the block JS and I'm not even sure if this is a better option.
What do you suggest for better option?
Thank you,


text:
Q: Updating phpMyAdmin to latest 4.2.11 version on MAMP I have downloaded the latest version of MAMP. It includes the latest PHP version but does not include the latest version of phpMyAdmin. Make sense to you?...me neither.
In order to assist me you will need to see the short and seeming easy upgrade instructions. You will find those  here.
I am unable to locate the "appsolute" directory of the "/Library/Application Support/appsolute/MAMP PRO/phpMyAdmin/config.inc.php" path. Can't find it in "MacintoshHD/Library/Application Support" or the "Users/username/Library/Application Support."
The "/Applications/MAMP/bin/phpMyAdmin" path starting at step 5 is no problem but seems like a secondary step required after steps 1 - 4.
Any help would be awesome.

A: Not sure if this will help anyone but it seams the "appsolute" directory only exists if you have MAMP Pro installed and configured. So you can pretty much just follow the instructions to copy the config.inc.php file from MAMP/bin/phpMyAdmin into the downloaded folder of your new phpMyAdmin version and replace your old phpMyAdmin directory with the new one containing the old config.inc.php.


text:
Q: Linear Programming Inventory A company is opening a new franchise and wants to try minimizing their quarterly cost using
linear programming. Each of their workers gets paid 500 per quarter and works 3 contiguous
quarters per year. Additionally, each worker can only make 50 pairs of shoes per quarter. The demand (in pairs of shoes) is 600 for quarter 1, 300 for quarter 2, 800 for quarter 3, and 100 for quarter 4. Pairs of shoes may be put in inventory, but this costs $50 per quarter per pair of shoes, and inventory must be empty at the end of quarter 4.
I've been working on a solution to this but I'm having trouble formulating the three contiguous quarters constraint and any help is appreciated. Here is what I have, with w_i = workers in that quarter and i_i = inventory in quarter i:
minimize value: 500*(w_1 + w_2 + w_3 + w_4) + 50*(i_1 + i_2 + i_3);
CONSTRAINTS
subject to condition_1: 50*w_1 - i_1 = 600;
subject to condition_2: 50*w_2 + i_1 - i_2 = 300;
subject to condition_3: 50*w_3 + i_2 - i_3 = 500;
subject to condition_4: 50*w_4 + i_3 = 100;
subject to condition_9: i_1 >= 0;
subject to condition_10: i_2 >= 0;
subject to condition_11: i_3 >= 0;
subject to condition_12: w_1 >= 0;
subject to condition_13: w_2 >= 0;
subject to condition_14: w_3 >= 0;
subject to condition_15: w_4 >= 0;

A: Redefine the problem introducing the number of workers that start in a certain quarter. They will still be at work and producing shoes in the next two quarters.
So $w'_i$ is the number of workers that start in quarter $i$ and $w_4 = w'_2 + w'_3 + w'_4$ , etc.


text:
Q: How to call a single mail function that will take from,to,content of the mail,subject and data that we want to pass? i am thinking to create a single mail function in Laravel that will take from,from name,to,toname,content of the mail,data that we want to pass to the mail and subject.i want to call this function everytime i need to send a mail by just passing the above mentioned parameters .i want to create the view of the mail dynamically .i just want to call that function everytime is need to send mail.How do i do that by using helper function or by creating a console command.please give some suggestion in Laravel??

A: Yes it can be small nice if you a make a custom class for sending emails from your project and the reuse-ability of the class help you to write less code.
if you want any more suggestion or instance for class let me know please.

A: A more Laravel way of handling this is laravel notifications.
Laravel notifications got a perfect support for mail notifications, where you can do message formatting, customising recipients and templates.

Link to latest documentation cheers :)

A: use Illuminate\Support\Facades\Mail;
// 1- Define your variables
$params = [
    'from'      => 'from@example.com',
    'fromTitle' => 'Example',
    'subject'   => 'subject example',
    'to'        => 'test@gmail.com',
];

$content = [
    'title'   => 'Title',
    'content' => 'lorem ipsuim',
];

// 2- Create a function
public function sendMail(array $params, array $content){
    Mail::send('mails.name_of_blade', $content, function ($message) use ($params) {
        $message->from($params['from'], $params['fromTitle']);
        $message->subject($params['subject']);
        $message->to($params['to']);
    });
    return true;
}

And then create a new blade file and put it in the mails folder under the view folder and choose a name for this file, in this case i use name_of_blade.


text:
Q: What combinations of "swaps" of elements in a list are equivalent? Define a swap-operation $s_{ij}=s_{ji}$ on an $n$-tuple $a_n=(1,2,\dots,n)$ as interchanging the elements in the $i$th and $j$th positions of the tuple.
I would like to find an efficient way to generate all distinct permutations resulting from applying $k<n$ such swaps, i.e., all distinct $S=s_1s_2\cdots s_k$, where the subscripts refers only to the order in which the swaps are applied; any of the swaps $1,\dots,k$ could be any of the possible $s_{ij}$ (but it is perhaps appropriate to exclude the possibility of having two adjacent and identical swaps, since they would just cancel).

Example:
For $n=3$, represent the tuple as a column vector and the swaps by the three $\left(\binom{n}{2}=3\right)$ possible $3\times 3$ matrices:
\begin{align}
s_{12}&=\pmatrix{0 & 1 & 0 \\ 1 & 0 & 0 \\ 0 & 0 & 1}\\
s_{13}&=\pmatrix{0 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 0} \\
s_{23}&=\pmatrix{1 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 1 & 0}
\end{align}
Then we can identify the results of applying $k=2$ such swaps:
\begin{align}
s_{12}s_{13}a_3^T&=\pmatrix{3 & 1 & 2}^T \\
s_{12}s_{23}a_3^T&=\color{red}{\pmatrix{2 & 3 & 1}^T} \\
s_{13}s_{12}a_3^T&=\color{red}{\pmatrix{2 & 3 & 1}^T} \\
s_{13}s_{23}a_3^T&=\color{blue}{\pmatrix{3 & 1 & 2}^T} \\
s_{23}s_{12}a_3^T&=\color{blue}{\pmatrix{3 & 1 & 2}^T} \\
s_{23}s_{13}a_3^T&=\color{blue}{\pmatrix{3 & 1 & 2}^T} \\
\end{align}
Note the duplicates. I would like to avoid calculating these. Could I have known from the start that $\color{red}{s_{12}s_{23}=s_{13}s_{12}}$ and $\color{blue}{s_{13}s_{23}=s_{23}s_{12}=s_{23}s_{13}}$, without actually calculating these?

So far, I've checked the result of all permutations of operations (giving the six scenarios in the example above), and then thrown out the duplicates, but my computer quickly chokes.
Is there a way to go directly to the unique results for a given $n$ and $k$? In my present problem, $n=9,$ but a generalization would be nice.
I'm using Matlab, but pseudo-code or strictly mathematical considerations are both very welcome.
Thank you.

A: One common way to describe a permutation is via its cycle decomposition. A permutation $\sigma$ specified by $\sigma(1)=4$, $\sigma(2)=5$, $\sigma(3)=2$, $\sigma(4)=1$, $\sigma(5)=3)$, $\sigma(6)=6$, $\sigma(7)=7$ can be described by writing down its cycles $$\begin{cases} 1 \xrightarrow{\sigma} 4 \xrightarrow{\sigma} 1\\ 2 \xrightarrow{\sigma} 5 \xrightarrow{\sigma} 3 \xrightarrow{\sigma} 2 \\ 6 \xrightarrow{\sigma} 6 \\ 7 \xrightarrow{\sigma} 7\end{cases}$$ which we usually shorten to $(1\;4)\;(2\;5\;3)\;(6)\;(7)$ or sometimes just $(1\;4)\;(2\;5\;3)$. (But for the purposes of this answer, we'll want to keep track of the length $1$ cycles as well.)
Each permutation has a cycle decomposition that's unique up to rotating a cycle (we can write $(2\;5\;3)$ as $(5\;3\;2)$ and that's still the same) and up to writing the cycles in a different order.
Moreover, knowing the cycle decomposition tells us how many swaps we need to get a given permutation. For example, we get the cycle $(2\;5\;3)$ by applying the swap $(5\;3)$ and then applying the swap $(2\;5)$; in general, we can get $(a_1\;a_2\;\cdots\;a_k)$ by applying $(a_1\;a_2)$ after $(a_2\;a_3)$ after ... after $(a_{k-1}\;a_k)$, which takes $k-1$ swaps.
Counting the $1$-cycles or fixed points, this tells us that we can obtain a permutation with $t$ cycles by doing $n-t$ swaps: If the cycles have length $\ell_1, \ell_2, \dots, \ell_t$, then $$(\ell_1-1) + (\ell_2-1) + \dots + (\ell_t-1) = n-t.$$ We also can't do any better: each swap can reduce the number of cycles by at most $1$, since at best it can combine two cycles into one cycle.
With $k$ swaps, we can get all permutations with $n-k$ cycles; also, all permutations with $n-k+2, n-k+4, \dots$ cycles, since we can insert as many pairs of redundant swaps as we like. Each swap reverses the sign of a permutation, so we can't get permutations with $n-k+1, n-k+3, \dots$ cycles in any way.
So if you want to find all the permutations that can be obtained with $k$ swaps, find all the cycle decompositions that have $t$ cycles, where $t \ge n-k$ and $t \equiv n-k \pmod 2$.

Here's an example. Suppose we have $n=5$ and we allow ourselves $k=2$ swaps. Then we can get permutations with $n-k=3$ cycles, or $5$ cycles. (The $5$ cycle case is when we do the same swap twice, and get back to the identity permutation, which you might not want to count.)
The $3$ cycles have total length $5$, which could be $3+1+1$ or $2+2+1$. We'll handle these cases separately:

*

*If the cycles have lengths $3$, $1$, and $1$, we'll want to choose the $3$ elements of the $3$-cycle (in $\binom{5}{3}=10$ ways) and then choose the ordering on the $3$-cycle (in $(3-1)!$ ways). These are:
$$(1\;2\;3)\;(4)\;(5) \qquad (1\;3\;2)\;(4)\;(5) \\
(1\;2\;4)\;(3)\;(5) \qquad (1\;4\;2)\;(3)\;(5) \\
(1\;2\;5)\;(3)\;(4) \qquad (1\;5\;2)\;(3)\;(4) \\
(1\;3\;4)\;(2)\;(5) \qquad (1\;4\;3)\;(2)\;(5) \\
(1\;3\;5)\;(2)\;(4) \qquad (1\;5\;3)\;(2)\;(4) \\
(1\;4\;5)\;(2)\;(3) \qquad (1\;5\;4)\;(2)\;(3) \\
(2\;3\;4)\;(1)\;(5) \qquad (2\;4\;3)\;(1)\;(5) \\
(2\;3\;5)\;(1)\;(4) \qquad (2\;5\;3)\;(1)\;(4) \\
(2\;4\;5)\;(1)\;(3) \qquad (2\;5\;4)\;(1)\;(3) \\
(3\;4\;5)\;(1)\;(2) \qquad (3\;5\;4)\;(1)\;(2)$$ For each of these, we can represent it as a product of the $s_{ij}$'s by factoring $(i\;j\;k)$ as $s_{ij}s_{jk}$: e.g., $(1\;3\;5)\;(2)\;(4)$ is the product $s_{13} s_{35}$. (That's $s_{13}$ done after $s_{35}$.)

*If the cycles have length $2$, $2$, and $1$, we have $5$ cases on what the odd element out is, and then $3$ ways to pair up the remaining $4$ elements into two cycles:
$$(1\;2)\;(3\;4)\;(5) \qquad (1\;3)\;(2\;4)\;(5) \qquad (1\;4)\;(2\;3)\;(5) \\
(1\;2)\;(3\;5)\;(4) \qquad (1\;3)\;(2\;5)\;(4) \qquad (1\;5)\;(2\;3)\;(4) \\
(1\;2)\;(4\;5)\;(3) \qquad (1\;4)\;(2\;5)\;(3) \qquad (1\;5)\;(2\;4)\;(3) \\
(1\;3)\;(4\;5)\;(2) \qquad (1\;4)\;(3\;5)\;(2) \qquad (1\;5)\;(3\;4)\;(2) \\
(2\;3)\;(4\;5)\;(1) \qquad (2\;4)\;(3\;5)\;(1) \qquad (2\;5)\;(3\;4)\;(1)$$ These are particularly easy to write in terms of $s_{ij}$'s: for example, $(1\;3)\;(4\;5)\;(2)$ is $s_{13} s_{45}$ in any order. (In general, each cycle in the cycle decomposition gives us some swaps, and swaps from different cycles can be interleaved however we like without changing the permutation.)


text:
Q: php - Receive webhook data from hipmob I'm trying to receive a webhook from hipmob (live chat app) that should be triggered at a chat event.
Documentation: https://www.hipmob.com/documentation/chat-events.html
I've been following How to catch the HTTP POST request sent by a Shopify Webhook , and i have to say that i am completly new to this. I tried the solution from the first answer but with no success.
this is what i did:
<?php
$webhookContent = "";

$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
    $webhookContent .= fread($webhook, 4096);
}
fclose($webhook);

$file = 'webhook.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
// Write the contents back to the file
file_put_contents($file, $current);

error_log($webhookContent);
?>

but with no success

A: I was able to solution it with:
   <?php

    $entityBody = file_get_contents('php://input');

    $file = 'webhook.txt';
    // Open the file to get existing content
    $current = file_get_contents($file);
    // Append a new person to the file
    // Write the contents back to the file
    file_put_contents($file, $entityBody);

    error_log($webhookContent);
    ?>


text:
Q: How to include @Html.Actionlink in C# text string? While the @Html.Actionlink() helper is very convenient for building <a> elements in the .cshtml files, is it possible to construct them inside C# strings, such that they are subsequently rendered correctly in the HTML output?
For example, if I assign a string variable a value similar to the following:
Book.ReadMore = "Click @Html.ActionLink(\"this link\", \"About\", \"Home\") to read more.";

And then I try to display it (the literal text plus the link) through my .cshtml page, using code similar to:
<p>@Model.ReadMore</p>

All I get in the browser is the whole string exactly as I typed it, including the @Html... etc:
Click @Html.ActionLink("this link", "About", "Home") to read more.

Now, for proper SoC, I know that it's not the best of practices to have HTML stuff included in C# code, but is it at all possible to get the proper <a> link in this scenario, instead of the string itself?
EDIT: More information - This string is just one item in a collection of about 20-30 strings (displayed using a for loop in the View). Only a small handful of those items need a link (which is different in each case). Since, as mentioned above, I agree that it's obviously not good practice to use Razor/HTML in Model code, I'm trying to get a simple approach (if possible) which would give me the flexibility of building the link somewhere at the right place, while still yielding the maintainability of MVC SoC.
There must be a "right" way of doing this, which is simple yet maintainable.

A: Your model should not contain HTML, that's a view concern and belongs in view code.  Probably you should be using a Razor helper.
In your App_Code folder (create one if you don't have one), add a file, ReadMoreHelpers.cshtml:
@helper ReadMore() {
    <text>Click @Html.ActionLink("this link", "About", "Home") to read more.</text>
}

Then in any view:
@ReadMoreHelpers.ReadMore()

And that will output what you want.  If you insist on putting that property in your view, you could do:
Book.ReadMore = "Click " + @Html.ActionLink("this link", "About", "Home").ToHtmlString() + " to read more.";

Then in your view, make sure you use Raw:
@Html.Raw(Book.ReadMore)

However, I couldn't recommend more strongly that you do not put HTML in your model properties.

A: I don't think so. The Razor view engine will interpret the ActionLink code during run-time while stuffing it as part of a C# string will be interpreted during compile time.


text:
Q: dplyr and previous observations I need to run a bunch of linear models on each unique identifier, but first I need to do a check.  For each unique id and year, I need to check that there are at least 24 months of previous monthly data, but not more than 60 months.  So when I run the regression it should include between 24 - 60 observations of previous month (years) data for each year of each individual.  If there are less than 24 months of data for that year, the year is dropped for that individual, but if there are more than 60, then only the 60 months are used.
Thanks to this (thanks @akrun) post, I was able to setup the linear models for each individual, run them, and then output the beta as the sum of both betas.  The problem is that this only runs the regression on the current year (12 obs) and not the previous 24-60.
Edit : I realized the dput was wrong...sorry
Single cusip dput:
    tdata <- structure(list(cusip = c(101L, 101L, 101L, 101L, 101L, 101L,
101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L,
101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L,
101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L,
101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L, 101L,
101L, 101L, 101L), date = c(19901130L, 19901031L, 19900928L,
19900831L, 19900731L, 19900629L, 19900531L, 19900430L, 19900330L,
19900228L, 19900131L, 19891229L, 19891130L, 19891031L, 19890929L,
19890831L, 19890731L, 19890630L, 19890531L, 19890428L, 19890331L,
19890228L, 19890131L, 19881230L, 19881130L, 19881031L, 19880930L,
19880831L, 19880729L, 19880630L, 19880531L, 19880429L, 19880331L,
19880229L, 19880129L, 19871231L, 19871130L, 19871030L, 19870930L,
19870831L, 19870731L, 19870630L, 19870529L, 19870430L, 19870331L,
19870227L, 19870130L, 19861231L, 19861128L, 19861031L, 19860930L,
19860829L, 19860731L), fyear = c("1990", "1990", "1990", "1990",
"1990", "1990", "1990", "1990", "1990", "1990", "1990", "1989",
"1989", "1989", "1989", "1989", "1989", "1989", "1989", "1989",
"1989", "1989", "1989", "1988", "1988", "1988", "1988", "1988",
"1988", "1988", "1988", "1988", "1988", "1988", "1988", "1987",
"1987", "1987", "1987", "1987", "1987", "1987", "1987", "1987",
"1987", "1987", "1987", "1986", "1986", "1986", "1986", "1986",
"1986"), month = c("11", "10", "09", "08", "07", "06", "05",
"04", "03", "02", "01", "12", "11", "10", "09", "08", "07", "06",
"05", "04", "03", "02", "01", "12", "11", "10", "09", "08", "07",
"06", "05", "04", "03", "02", "01", "12", "11", "10", "09", "08",
"07", "06", "05", "04", "03", "02", "01", "12", "11", "10", "09",
"08", "07"), ret = c("0.117647", "0.030303", "-0.161017", "-0.186207",
"-0.131737", "0.128378", "0.027778", "-0.162791", "0.131579",
"0.178295", "-0.091549", "0.163934", "-0.089552", "0.007519",
"0.117647", "0.155340", "0.211765", "0.024096", "0.338710", "0.377778",
"0.071429", "-0.176471", "0.378378", "-0.026316", "-0.050000",
"-0.047619", "-0.086957", "-0.061224", "0.088889", "-0.062500",
"-0.040000", "-0.056604", "0.081633", "0.042553", "-0.096154",
"0.238095", "-0.263158", "-0.393617", "-0.160714", "0.400000",
"-0.090909", "-0.200000", "-0.098361", "-0.152778", "0.000000",
"0.107692", "0.460674", "-0.101010", "-0.019802", "0.246914",
"-0.052632", "0.179310", "-0.064516"), ewretd = c(0.035468, -0.057155,
-0.080468, -0.108911, -0.025732, 0.005359, 0.045675, -0.028117,
0.021315, 0.015434, -0.046408, -0.012375, -0.0058, -0.049934,
0.005532, 0.018626, 0.031017, -0.007744, 0.025054, 0.029089,
0.01806, 0.002988, 0.062124, 0.018872, -0.036484, -0.011485,
0.016951, -0.025001, 0.000289, 0.047677, -0.017671, 0.014016,
0.03569, 0.060265, 0.077392, 0.026065, -0.05085, -0.272248, -0.015876,
0.014544, 0.035123, 0.021487, 0.000573, -0.017709, 0.036283,
0.074612, 0.117565, -0.034609, -0.006263, 0.023777, -0.059071,
0.023269, -0.073128), lagewretd = c(-0.004526, 0.035468, -0.057155,
-0.080468, -0.108911, -0.025732, 0.005359, 0.045675, -0.028117,
0.021315, 0.015434, -0.046408, -0.012375, -0.0058, -0.049934,
0.005532, 0.018626, 0.031017, -0.007744, 0.025054, 0.029089,
0.01806, 0.002988, 0.062124, 0.018872, -0.036484, -0.011485,
0.016951, -0.025001, 0.000289, 0.047677, -0.017671, 0.014016,
0.03569, 0.060265, 0.077392, 0.026065, -0.05085, -0.272248, -0.015876,
0.014544, 0.035123, 0.021487, 0.000573, -0.017709, 0.036283,
0.074612, 0.117565, -0.034609, -0.006263, 0.023777, -0.059071,
0.023269)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-53L), .Names = c("cusip", "date", "fyear", "month", "ret", "ewretd",
"lagewretd"))

dplyr code :
res1 <- tdata %>%
  group_by(cusip, fyear) %>%
  arrange(desc(date)) %>%
  mutate(n=n()) %>%
  do(data.frame(., beta=ifelse(.$n > 2,
   sum(coef(lm(ret~ewretd+lagewretd, data=.))[-1]), NA)))

Update 2 : 04/13/2015
Here is a for loop that I could think of that would solve the problem, but again, for loops in R are not the most efficient solution.
for (i : unique(cusip)){
  for (j : unique(fyear)){
    check <- filter(tdata, fyear == i & fyear == i-1 & fyear == i-2 & fyear == i-3 & fyear == i-4)
    ifelse(length(check$month < 24), tdata$beta == NA, if(length(check$month >= 60)){
                                                         arrange(check, desc(date)),
                                                         filter(check, month[1:60,]),
                                                         check$beta <- sum(coef(lm(ret~ewretd+lagewretd, data = check))[-1])),
                                                         left_join(tdata, check, by=c("cusip", fyear == j))}

Update 3 : Full sample set
This includes all obs, which is fairly large (323mb)
Full Sample

A: In the long run, you probably want to use proper dates. I've made a small step in that direction by converting fyear from character to integer.
library(dplyr)

## convert fyear to a proper number and then exploit for sorting
tdata <- tdata %>%
  mutate(fyear = fyear %>% as.integer) %>%
  arrange(fyear, month)

Then I make a tbl summarized at the level of fyear, computing how many cumulative months of data you would have available for fitting a model. (I'm dragging cusip around but since your data only includes one cusip, I can't be sure that this is all working correctly.)
## figure out cumulative months available for each year (for each cusip)
yearstuff <- tdata %>%
  group_by(cusip, fyear) %>%
  summarize(n = n()) %>%
  mutate(n_cum = cumsum(n))
yearstuff
# Source: local data frame [5 x 4]
# Groups: cusip
#
#   cusip fyear  n n_cum
# 1   101  1986  6     6
# 2   101  1987 12    18
# 3   101  1988 12    30
# 4   101  1989 12    42
# 5   101  1990 11    53

I don't find the model fitting to be a very natural task for dplyr, since it doesn't fit nicely into the group_by paradigm. Instead I drive things off of yearstuff, using plyr::ddply(), and pull the data I need for each cusip * fyear combination. I decline to fit a model if there is not enough data and if there is too much data, I only take the most recent 60 months.
## iterate over rows of yearstuff (for each cusip)
models <- plyr::ddply(yearstuff, ~ cusip + fyear, function(y) {
  if(y$n_cum < 24) {
    c('(Intercept)' = NA_real_, ewretd = NA_real_, lagewretd = NA_real_)
  } else {
    my_dat <- tdata %>%
      filter(cusip == y$cusip, fyear <= y$fyear) %>%
      mutate(rn = row_number(desc(date)))
    lm(ret ~ ewretd + lagewretd, my_dat, subset = rn < 61) %>% coef
  }
})
models
#   cusip fyear (Intercept)   ewretd  lagewretd
# 1   101  1986          NA       NA         NA
# 2   101  1987          NA       NA         NA
# 3   101  1988 -0.01138861 1.614342 0.14885911
# 4   101  1989  0.02467139 1.878295 0.00598857
# 5   101  1990  0.02529068 1.900389 0.05766020

This leaves you with the estimated coefficients to use as you wish. I think this should scale to multiple cusips but who knows?. Also this dataset doesn't contain more than 60 months. You should obviously do some spot checks of these results "by hand"!


text:
Q: xmlnodelist to dropdown I am trying to generate a list(of string) to use as a datasource for a dropdown list.
I have done this numerous times but this version is not separating the items out as it normally does.
Here is an xml sample
<fueltypes>
<fuel>
  <type>Marine Diesel NY Harbor</type>
  <dbheader>NYMarineDiesel</dbheader>
</fuel>
<fuel>
  <type>ULSD NY Harbor</type>
  <dbheader>NYULSD</dbheader>
</fuel>
</fueltypes>

Here is the function
Public Shared Function GetFuelTypes(ddlControl As Control) As List(Of String)
    Dim doc As New XmlDocument()

    'Load XML from the file into XmlDocument object
    doc.Load("H:\OtherDataFiles\dataXML.xml") 'this needs to be changed to the server path
    Dim root As XmlNode = doc.DocumentElement

    'Select all nodes with the tag paramter indicated by the nodestring variable
    Dim nodeList As XmlNodeList = root.SelectNodes("fueltypes")
    Return (From node As XmlNode In nodeList Select node.InnerText).ToList()
End Function

They get bound to the dropdown as follows
 'load the fuel types into the dropdownlist
    ddlFuelTypes.DataSource = GetFuelTypes()
    ddlFuelTypes.DataBind()
    ddlFuelTypes.SelectedIndex = 1

The dropdown displays all the items in one line

A: You need to either fully qualify nodeList, so that you get to the sub-elements that contain the text you want, e.g.
Dim nodeList As XmlNodeList = root.SelectNodes("/fueltypes/fuel/type")

Or, you need to loop through nodeList and read the elements you need, e.g.
Dim nodeList As XmlNodeList = root.SelectNodes("/fueltypes/fuel")

For Each fuelNode In nodeList
    Dim fuelType = fuelNode.ChildNodes.Item(0).InnerText


text:
Q: Sails.js: how to use i18n function in assets/js/files.js I need use i18n() in my code inside of assets/js of my sailsjs project. How can i to do it?
In my views is ok but in my js not, why?
thanks you very much.
I have sailsjs@0.10.5

A: What I do, is download the translations from the server and use them client side. I never hardcode translations in my assets and I wouldn't if I were you either.
Add a route to fetch your translations (static json) and parse the JSON client side. There are plenty of libraries that can help you from there.
Keep in mind that it's always possible to include translations in a build for something like require.js.

A: I agree with Wesley, but if you don't want all of the translations client side. I would suggest writing an Ajax call and make use of the following:
sails.__({
  phrase: 'Good day',
  locale: 'de'
});

This should then be returned as the German version of 'Good day'. Or you can just send the key phrase and return all your language translations of that.


text:
Q: Is it possible to unit test View's in CodeIgniter? I'm using TOAST and it's doing a great job testing models... but what about views?

A: If you want to do testing of views, you should concider Unit Testing. PHPUnit is a great one and has a bridge for codeigniter!
http://www.knollet.com/foostack/

A: By default there's no possibility to perform unit testing on your views. Codeigniter does has basic unit testing support but in my opinion it lacks many features found in other frameworks (e.g. Rails).
While there are several projects that could solve the problem I doubt they'll work with CI out of the box. As stated by Kieran Andrews you could give PHPUnit a try.

A: I wrote an article about testing "views" in Codeigniter with Selenium:
http://taiar.github.io/php/2014/04/21/acceptance-tests-on-codeigniter-with-phpunit-and-selenium/

A: I would look in to Selenium RC (http://seleniumhq.org/projects/remote-control/) for view testing. It doesn't directly integrate with CodeIgniter. PHPUnit has built in support for it so you may be able to take the driver from there to get it working.

A: Most likely you don't need to unit test your Views.
If you've got code in your Views that needs unit testing, most likely that code belongs in a related controller/library/etc. Views should mainly just display data it receives from the controller; check for valid data and errors before it gets to the View.
See related post: Unit Testing CodeIgniter with Simpletest


text:
Q: Increase any position fixed How can I use javascript to increase every single position:fixed in a page by a number of pixels?
For example:  I have a webpage with several fixed position elements and I insert a toolbar at the top using javascript.  Now that the toolbar takes up 40px of space, all the fixed elements are positioned 40px off.
I need some javascript that I can fire at the same time as introducing the toolbar that will increase all the position fixed by 40px.

A: You can set the top or the bottom CSS properties of your elements by modifying the style attributes in JS.

A: I would imagine you'd have to do something like this:
var elems = document.all || document.getElementsByTagName("*");
// I know document.all isn't ideal, but it saves a function call if it's there ;)
var l = elems.length, i, stl;
window.getComputedStyle = window.getComputedStyle || function(e) {return e.currentStyle};
for( i=0; i<l; i++) {
  stl = window.getComputedStyle(elems[i]);
  if( stl.position === "fixed") {
    elems[i].style.marginTop = ((parseInt(stl.marginTop,10) || 0) + 40) + "px";
  }
}

The use of margin-top as opposed to top is to allow for things like top:50%. Of course, margin-top can be a percentage too, which would be a problem, but it's less frequent.

A: You can give a common class to each fixed element and then target all of those:
<div class="fixed">
    some fixed element
</div>

js (jquery method):
$('.fixed').each(function(){
    $(this).css('top', $(this).css('top') + 40 + 'px');
});

if not using jquery see aurel's answer


text:
Q: How to convert slice to fixed size array? I want to convert a fixed size array from a slice:
func gen(bricks []Brick) {
    if len(bricks) == 16 {
        if check(Sculpture{bricks}) {
            var b [16]Brick = bricks[0:16];
        }
     }
}

But this results in:
 cannot use bricks[0:16] (type []Brick) as type [16]Brick in assignment

How to convert a slice into a fixed size array?

A: I found a way to solve the problem without allocating any more space - to define a new struct with the same construction as slice and receive the unsafe.Pointer.
type MySlice struct {
    Array unsafe.Pointer
    cap   int
    len   int
}
func main(){
    a := []byte{1, 2, 3, 4}
    fmt.Printf("a before %v, %p\n", a, &a)
    b := (*MySlice)(unsafe.Pointer(&a))
    c := (*[4]byte)(b.Array)
    fmt.Printf("c before %v, %T, %p\n", *c, *c, c)
    a[1] = 5
    fmt.Printf("c after %v, %p\n", *c, c)
    fmt.Printf("a after %v, %p\n", a, &a)
}

the result shows as follows:

A: Edit: as of Go 1.17+, you may be able to use new support for slice-to-array conversions, https://tip.golang.org/ref/spec#Conversions_from_slice_to_array_pointer:
s := make([]byte, 2, 4)
s0 := (*[0]byte)(s)      // s0 != nil
s1 := (*[1]byte)(s[1:])  // &s1[0] == &s[1]
s2 := (*[2]byte)(s)      // &s2[0] == &s[0]
s4 := (*[4]byte)(s)      // panics: len([4]byte) > len(s)

Previous answer for Go 1.16 and below:
You need to use copy:
slice := []byte("abcdefgh")

var arr [4]byte

copy(arr[:], slice[:4])

fmt.Println(arr)

As Aedolon notes you can also just use
copy(arr[:], slice)

as copy will always only copy the minimum of len(src) and len(dst) bytes.


text:
Q: Copy array into another array in PHP I am trying to copy array into another array in PHP. Then send the response as JSON output. But it copies only the last element in array multiple times. Please let me know where I am going wrong? Any help is appreciated
PHP code
stmt_bind_assoc($stmt, $resultrow);
while ($stmt->fetch()) {
    $r[] = $resultrow;
    print_r($resultrow);
}
echo json_encode($r);

Output from print_r($resultrow).This is correct. Values in array is different
Array( [a_id] => 1 [b_number] => 10101010 [dateandtime] => 2013-12-25 09:30:00 )
Array( [a_id] => 1 [b_number] => 20202020 [dateandtime] => 2013-12-27 11:40:00 )

Output from json_encode($r).This is incorrect. Values in array is same
[{"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"},
 {"a_id":1,"b_number":20202020,"dateandtime":"2013-12-27 11:40:00"}]

A: You got the function stmt_bind_assoc from here: http://www.php.net/manual/en/mysqli-stmt.fetch.php#82742
Posted under that OP is:

"...the problem is that the $row returned is reference and not data.
  So, when you write  $array[] = $row, the $array will be filled up with
  the last element of the dataset."

With that user's solution I came up with this to resolve your issue:
// replace your posted code with the following

$r = array();

// loop through all result rows
while ( $stmt->fetch() ) {

    $resultrow = array();

    foreach( $row as $key=>$value )
        $resultrow[ $key ] = $value;

    $r[] = $resultrow;

    print_r($resultrow);
}

echo json_encode($r);

Next time you get code from a source read the comments about the source.


text:
Q: Android: How do I bind each value of an ArrayList to a variable? I have an ArrayList that holds ImageViews:
ArrayList<ImageView> ivArray = new ArrayList<ImageView>();
imgView1 = (ImageView) findViewById(R.id.imgView1);
imgView2 = (ImageView) findViewById(R.id.imgView2);
ivArray.add(imgView1);
ivArray.add(imgView2);

I pass this ArrayList to my custom class so it can access each ImageView passed in.
CustomClass cClass = new CustomClass(ivArray);

How can I get each value from the passed in ArrayList in my custom class, and bind them to their own variable?
I was thinking something along the lines of using a foreach loop, like:
public class CustomClass() {
    public CustomClass(ArrayList<ImageView> ivArray) {
        for (ImageView iView : ivArray) {
            // Bind each ImageView
        }
    }
}

A: Use a HashMap
 public class CustomClass{
        //Bind it to a string just for example
        private HashMap<String, ImageView> mMap = new HashMap<String, ImageView>();
        public CustomClass(ArrayList<ImageView> ivArray) {
            for (ImageView iView : ivArray) {
                mMap.put("SomeValue", iView);
            }
        }
        public ImageView getImageViewByString(String s){
            return mMap.get(s);
        }
    }


text:
Q: aws athena SQL query; get unique count of column2 for each unique column1 I am fairly new to SQL queries, and am working with querying an aws athena database.
My first query will return every unique brand given some parameters:
-- query1
SELECT DISTINCT brand
FROM "database"
WHERE product_gap = 'yes' AND store_name = 'petco'

Returning a list like this:
#   brand
1   Drs. Doink and Foink
2   Zkukit!
3   Willow
4   Freshz
5   Aquatic Land
6   UniLaws
7   Seraz
.....

And so on and so on for 553 rows.
If I pick any of the brands, such as 'Seraz' and run this second query, it will return that distinct count of that brand's 'merch1' column
-- query2
SELECT COUNT (DISTINCT merch1)
FROM "database"
WHERE product_gap = 'yes' AND store_name = 'petco' AND brand='Seraz'

Which returns:
#   _col0
1   2

Where _col0 is the distinct count of merch1 for seraz.
My question is how can I combine my queries, so that for every unique brand result from query1, it runs query2, and presents the unique merch1 count in the table like so:
#   brand                 merch1_distinct_count
1   Drs. Doink and Foink  2
2   Zkukit!               1
3   Willow                1
4   Freshz                1
5   Aquatic Land          1
6   UniLaws               3
7   Seraz                 2
.....

A: use group by with brand column
SELECT brand, COUNT(DISTINCT merch1) merch1_distinct_count
FROM "database"
WHERE product_gap = 'yes' AND store_name = 'petco'
group by brand


text:
Q: How to use multiple decorator to a function and chain them together? How can I make two decorators in Python that would do the following?
@check_zero_error
@check_numerator
def division(a, b):
    return a/b

'check_numerator' will reverse the numbers in case numerator is lesser than denominator.
'check_zero_error' will give check for the zero division error.
The expected output is:
division(1, 2)   # Output : 2.0

division(0, 2)   # Output : "Denominator can't be zero"

division(4, 1)   # Output : 4.0

division(5, 0)   # Output : "Denominator can't be zero"

My code is as below but I am not getting expected results:
def check_zero_error(division_func):
    def inner(a, b):
        if b == 0:
            return "Denominator can't be zero"
        else:
            division_func(a, b)
    return inner

def check_numerator(division_func):
    def inner(a, b):
        if a < b:
            a, b = b, a
        division_func(a, b)
    return inner

@check_zero_error
@check_numerator
def division(a, b):
    return a/b

print(division(1, 2))  # Expected output : 2.0
print(division(0, 2))  # Expected output : "Denominator can't be zero"
print(division(4, 1))  # Expected output : 4.0

A: *

*Your decorators method should return the result of the division
def check_zero_error(division_func):
    def inner(a, b):
        if b == 0:
            return "Denominator can't be zero"
        else:
            return division_func(a, b)
    return inner

def check_numerator(division_func):
    def inner(a, b):
        if a < b:
            a, b = b, a
        return division_func(a, b)
    return inner

*Change the order of decorators, first swap (check_numerator) then if needed, THEN check the denominator with check_zero_error
@check_numerator
@check_zero_error
def division(a, b):
    return a / b

Giving expected
print(division(1, 2))  # actual output : 2.0
print(division(0, 2))  # actual output : "Denominator can't be zero"
print(division(4, 1))  # actual output : 4.0
print(division(5, 0))  # actual output :  "Denominator can't be zero"


text:
Q: Pyspark - Code to calculate file hash/checksum not working I have the below pyspark code to calculate the SHA1 hash of each file in a folder. I'm using spark.sparkContext.binaryFiles to get an RDD of pairs where the key is the file name and the value is a file-like object, on which I'm calculating the hash in a map function rdd.mapValues(map_hash_file). However, I'm getting the below error at the second-last line, which I don't understand - how can this be fixed please? Thanks
Error:
org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 66.0 failed 4 times, most recent failure: Lost task 0.3 in stage 66.0
Code:
#Function to calulcate hash-value/checksum of a file
def map_hash_file(row):
    file_name = row[0]
    file_contents = row[1]
    sha1_hash = hashlib.sha1()
    sha1_hash.update(file_contents.encode('utf-8'))
    return file_name, sha1_hash.hexdigest()

rdd = spark.sparkContext.binaryFiles('/mnt/workspace/Test_Folder', minPartitions=None)

#As a check, print the list of files collected in the RDD
dataColl=rdd.collect()
for row in dataColl:
    print(row[0])

#Apply the function to calcuate hash of each file and store the results
hash_values = rdd.mapValues(map_hash_file)

#Store each file name and it's hash value in a dataframe to later export as a CSV
df = spark.createDataFrame(data=hash_values)
display(df)

A: You will get your expected result if you do the following:

*

*Change file_contents.encode('utf-8') to file_contents. file_contents is already a of type bytes

*Change rdd.mapValues(map_hash_file) to rdd.map(map_hash_file). The function map_hash_file expects a tuple.

Also consider:

*

*Adding an import hashlib

*Not collecting the content of all files to the driver - you risk consuming all the memory at the driver.

With the above changes, your code should look something like this:
import hashlib
#Function to calulcate hash-value/checksum of a file
def map_hash_file(row):
    file_name = row[0]
    file_contents = row[1]
    sha1_hash = hashlib.sha1()
    sha1_hash.update(file_contents)
    return file_name, sha1_hash.hexdigest()

rdd = spark.sparkContext.binaryFiles('/mnt/workspace/Test_Folder', minPartitions=None)

#Apply the function to calcuate hash of each file and store the results
hash_values = rdd.map(map_hash_file)

#Store each file name and it's hash value in a dataframe to later export as a CSV
df = spark.createDataFrame(data=hash_values)
display(df)


text:
Q: is it possible to save data after commit statement in sql If 10 users are working on one table at once (e.g.-A1,A2,A3....,A10). Every one is performing DML operation on same table  parallel (i.e. insert,update and delete). If user A1 commit the transaction when others are performing operations. is possible to save all's transaction operations.(Yes/No)
If Yes then why?
If No the Why?

A: No. Transactions are isolated as per ACID.
If a user A1 creates a transaction, then only he can commit it. This will make either all or none of his changes visible to other users. Depending on the isolation level of the transactions, other users will see committed changes by other users only after their own active transaction is committed (see phantom/dirty/non-repeatable reads).
Imagine this:
I'm in the middle of changing something in the database. For example, I'm deleting an object which user A1 has changed. If his commit commits my transaction, too, what should happen? Should he get an error because the object has/will vanish? Or should I get an error because the object was modified by another user?
There is no simple way to resolve these conflicts.
Cloud databases solve it by keeping a history of all objects. So when user A1 changes an object and I delete it, the DB will record the two changes but keep the object around. I can move in time to see A1's change and I can also see my "deletion".
Another point: You could write a server which synchronizes the changes made by all users. So there would always be only a single transaction open. If two users change the same objects, how do you resolve the conflicts?
Or you could write a server which keeps track of all transactions and commits them all at one, how do you make sure that half-valid objects are written to the database (like orders without items, invoices without totals, customers without addresses)?

A: I'm not sure I understand the question.
Are all the users operating on the same row of the table?  Or are they operating on different rows?  If they are operating on the same row, the sessions will necessarily lock each other-- only one session can update a row-- the other sessions would need to wait for the lock to be released when the transaction committed.  If they are operating on different rows, then User A's transaction will have no impact on User B-- it's not obvious to me what "transaction operations" you would want to save in that case or where you would want to save that information.

A: I'm guessing what you want is a history of the changes? In which case you can use either your own triggers to capture the changes or Total Recall in Oracle 11g.


text:
Q: Android, view Holder does not update listview correctly I'm reading data into my listview from a database and i can see the information in the listview, the data in each row is split into left and right. When i scroll in the listview the items are not uppdating correctly. Some items in the right side off the listview are moving to the left side and the other way around.
I can make this problem go away by setting convertView = null directly under the getView() which is a very bad solution! How to solve the problem properly?
Code links:
Xml "http://pastebin.com/rCbeBS6E"
ChatFragment "http://pastebin.com/xMFCm62s"
public class ChatAdapter extends ArrayAdapter<Message> {

private ArrayList<Message> lstMessages;
private LayoutInflater layoutInflater;

public ChatAdapter(Context context, ArrayList<Message> messages) {
    super(context, 0, messages);
    this.lstMessages = messages;
    layoutInflater = LayoutInflater.from(getContext());
}

public int IsMsgFromMe(Message message) {
    boolean isSenderMe = ChatFragment.username.equals(message.GetFrom());
    if (isSenderMe) {
        return 0;
    }
    return 1;
}

@Override
public Message getItem(int position) {
    return lstMessages.get(position);
}

@Override
public int getCount() {
    return lstMessages.size();
}

//Number of layouts
@Override
public int getViewTypeCount() {
    return 1;
}

@Override
public int getItemViewType(int position) {
    Message message = lstMessages.get(position);
    int sender = IsMsgFromMe(message);
    return sender;
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;

    //Warning very bas solution!!!!
    convertView = null; //Make it possible to scroll without loading data over an already existing view.
    int sender = getItemViewType(position);

    if (convertView == null) {
        holder = new ViewHolder();

        //Check who has sent the message me or someone else...
        switch(sender) {
            case 0:
                convertView = layoutInflater.inflate(R.layout.row_chat_me, parent, false);

                holder.chatFrom = (TextView) convertView.findViewById(R.id.txt_message_me_from);
                holder.chatMessage = (TextView) convertView.findViewById(R.id.txt_message_me_message);
                holder.chatTime = (TextView) convertView.findViewById(R.id.txt_message_me_time);
                break;
            case 1:
                convertView = layoutInflater.inflate(R.layout.row_chat_others, parent, false);

                holder.chatFrom = (TextView) convertView.findViewById(R.id.txt_message_others_from);
                holder.chatMessage = (TextView) convertView.findViewById(R.id.txt_message_others_message);
                holder.chatTime = (TextView) convertView.findViewById(R.id.txt_message_others_time);
                break;
        }
        convertView.setTag(holder);

    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    // Get the data item for this position
    Message message = lstMessages.get(position);

    // Populate the data into the template view using the data object
    holder.chatFrom.setText("From: " + message.GetFrom());
    holder.chatMessage.setText(message.GetMsg());
    holder.chatTime.setText("Date: " + message.GetTime());

    // Return the completed view to render on screen
    return convertView;
}

public static class ViewHolder {
    public TextView chatFrom;
    public TextView chatMessage;
    public TextView chatTime;
}

}

A: Try this.
getViewTypeCount() should be returning 2 since you have 2 types of layouts.


text:
Q: Complex regex to check for two words and a quanity Ok what I'm trying to do is to check for the presence of

*

*"TestItem-1"

*a number greater then 1

*one of the possible words in the list of "KG. Kg, kg, Kilo(s) or Kilogram(s)"

Where any of the items could be in any order and within a 6 word limit of each other.
Has to be done in regex as there is no access to the underlying scripting engine
This is what I've got as there a way of checking greater then I decided to use a range of 1-999 for the number check.
\b(?:[T|t]estItem-1\W+(?:\w+\W+){1,6}(^[0-9]|[1-9][0-9]|[1-9][0-9][0-9])$)\W+(?:\w+\W+){1,6}[K|k]il[o|os]|[K|k][[G|GS]|[g|gs]]|[|K|k]ilogra[m|ms]\b

Examples of what I need to find would be like -

"TestItem-1 is unstable in quanties above 12 Kilograms"
  "1 Kilogram of TestItem-1"

While I wouldn't want to find -

"15 units of TestItem-1"

I know that what I got isn't working each section appears to work independently of each other but not together.
I pass this over to far greater minds then mine :)

A: You can try something like this:
\b(?:[2-9]|\d\d+)\b\s\b(?:KG.|Kg,|kg,|Kilos?|Kilograms?)\b(?:\S+\s){0,6}\bTestItem-1\b|\bTestItem-1\b(?:\S+\s){0,6}\b(?:[2-9]|\d\d+)\b\s\b(?:KG.|Kg,|kg,|Kilos?|Kilograms?)\b

Not ideal with the duplication but without lookarounds that's the best I could think of. I'll try and improve it in a bit.


text:
Q: Is it safe to use a laptop AC adapter with 220V power if the AC cable is not rated for 220V? The AC adapter supplied with my laptop is designed to accept voltage in the range of 100-240VAC at 50-60Hz, but the AC cable that plugs into the adapter unit itself is only rated to 125VAC 7.5A 2.5A.  I know the adapter can accept 220V power, but is it safe to use this cable with the AC adapter to plug into a 220V socket?
Edit: The part in question is a 90W HP Smart AC Adapter.  The laptop does not cause the AC adapter to draw more than about 80 watts from the socket (as measured with a Kill A Watt meter).
Edit 2: The amperage rating of the cable as marked on the attached label is 2.5A, not 7.5A.

A: It should be fine.
Your laptop's power consumption is probably less than 100 W (unless it's a particularly power-hungry workstation or gaming machine), which at 220 V works out to about 0.45 A,1 or way less than the 2.5 A the cable is rated for. In fact, since voltage and current are inversely proportional (for constant wattage), you're actually running less current through the cable than it was meant for. So current-wise, you're good.
As for voltage, as far as I know, the 125 V rating is merely an indicator of which mains system it was intended to be used with. The real concern here would be the insulation - if for some reason it's rated for less than 220 V, you'd be creating a fire and shock hazard. From what I've read about typical laptop power cords, the insulation should be good for at least 300 V, but you may want to inspect the cable carefully, the insulation's maximum voltage should be marked on it somewhere.
Nevertheless, if you want to be 100% sure, get a cable that's meant for use with 220 V mains systems.

1 - a bit more, actually, since for alternating current, the amount of power usable by devices (called real power) is less than current × voltage (which is called apparent power), but the number is in the ballpark.


text:
Q: When page unload, a confirm box appear I don't want I am making a chat program like this:http://www.webengine.co.kr/wechat?l=en(korean site) and I have a problem like title.
(This problem appears sometimes. If you want test this, refresh the page many times.)
I think this problem was made by my ajax script
function wechat(id, chatroom_srl, last_chatline_srl, key, nick_name){
  this.id = id;
  this.chatroom_srl = chatroom_srl;
  this.last_chatline_srl = last_chatline_srl;
  this.key = key;
  this.nick_name = nick_name;
  this.wechat = $("#"+this.id);

  var oWechat = this.wechat;
  function exec_json_nomsg(a,b,c){
    if("undefined" == typeof b) b = {};
    a = a.split(".");
    if(2 == a.length){
      $.extend(b, {module:a[0],act:a[1]});
      if("undefined" != typeof xeVid) $.extend(b, {vid:xeVid});
      $.ajax({
        type:"POST",
        dataType:"json",
        url:request_uri,
        contentType:"application/json",
        data:$.param(b),
          success:function(a){
          if($.isFunction(c)) c(a);
        }
      });
    }
  }

  function procChatLines(data){
    for(i=0;i<data.chatline_list.length;i++){
      appendLine(data.chatline_list[i].nick_name, data.chatline_list[i].content, data.chatline_list[i].key);
      wechat.last_chatline_srl = data.chatline_list[i].chatline_srl;
    }
    wechat.timer = setTimeout(loadChatContents, 100);
  }
  function loadChatContents(){
    exec_json_nomsg("chat.loadChatContents", {chatroom_srl:wechat.chatroom_srl, last_chatline_srl:wechat.last_chatline_srl, key:wechat.key}, procChatLines);
    clearTimeout(wechat.timer);
  }
  function appendLine(nick_name, content, key){
    var lineObj = $("

");
    if(wechat.key == key) lineObj.addClass("chatMe");
    lineObj.html(""+nick_name+" : "+content);
    oWechat.find(".chatContentHeight").append(lineObj);
    scrollDown();
  }
  function scrollDown(){
    var o = oWechat.find(".chatContent");
    o.stop().animate({scrollTop:o.find(">.chatContentHeight").height()-o.height()}, 300, "easeInOutQuart");
  }
  $(window).load(function(){
    scrollDown();
  });
  oWechat.find(".wechatInput").keydown(function(e){
    if(e.keyCode == 13){
      if($(this).val().trim() != ""){
        exec_json_nomsg("chat.procChatInsertChatLine",{"chatroom_srl":wechat.chatroom_srl,"content":$(this).val()});
        appendLine(wechat.nick_name, $(this).val(), wechat.key);
        $(this).val("");
      }
    }
  });
  wechat.timer = setTimeout(loadChatContents, 100);
}
  new wechat("wechat1", 1, [last_chatline_srl(PHP give this)], "[User Hidden Key(PHP give this)]", "[User Nick Name]");

What can I do to resolve this problem?

A: It seems like your syntax is just a bit wrong. You are missing an extra bracket. This is what it should look like.
$.ajax({
    type:"POST",
    dataType:"json",
    url:request_uri,
    contentType:"application/json",
    data:postData,
    success:function(b){
        if(0 < b.error){
            //we get to here if b.error is < 0.
            alert(b.message);
        }
        else{
            call_back_function();
        }

    }
});

A: your problem is not in the script you have sent, on the website that you have pointed to you are using a widget on the srchat.js file line 648 and 649 you have:
window.onbeforeunload = function(){if(!chtisbk && chtunload == 'Y') {if(dallar('cht_gout').value == '0'){if(cht_go('out')){dallar('cht_gout').value = '9';if(navigator.appName == 'Opera') alert('접속을 종료합니다');}}}}
window.onunload = function(){window.onbeforeunload();}

those two lines are responsible for that message.
you also are using this libary common/js/xe.min.js
on this libary when an ajax call is initiated it will display that message until the call returned a value. if you want to modify that you need the source of that file.


text: Q: Browser extension - run web worker on demand after button click I'm working on a browser extension that will act like a download manager. The user will have the ability to add multiple files in a queue, I want to give the ability to start at least two download simultaneusly. To implement this I'm thinking to use web workers but I have some doubt about it. Mainly I want to run the web worker only when the user click on the download button of each file and to achive this I'm not sure if implement the js code into the background.js file that run as persistent, or if it will be better to call it from the popup js code. The worker will also use the importScripts() because I need an external library to do the downloads, about this point, if I understand well, after the import the script content will be available to the worker and every spawned child right? What will be the best approach to achive my scope?


text:
Q: How to use regex to only show match at beginning of string I am trying to use regex on this test text:
www.demo.comhttp://foo.co.uk/
http://regexr.com/foo.html?q=bar

I want it to only match 'http://' in the beginning of the string. I tried
^http:\/\/

and
^(http:\/\/)

and
(http:\/\/)\B

and neither worked. What am I doing wrong (I'm not very good at regex and I'm trying to learn)

A: More likely you have omitted the multi-line flag :
/^http:\/\//m


text:
Q: Dúvida sobre ambiente de desenvolvimento LAMP com Vagrant e provisionamento com Puppet Depois de alguns problemas em relação à incompatibilidade de aplicações, desenvolvidas localmente, com o servidor, resolvi utilizar a ferramenta Vagrant.
Segui alguns tutoriais, li sua documentação, criei minha máquina virtual e tive problemas com o provisionamento (creio eu que por falta de entendimento do funcionamento da mesma).
Enfim, encontrei uma trilogia de artigos muito bom (pelo menos eu achei rs) que me ajudou bastante a entender como funcionava o provisionamento com o Puppet.
Mas ainda assim, tenho algumas dúvidas e venho aqui perguntar aos que já trabalham com essas ferramentas, se podem esclarecê-las.
Algumas delas são:

*

*Em um ambiente de desenvolvimento com Vagrant, é necessário instalar um sistema de controle de versões como o GIT dentro da VM? Se sim, Por que?

*Sou iniciante no uso do Composer, e estou entusiasmado, querendo utilizar esta ferramenta em meus projetos, é necessário instalá-lo na VM também? Se sim, Por que?

*O que seria preciso instalar além do básico (Apache, PHP, MySQL)?

Bom pessoal, as principais dúvidas que me surgiram foram essas.
Agradeço desde já a atenção dispensada.

A:
Em um ambiente de desenvolvimento com Vagrant, é necessário instalar um sistema de controle de versões como o GIT dentro da VM? Se sim, Por que?

Depende. O Vagrant tem um funcionamento básico de compartilhamento de uma pasta na sua máquina física com a máquina virtual. Você pode:

*

*Utilizar o GIT na sua máquina física para versionar seu projeto

*Utilizar o GIT na máquina virtual

Basicamente, tanto faz. Mas é importante lembrar que o uso do Vagrant não substitui o uso de um software de versionamento. Talvez se você estiver trabalhando sozinho em um projeto, sinta-se como se não houvesse a necessidade de utilizar versionamento, no entanto é sempre bom manter-se atualizado diante das ferramentas para que você não tenha que aprender muita coisa nova se começar um projeto em parcerias.

Sou iniciante no uso do Composer, e estou entusiasmado, querendo utilizar esta ferramenta em meus projetos, é necessário instalá-lo na VM também? Se sim, Por que?

Basicamente o mesmo conceito anterior se aplica. Você poderia instalar o Composer só na máquina física e gerenciar seu projeto por lá ou instalar na máquina virtual.
Particularmente, sugiro instalar todas as ferramentas de desenvolvimento no Vagrant. Por quê?

*

*Qual a utilidade do Composer na sua máquina física?

*Qual a utilidade do GIT na sua máquina física?

Se a resposta para ambas as perguntas é apenas gerenciar meu projeto que está rodando dentro do Vagrant, então você simplesmente está sujando o ambiente da sua máquina física ao invés de tirar um maior proveito da máquina virtual.

O que seria preciso instalar além do básico (Apache, PHP, MySQL)?

É importante instalar as ferramentas básicas que você utilizará para trabalhar. O Laravel, por exemplo, oferece uma Vagrant chamada Homestead que vem com PHP 7, MySQL, Nginx (ao invés do Apache), Composer, Git, Mencache, Sqlite 3, etc...
Talvez seja melhor não se preocupar com o que mais precisa instalar além das ferramentas básicas. Quando surgir a necessidade, você saberá o que mais instalar.


text:
Q: SQL query on one to many relationship with multiple filters I have some experience with SQL but I still couldn't find out how can I do the following query performance efficient.
I have 2 tables - Box and Item. Box has id attribute which is the primary key (and some more), and Item has box_id, type, name. Each table has billions of records, each box has on average 10 items.
I want to query all the boxes that have at least one item with a given type, and at least one item with a given name (could be the same item or different). The query should be paginated with page size of 10.
I used single column indexing on all Item attributes. The following query for that (the first page) takes a very long duration (more than a minute):
SELECT Box.id FROM Box WHERE
(EXISTS (SELECT 1 FROM Item WHERE Item.box_id = Box.id AND Item.type = 'my_type')) AND
(EXISTS (SELECT 1 FROM Item WHERE Item.box_id = Box.id AND Item.name = 'my_name'))
LIMIT 10

I think that the problem is making the intersection between boxes filtered in each part of the query (querying with just one of the constraints returns about million records). I am using Aurora PostgreSQL 9.6.6.

A: You haven't responded to the clarifications so I will assume a few things:

*

*You want ALL the boxes, not just 10 of them.

*There's a typo when comparing by name. Should be: Item.name = 'my_name'

*You said "I have indexed all Item attributes." I would assume you have single column indexes for all the columns of the Item table.

*The column id of Box is the primary key, and therefore it already has an index on it.

Now, my take is the indexes you are using are not optimal for this query since they only include columns separately. If you don't already have them, please try creating the following indexes:
create index ix1 on Item (box_id, type);

create index ix2 on Item (box_id, name);

Yes, both of them. Try the query again and see how long does it take.
If still slow, please post the explain plan, using:
EXPLAIN ANALYZE
SELECT Box.id
  FROM Box
  WHERE
(EXISTS (SELECT 1 FROM Item WHERE Item.box_id = Box.id AND Item.type = 'my_type'))
  AND
(EXISTS (SELECT 1 FROM Item WHERE Item.box_id = Box.id AND Item.name = 'my_name'))

A: INTERSECT is another option.
  SELECT Box_id FROM Item
  WHERE Item.type = 'my_type'
  INTERSECT
  SELECT Box_id FROM Item
  WHERE Item.name = 'my_name'

Note: INTERSECT returns distinct values so no need for an outer query to get the list of distinct Box_id values that meet your criteria. This query does return orphan items (items with a box_id not in the box table) so an outer query might be required if this is the case.

A: Something like this?
SELECT DISTINCT ON (Box.id) Box.*
FROM Box
  JOIN Item I1 ON I1.box_id = Box.id AND I1.type = 'my_type'
  JOIN Item I2 ON I2.box_id = Box.id AND I2.name = 'my_name'
ORDER BY Box.id;

JOINs filters results by item's type and name.


text:
Q: implementation 'com.firebaseui:firebase-ui-database:4.1.0 error when add this in Gradle
implementation 'com.firebaseui:firebase-ui-database:4.1.0
this error appears:
Program type already present: android.arch.core.util.Function
Message{kind=ERROR, text=Program type already present: android.arch.core.util.Function, sources=[Unknown source file], tool name=Optional.of(D8)}


text:
Q: Compactness of an operator using sequences I want to learn how to prove the compactness of an operator using the following definition: An operator $L$ is compact if for a bounded sequence $\{ x_n\}$, there exists a convergent subsequence $\{ x_{n_k}\}_k$.
Example. Define the linear operator $T : L_2[0, 1] \rightarrow L_2[0, 1]$ by
$$Tf(x) = \int_0^x \int_y^1 f(z)\,dz\,dy.$$
I want to prove it's compact. Take a bounded sequence $\{f_n\}\subset L_2[0,1]$. The domain of each $f_n$ is compact but $f_n$'s are not continuous themselves. So, I cannot say anything about $Lf_n$'s. Can someone help me out here please?
Can I just argue that because $T$ is a bounded linear operator and $dim(R(T))<\infty$, then $L$ is compact?

A: Note that $L^2[0, 1]$ has a complete orthonormal basis, say $\mathcal{B}=\{e_k\}$. In fact, the basis for $L^2[0, 1]$ is given by the set $\{e^{2\pi ni x}\}$ for all $n\in \mathbb{Z}$. Hence $T$ formally has the matrix representation
\begin{align}
[T]_\mathcal{B} = \sum_{m, n \in \mathbb{Z}} \langle e_m, Te_n\rangle e_m \otimes \bar e_n.
\end{align}
Note that
\begin{align}
Te_n = \int^x_0\int^1_y e^{2\pi i n z}\ dzdy = \int^x_0 \frac{1-e^{2\pi in y}}{2\pi in}\ dy = \frac{x}{2\pi in}-\frac{e^{2\pi inx}-1}{(2\pi in)^2}
\end{align}
which means
\begin{align}
\langle e_m, Te_n\rangle = \int^1_0 \frac{xe^{-2\pi i m x}}{2\pi in}-\frac{e^{2\pi i(n-m)x}-e^{-2\pi i mx}}{(2\pi in)^2} =
\begin{cases}
\frac{1}{2\pi^2n^2}& m=n,\\
\frac{1}{4\pi^2mn} & m\ne n
\end{cases}.
\end{align}
This shows that the matrix representation is well-defined since the coefficients are absolutely summable.
Next, define the sequence of finite rank operators
\begin{align}
T_N = \sum_{|n|, |m|\leq N}\langle e_m, Te_n\rangle e_m \otimes \bar e_n
\end{align}
and observe that
\begin{align}
\|T_N - T\|_\text{op} \leq \left(\sum^\infty_{m, n = N+1}|\langle e_m, Te_n\rangle |^2 \right)^{1/2}\rightarrow 0
\end{align}
when $N\rightarrow \infty$, i.e. $T$ is the limit of a sequence of finite rank operator. So $T$ is compact. This is along the line of your second question.