Q: Azure eventhub Kafka org.apache.kafka.common.errors.TimeoutException for some of the records Have a ArrayList containing 80 to 100 records  trying to stream and send each individual record(POJO ,not entire list) to Kafka topic (event hub) . Scheduled a cron job like every hour to send these records(POJO) to event hub.
Able to see messages being sent to eventhub ,but after 3 to 4 successful run  getting following exception (which includes several messages being sent and several failing with below exception)
    Expiring 14 record(s) for eventhubname: 30125  ms has passed since batch creation plus linger time

Following is the config for Producer used,
    props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
    props.put(ProducerConfig.ACKS_CONFIG, "1");
    props.put(ProducerConfig.RETRIES_CONFIG, "3");

Message Retention period - 7
Partition - 6
using spring Kafka(2.2.3) to send the events
method marked as @Async where kafka send is written
    @Async
    protected void send() {
       kafkatemplate.send(record);
    }

Expected - No exception to be thrown from kafka
Actual - org.apache.kafka.common.errors.TimeoutException is been thrown

A: Prakash - we have seen a number of issues where spiky producer patterns see batch timeout.
The problem here is that the producer has two TCP connections that can go idle for > 4 mins - at that point, Azure load balancers close out the idle connections.  The Kafka client is unaware that the connections have been closed so it attempts to send a batch on a dead connection, which times out, at which point retry kicks in.

*

*Set connections.max.idle.ms to < 4mins – this allows Kafka client’s network client layer to gracefully handle connection close for the producer’s message-sending TCP connection

*Set metadata.max.age.ms to < 4mins – this is effectively a keep-alive for the producer metadata TCP connection

Feel free to reach out to the EH product team on Github, we are fairly good about responding to issues - https://github.com/Azure/azure-event-hubs-for-kafka

A: This exception indicates you are queueing records at a faster rate than they can be sent. Once a record is added a batch, there is a time limit for sending that batch to ensure it has been sent within a specified duration. This is controlled by the Producer configuration parameter, request.timeout.ms. If the batch has been queued longer than the timeout limit, the exception will be thrown. Records in that batch will be removed from the send queue.
Please check the below for similar issue, this might help better.
Kafka producer TimeoutException: Expiring 1 record(s)
you can also check this link
when-does-the-apache-kafka-client-throw-a-batch-expired-exception/34794261#34794261 for reason more details about batch expired exception.
Also implement proper retry policy.
Note this does not account any network issues scanner side. With network issues you will not be able to send to either hub.
Hope it helps.


Q: Is it necessary to call end() on a received http request in Node? I have a Node server which can reject requests based upon security headers.  If I reject a request, is it necessary to use blank data and end handlers to read the request body or can I just send the response, a 401, and leave the request unread?
It seems that if I leave the response unread then I get occasional "The existing connection has been forcibly closed by the remote host" errors at the client.  Adding code to wait for the request body to be read does seem to fix the issue but then again, adding delays at various points in the server code also seems to have a beneficial effect.  It can be hard to tell with an intermittent fault.
The coffeescript code that seems to fix the issue is:
 @res.writeHead status, message, @headers
 @req.on 'data', (d) ->
 # wait for request to be completely read before ending response stream
 @req.on 'end', => @res.end()

The empty data handler is required to get the end event and the end event is possibly required to avoid the error at the client.  Given that the request body might be megabytes is this the best way to send a 401 response or is there a better way that doesn't require reading the whole request.

A: Further investigation has revealed a large can of worms.  It would seem that there is no properly implemented method to kill the request stream without potentially causing an error at the client.
This question covers the difficulty of terminating a request early without causing an error:
How to cancel HTTP upload from data events?
I have decided to abort very long requests and to allow shorter ones to complete. In my application this should only normally abort requests that are probably a DOS attack (legitimate requests are usually short)


Q: How to erase specific row from QListWidget I have a small ui with 1 QListWidget. In this uithere is a predefined row in the QListWidget called "Add New".
I drag and drop several files from a folder into a QListWidget. So there are all my files plus the "Add New" record.
The "Add Record" is used as a doubleClick to create a New File and store it both in the QListWidget and in the local folder of the computer.
The problem is that when I erase a specific record from the QListWidget, several files are erased together and I don't know why.
See below the steps:

*

*I launch the application:

*I drag and drop some files and I right click on the last one to erase it:

*As soon as I erase that, several other are also erased as shown below:

Below is the logic I used:
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QAction *remove;
    remove = new QAction(QIcon(":/icons/remove_item.png"), "Remove", this);
    QObject::connect(remove, SIGNAL(triggered()), this, SLOT(on_eraseBtn_clicked()));
    ui->listWidget->setContextMenuPolicy(Qt::ActionsContextMenu);
    ui->listWidget->addAction(remove);
    setAcceptDrops(true);

     ui->listWidget->addItem("Add New");
     ui->listWidget->item(0)->setSelected(true);
}

void MainWindow::on_eraseBtn_clicked()
{
    for(int i = 0; i < ui->listWidget->count(); ++i)
    {
        QString str = ui->listWidget->item(i)->text();
        if (str != "Add New")
            delete ui->listWidget->item(i);
        qDebug() << ui->listWidget->item(i) << str;
    }
}

UPDATE
As proposed by @absolute.madeness, a whileloop could be used too. Not exactly the behavior but close. With the following loop, all the records (or row) of the QListwidget are erased with the exception of the row "Add New"
void MainWindow::on_eraseBtn_clicked()
{
    for(int i = 0; i < ui->listWidget->count(); ++i)
    {
        while(i < ui->listWidget->count() && ui->listWidget->item(i)->text() != "Add New")
            delete ui->listWidget->item(i);
    }
}

What I have done so far is:

*

*on the slot on_eraseBtn_clicked() I just added the line delete  ui->listWidget->currentItem(); to see if at least the record was successfully erased. Which it was so I was sure that the slot was properly triggered.

*After that I did some research and the best approach was to loop through the all QListWidget and and as soon as the record with the QString Add New is found, please keep it and pass to the next record and erase it. This methodology is also described in this post. But for some reason more then one record is erased.

*I tried to do additional research and found this post

*I tried to delete by context as explained in this post.
Any other pointers you can suggest?

A: I originally wrote a for loop that was straightforward but I incurred in the problem to delete item(i) recursively. The next item previously accessed as item(i+1) will decrease by 1, creating a strange effect of erasing several rows unexpectedly.
As proposed by @absolute.madeness, below the solution that avoids that. I hope other will benefit from this solution and don't get stuck wondering why a simple loop can create such unexpected issues:
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    remove = new QAction(QIcon(":/icons/remove_item.png"), "Remove", this);
    QObject::connect(remove, SIGNAL(triggered()), this, SLOT(on_eraseBtn_clicked()));

// other operations in the constructor....
}

void MainWindow::on_eraseBtn_clicked()
{
    for(auto item: ui->listWidget->selectedItems())
        if(item->text() != "Add New") delete item;
}

This way the user selectively erase single rows in the QListWidget leaving only a specific row.


Q: JavaScript small game example Learning Javascript  and stack in small game example.
So why  println(beaver.holes) has "NaN" value ??? It must be normal number without flouting point.
var Beaver = function(x, y) {
this.x = x;
this.y = y;
this.img = getImage("creatures/Hopper-Happy");
this.sticks = 0;
};

Beaver.prototype.draw = function() {
    fill(255, 0, 0);
    this.y = constrain(this.y, 0, height-50);
    image(this.img, this.x, this.y, 40, 40);
};

Beaver.prototype.hop = function() {
    this.img = getImage("creatures/Hopper-Jumping");
    this.y -= 5;
};

Beaver.prototype.fall = function() {
    this.img = getImage("creatures/Hopper-Happy");
    this.y += 5;
};

Beaver.prototype.checkForStickGrab = function(stick) {
    if ((stick.x >= this.x && stick.x <= (this.x + 40)) &&
        (stick.y >= this.y && stick.y <= (this.y + 40))) {
        stick.y = -11;
        this.sticks++;
    }
};
Beaver.prototype.checkForHoleDrop = function(hole) {
    if ((hole.x >= this.x && hole.x<=(this.x +40)) &&
    (hole.y >=this.y && hole.y <= (this.y + 40))) {
        hole.y = -11;
        this.holes++;

    }
};
var Stick = function(x, y) {
    this.x = x;
    this.y = y;
};
var Hole = function(x,y) {
    this.x = x;
    this.y = y;
};
Hole.prototype.draw = function() {

    rectMode(CENTER);
    noStroke();
    fill(120, 144, 204);
    ellipse(this.x,this.y, 51,19);
     fill(0, 40, 71);
    ellipse(this.x,this.y, 40,15);

};
Stick.prototype.draw = function() {
    fill(89, 71, 0);
    rectMode(CENTER);
    rect(this.x, this.y, 5, 40);
};

var beaver = new Beaver(37, 300);

var sticks = [];
for (var i = 0; i < 40; i++) {
    sticks.push(new Stick(i * 44 + 300, random(44, 260)));
}

// holes var
var holes = [];
for (var i = 0;i< 10; i ++) {
    holes.push(new Hole(random(33,400)*i + 306, 378));
}
var grassXs = [];
for (var i = 0; i < 25; i++) {
    grassXs.push(i*18);
}

draw = function() {

    // static
    background(227, 254, 255);
    fill(130, 79, 43);
    rectMode(CORNER);
    rect(0, height*0.90, width, height*0.10);

    for (var i = 0; i < grassXs.length; i++) {
        image(getImage("cute/GrassBlock"), grassXs[i], height*0.85, 20, 20);
        grassXs[i] -= 1;
        if (grassXs[i] <= -32) {
            grassXs[i] = width;
        }
    }
    // making holes
    for (var i = 0; i < holes.length; i++) {
        holes[i].draw();
         beaver.checkForHoleDrop(holes[i]);
       holes[i].x -=2;

    }
    for (var i = 0; i < sticks.length; i++) {
        sticks[i].draw();

        beaver.checkForStickGrab(sticks[i]);
        sticks[i].x -= 2;// value turn speed of sticks
    }

So here if we print beaver.holes on screen it will be give us NaN value.
    textSize(18);
    text("Score: " + beaver.sticks, 20, 30);
    textSize(18);
    text("Score: " + beaver.holes, 105, 30);

    if (beaver.sticks/sticks.length >= 0.95) {

        textSize(36);
        text("YOU WIN!!!!", 100, 200);

    }
    if  (beaver.hole >41) {
            textSize(36);
            text("YOU LOSE!!!",100,200);}
            //println(beaver.holes/holes.length);
    if (keyIsPressed && keyCode === 0) {
        beaver.hop();
    } else {
        beaver.fall();
    }
    beaver.draw();

    };

A: Looks like holes was never initialized for beaver prototypes.
Try modifying the constructor function to look like so.
    var Beaver = function(x, y) {
        this.x = x;
        this.y = y;
        this.img = getImage("creatures/Hopper-Happy");
        this.sticks = 0;
        this.holes = 0;
        };

Performing a ++ operation on an undefined variable returns a NaN result.


Q: Joomla 3 - template only works with category, will not show single article If I set the menu link to be a category blog, it all works fine... but even if I remove all coding from the template 'index.php' file (besides  etc) and add one word, it doesn't work. Just shows a blank page.
e.g.
http://dev.addrenaline.com/acces/index.php?option=com_content&view=article&id=2&Itemid=101
*** I just realized there was a dedicated Joomla stack site - have posted this over there now...


Q: Performance gains from secure-erasing an SSD? Are there performance gains to be had by secure-erasing an SSD? (the secure-erase function, not securely zero'ing out data)
I'm using an Intel 320 SSD 160GB as my main OS drive. It's been a couple years since I've reformatted and started fresh. I'm wondering if there'd be any performance gains from imaging the drive, secure-erasing it, and then laying the image back down (rather than reformatting from scratch)?
I seem to recall seeing a suggestion somewhere that it was good measure to secure-erase an SSD every now and then, even if it's TRIM-capable, because there's some manner of continual performance degradation until a secure-erase is done and the drive is factory-fresh. It might've just been SSD snake-oil, however.

A: yes, secure erase boosts the performance to the default values. I do this each time I reinstall Windows. Your SSD with SandForce controller will benefit from it very much.
http://forums.sandisk.com/t5/SanDisk-Extreme-SSD/HOW-TO-GET-YOUR-SSD-PERFORMANCE-BACK/td-p/281740


Q: How to share variables across in scripts on python two fills I want share two variables in two python files , they are working on serial communication
python serial communication to python gui(tikinter)


Q: Mockito test cases for foreach loop I have an arraylist and I am converting it into another arraylist of different type using foreach loop. I want to write test cases using mockito. How can I do it?
List<Product1> list1 = new ArrayList<Product1>();
List<Product2> list2 = new ArrayList<Product2>();
list1.foreach(productList1 -> list2.add(new Product2(product1.getName())));

class Product1{

}

class Product2{
    String name;
    public Product2(String name){
        this.name=name;
    }
}

A: You dont' need mocking here. You can write a simple test such as
@Test
public void testListConversionForEmpty() {
  assertThat(theConvertingMethod(emptyListOfProduct1), is(emptyListOfProduct2));
}

And then you go in, and add more test methods that act on lists with real content.
In other words: you only use mocking frameworks when creating "real" objects is too complicated.
In your case, you should simply instantiate a few Product1 and Product2 objects, put them into lists, and make sure that your conversion code delivers the expected results. Meaning: you can fully control the input without mocking anything.
( for the record: is() up there is a hamcrest matcher )


Q: Kronecker tensor product in javascript I need to calculate the Kronecker product of two matrices (like the kron() function in MatLab). I can't seem to find any code on it already, maybe someone has one lying on their computer tha is ready to use? I've already searched GitHub, and none of them seem to be working properly.
https://en.wikipedia.org/wiki/Kronecker_product
So for example:
A = [1, 2];
B = [3, 4];
C =kroneckerProduct(A,B)
C will then give [3, 4, 6, 8]

A: I don't know the topic, I had to read it up. So I'm not entirely sure the code is works right (for every input), though I checked it for some examples I found on the net.
function mapAB(a,b,fn){
    var k=0, out = Array(a.length*b.length);
    for(var i=0; i<a.length; ++i)
        for(var j=0; j kroneckerProduct(v, b)):
        Array.isArray(b)?
            b.map(v => kroneckerProduct(a, v)):
            a*b;
}

function mapAB(a, b, fn) {
  var k = 0,
    out = Array(a.length * b.length);
  for (var i = 0; i < a.length; ++i)
    for (var j = 0; j  kroneckerProduct(v, b)) :
    Array.isArray(b) ?
    b.map(v => kroneckerProduct(a, v)) :
    a * b;
}

function compute() {
  var a = document.getElementById("a").value;
  var b = document.getElementById("b").value;
  var text;
  try {
    text = JSON.stringify(kroneckerProduct(
      JSON.parse(a.trim()),
      JSON.parse(b.trim())
    ), null, 2);
  } catch (err) {
    text = err;
  }

  document.getElementById("out").innerHTML = text;

}
<input id=a value=[1,2]>

<input id=b value=[3,4]>

<input type=button value=compute onclick=compute()>


Q: AccessViolationException outside Visual Studio? I'm developing a small C# winforms application that consumes an unmanaged C++ library.
I have no access to the code of this library.
If I'm in Visual Studio and I runt my application, do my calls to the library everything is working find. Once I run CTRL + F5 I get an AccessViolationException.
I did some testing, created another winforms application in .NET 2.0 (others were in .NET 4.0) and there I don't receive the AccessViolationException. So I thought i'd create a .net 2.0 class library in my .net 4.0 solution and consume that class lib. This didn't help, still I had the AccessViolationException.
Tried setting allow unsafe code, optimize code on and off but that didn't help.
Why am I getting the AccessViolationException once I'm out of debug mode?
Thanks

A: I just stumbled upon the same issue. To reproduce the problem in the debugger, I had to go to:
Tools\Options
Debugging\General
and disable: Suppress JIT optimization on module load (managed only).
Of course the problem would only appear for a  optimized code.


Q: How to Access Activation Functions from Saved Model .h5 without importing tensorflow? Is the activation function for each layer stored in the .h5 file produced by model.save()? Or is it already "baked in" to the weights?
I am writing an AWS Lambda function to generate time-series predictions from multiple regression models every five minutes. Unfortunately, TensorFlow is too large of a library to be loaded into an AWS Lambda function, so I am writing my own Python code to load the saved .h5 model file and generate predictions based on the weights and input data. Here's where I'm at so far:
def generate_predictions(model_path, df):
    model_info = h5py.File(model_path, 'r')
    model_weights = model_info['model_weights']
    # Initialize predictions matrix with preprocessed inputs
    predictions = preprocessing.scale(df[inputs])
    layer_list = list(model_weights.keys())
    for layer in layer_list:
        weights = model_weights[layer][layer]['kernel:0'][:]
        bias = model_weights[layer][layer]['bias:0'][:]
        predictions = predictions.dot(weights)
        predictions += bias
        # How to retrieve activation function for layer?
        # predictions = activation_function(predictions)

    return predictions

I understand I'll probably want some kind of case/switch statement to handle the various activation functions.

A: The model configuration is accessible through an attribute called "model_config" on the top group that seems to contain the full model configuration JSON that is produced by model.to_json().
import json
import h5py
model_info = h5py.File('model.h5', 'r')
model_config_json = json.loads(model_info.attrs['model_config'])

A: If you save the full model with model.save, you can access each layer and it's activation function.
from tensorflow.keras.models import load_model
model = load_model('model.h5')

for l in model.layers:
  try:
    print(l.activation)
  except: # some layers don't have any activation
    pass

<function tanh at 0x7fa513b4a8c8>
<function softmax at 0x7fa513b4a510>

Here, for example, softmax is used in the last layer.
If you don't want to import tensorflow, you can also read from h5py.
import h5py
import json

model_info = h5py.File('model.h5', 'r')

model_config = json.loads(model_info.attrs.get('model_config').decode('utf-8'))

for k in model_config['config']['layers']:
  if 'activation' in k['config']:
      print(f"{k['class_name']}: {k['config']['activation']}")

LSTM: tanh
Dense: softmax

Here, last layer is a dense layer which has softmax activation.


Q: Can't get Chrome Extension to store settings via popup.html & popup.js I am trying to setup a Chrome Extension, so when the user clicks on the extension icon, it presents two checkboxes that the user can check or not (via popup.html). This works. Then, I want the user to click on a Save button, and have popup.js fire, which will store their choices in chrome storage. I cannot get this to work at all.  I can't get anything to show up in console.log either.
Ultimately, I want my code to check to see if anything has been set in storage, retrieve the values and pre-set them, and then have the choices show to the user.  If they change something, I want to establish a listener that notes the change, and saves the current settings to storage.  But I need to walk before I run.
I should point out that I am a neophyte web developer and have done my best searching the web, looking at code examples, etc. for weeks to no avail. Any help would be greatly appreciated !
Here are my key files:
manifest.json
{
  "manifest_version": 2,
  "name": "WSH",
  "description": "WSH Description",
  "version": "2.7.3",
  "web_accessible_resources": [
    "icon-32.png"
  ],
  "content_scripts": [{
    "matches": [
      "*://*.boardgamegeek.com/*"
    ],
    "js": [
      "content.js"
    ],
    "css": [
      "content.css"
    ],
    "run_at": "document_idle"
  }],
  "permissions" : [
    "https://raw.githubusercontent.com/*",
    "storage"
  ],
  "browser_action": {
    "default_icon": {
      "32": "icon-32.png",
      "48": "icon-48.png",
      "128": "icon-128.png"
    },
  "default_title": "Click for GCV Options",
  "default_popup": "popup.html"
  }
}

popup.html
<!doctype html>

GCV Objects

Cards
  <input type="checkbox" id="GCVCards" name="GCVCards" value="1" checked>

Tokens
  <input type="checkbox" id="GCVTokens" name="GCVTokens" value="1" checked>

<input id="Save" type="submit" name="Save" value="Save">

popup.js
function save_options(){
  var GCVCards = document.getElementById('GCVCards').value;
  chrome.storage.sync.set({'GCVCards': GCVCards}, function() {
    console.log('GCVCards Value is set to: ' + GCVCards);
  });
}

document.getElementById('Save').onclick = save_options;


Q: Finite Number of Zeros in Differential Equation? Let $y(x)$ be a non-trivial solution of $$\frac{d^2y}{dx^2}+ q(x) y = 0$$ on a closed interval $[a,b]$ where $q(x)$ is a positive function. Then prove that $y(x)$ has at most a finite number of zeros in $[a,b]$.
Any help would be greatly appreciated.
Thanks :)

A: Suppose that $y$ has an infinite number of zeros on $[a,b]$. Since $[a,b]$ is compact, the set of zeros has an accumulation point $x_0\in[a,b]$. Then $y(x_0)=y'(x_0)=0$. By uniqueness of solution, $y(x)=0$ for all $x\in[a,b]$.


Q: Wireless Networks showing "device not managed" in Network Manager I am using Kali Linux 1.0.6. Recently I have disabled NetworkManager and configured my system to connect to wireless network through Terminal by editing /etc/network/interfaces and running wpa_supplicant.
Now, I want to switch back to NetworkManager UI but I am unable to see any wireless networks. It is saying "device not managed" under Wireless Networks. I tried many solutions which said editing /etc/NetworkManager/NetworkManager.conf and changing Managed=true will solve the issue. But  it didn't solve. I reinstalled NetworkManager even reinstalled wireless modules with no use.
How to get back wireless networks in my NetworkManager UI?

A: Probably what is happening here is that some other process owns the wireless chip inside your computer, so NetworkManager isn't allowed to do anything. In this case, that process would be wpa_supplicant or whatever is calling wpa_supplicant (and acting on the information in /etc/network/interfaces).
Instead of randomly installing things, you should stop and think a moment about what caused your problem. The problem appeared when you edited /etc/network/interfaces, right? So undo the changes you made in that file. That will stop other processes from wanting ot take control of the network device, thus allowing NetworkManager to do its thing.

A: By default, if an interface is listed in /etc/network/interfaces, NetworkManager will be smart and not touch this interface, to avoid both configuration method to interfere with each other.
Comment the /etc/network/interfaces definition concerning your wireless device and restart NetworkManager.


Q: How to pop up div inside a ? Here is my code?

                    Document No
                    Document Type
                    Total Amount

I want to popup content of inside

  from JavaScript or jQuery.

A: You can clone table to some popup and show it:
HTML

            Document No
            Document Type
            Total Amount

<button onclick="popup()">Pop-up</button>

JavaScript
var popupEl;

function popup() {
  var divEl,
      tableEl,
      xEl;
  if(!popupEl) {
    // Find table
    tableEl = document.querySelector('#sub-155642 > table');
    divEl = tableEl.parentNode;
    // Create popup and clone table to it
    popupEl = document.createElement('div');
    popupEl.innerHTML = divEl.innerHTML;
    popupEl.setAttribute('style', 'position:fixed;top:50%;left:50%;width:300px;height:100px;margin-left:-150px;margin-top:-50px;border:1px solid gray');
    // Show popup
    document.querySelector('body').appendChild(popupEl);
  } else {
    document.querySelector('body').removeChild(popupEl);
    popupEl = null;
  }
}

JSBin: http://jsbin.com/OyeXiNu/1/edit
otherwise you can make wrapping tables visible (but be sure IDs are unique):
JavaScript
var div = document.getElementById('sub-155642');
div.style.display = 'block';
div.parentNode.parentNode.style.display = 'table-row';


Q: Unpacking mono channel wave data and storing it in an array I'm trying to unpack the data from a single channel WAVE file using struct.unpack. I want to store the data in an array and be able to manipulate it (say by adding noise of given variance). I have extracted the header data and stored it in a dictionary as follows:
stHeaderFields['ChunkSize'] = struct.unpack('<L', bufHeader[4:8])[0]
stHeaderFields['Format'] = bufHeader[8:12]
stHeaderFields['Subchunk1Size'] = struct.unpack('<L', bufHeader[16:20])[0]
stHeaderFields['AudioFormat'] = struct.unpack('<H', bufHeader[20:22])[0]
stHeaderFields['NumChannels'] = struct.unpack('<H', bufHeader[22:24])[0]
stHeaderFields['SampleRate'] = struct.unpack('<L', bufHeader[24:28])[0]
stHeaderFields['ByteRate'] = struct.unpack('<L', bufHeader[28:32])[0]
stHeaderFields['BlockAlign'] = struct.unpack('<H', bufHeader[32:34])[0]
stHeaderFields['BitsPerSample'] = struct.unpack('<H', bufHeader[34:36])[0]

When I pass in a file I get the following output:
NumChannels: 1
ChunkSize: 78476
BloackAlign: 0
Filename: foo.wav
ByteRate: 32000
BlockAlign: 2
AudioFormat: 1
SampleRate: 16000
BitsPerSample: 16
Format: WAVE
Subchunk1Size: 16

I then try to get the data by doing struct.unpack('<h', self.bufHeader[36:])[0] but doing this returns a simple integer value 24932. I'm not allowed to use the wave library or anything else to do with waves specifically as I Will have to adapt this to other sorts of signals. How can I store and manipulate the actual wave data?
EDIT:
while chunk_reader < stHeaderFields['ChunkSize']:
        data.append(struct.unpack('<H', bufHeader[chunk_reader:chunk_reader+stHeaderFields['BlockAlign']]))

A: Okay, I'll try to write a complete walk-through.
First, it is a common mistake to treat WAV (or, more likely, RIFF) file as a linear structure. It is actually a tree, with each element having a 4-byte tag, 4-byte length of data and/or child elements, and some kind of data inside.
It is just common for WAV files to have only two child elements ('fmt ' and 'data'), but it also may have metadata ('LIST') with some child elements ('INAM', 'IART', 'ICMT' etc.) or some other elements. Also there's no actual order requirement for blocks, so it is incorrect to think that 'data' follows 'fmt ', because metadata may stick in between.
So let's look at the RIFF file:
'RIFF'
  |-- file type ('WAVE')
  |-- 'fmt '
  |     |-- AudioFormat
  |     |-- NumChannels
  |     |-- ...
  |     L＿ BitsPerSample
  |-- 'LIST' (optional)
  |     |-- ... (other tags)
  |     L＿ ... (other tags)
  L＿ 'data'
        |-- sample 1 for channel 1
        |-- ...
        |-- sample 1 for channel N
        |-- sample 2 for channel 1
        |-- ...
        |-- sample 2 for channel N
        L＿ ...

So, how should you read a WAV file? Well, first you need to read 4 bytes from the beginning of the file and make sure it is RIFF or RIFX tag, otherwise it is not a valid RIFF file. The difference between RIFF and RIFX is the former uses little-endian encoding (and is supported everywhere) while the latter uses big-endian (and virtually nobody supports it). For simplicity let's assume we're dealing only with little-endian RIFF files.
Next you read the root element length (in file endianness) and following file type. If file type is not WAVE, it is not a WAV file, so you might abandon further processing. After reading the root element, you start to read all child elements and process those you're interested in.
Reading fmt header is pretty straightforward, and you have actually done it in your code.
Data samples are usually represented as 1, 2, 3 or 4 bytes (again, in the file endianness). The most common format is a so-called s16_le (you might have seen such naming in some audio processing utilities like ffmpeg), which means samples are presented as signed 16-bit integers in little endian. Other possible formats are u8 (8-bit samples are unsigned numbers!), s24_le, s32_le. Data samples are interleaved, so it is easy to seek to arbitrary position in a stream even for multi-channel audio. Note: this is valid only for uncompressed WAV files, as indicated by AudioFormat == 1. For other formats data samples may have another layout.
So let's take a look at a simple WAV reader:
stHeaderFields = dict()
rawData = None

with open("file.wav", "rb") as f:
    riffTag = f.read(4)
    if riffTag != 'RIFF':
        print 'not a valid RIFF file'
        exit(1)

    riffLength = struct.unpack('<L', f.read(4))[0]
    riffType = f.read(4)
    if riffType != 'WAVE':
        print 'not a WAV file'
        exit(1)

    # now read children
    while f.tell() < 8 + riffLength:
        tag = f.read(4)
        length = struct.unpack('<L', f.read(4))[0]

        if tag == 'fmt ': # format element
            fmtData = f.read(length)
            fmt, numChannels, sampleRate, byteRate, blockAlign, bitsPerSample = struct.unpack('<HHLLHH', fmtData)
            stHeaderFields['AudioFormat'] = fmt
            stHeaderFields['NumChannels'] = numChannels
            stHeaderFields['SampleRate'] = sampleRate
            stHeaderFields['ByteRate'] = byteRate
            stHeaderFields['BlockAlign'] = blockAlign
            stHeaderFields['BitsPerSample'] = bitsPerSample

        elif tag == 'data': # data element
            rawData = f.read(length)

        else: # some other element, just skip it
            f.seek(length, 1)

Now we know file format info and its sample data, so we can parse it. As it was said, sample may have any size, but for now let's assume we're dealing only with 16-bit samples:
blockAlign = stHeaderFields['BlockAlign']
numChannels = stHeaderFields['NumChannels']

# some sanity checks
assert(stHeaderFields['BitsPerSample'] == 16)
assert(numChannels * stHeaderFields['BitsPerSample'] == blockAlign * 8)

for offset in range(0, len(rawData), blockAlign):
    samples = struct.unpack('<' + 'h' * numChannels, rawData[offset:offset+blockAlign])

    # now samples contains a tuple with sample values for each channel
    # (in case of mono audio, you'll have a tuple with just one element).
    # you may store it in the array for future processing,
    # change and immediately write to another stream, whatever.

So now you have all the samples in rawData, and you may access and modify it as you like. It might be handy to use Python's array() to effectively access and modify data (but it won't do in case of 24-bit audio, you'll need to write your own serialization and deserialization).
After you've done with data processing (which may involve upscaling or downscaling the number of bits per sample, changing number of channels, sound levels manipulation etc.), you just write a new RIFF header with correct data length (usually may be computed with a simplified formula 36 + len(rawData)), an altered fmt header and data stream.
Hope this helps.


Q: How to specify soft constraints using prolog? (puzzle with soft constraints) I've been given as an assignment to solve a puzzle using prolog.
Being a beginner in prolog, who just read a couple of online tutorials on prolog the last few hours, I have no idea how to even start this..
The puzzle is much larger scale and has more constraints, but I will simplify it here because I just want to get the idea so I can scale it later.
The puzzle goes like this:
You need to schedule shifts for 2 employees, A and B, for the week.(including weekends)
Rules:

*

*In a single day, either A or B (but not both) must be working

*A must work on Tuesday

*no one can work continuously for more than 2 days

Soft constraints:

*

*A prefers to work on Thursday (add 2 points if A works on Thursday )

*B dislike to work on Wednesday (add 5 points if B doesn't work on Wednesday)

The chart:
|--------|--------|--------|---------|-----------|----------|--------|----------|
|        | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday |
|--------|--------|--------|---------|-----------|----------|--------|----------|
|    A   |        |        |         |           |          |        |          |
|--------|--------|--------|---------|-----------|----------|--------|----------|
|    B   |        |        |         |           |          |        |          |
|--------|--------|--------|---------|-----------|----------|--------|----------|

How to schedule this so that can achieve the highest points possible?
One possible solution (there are several) will be:
|--------|--------|--------|---------|-----------|----------|--------|----------|
|        | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday | Saturday |
|--------|--------|--------|---------|-----------|----------|--------|----------|
|    A   |        |        |    X    |     X     |          |        |     X    |
|--------|--------|--------|---------|-----------|----------|--------|----------|
|    B   |    X   |    X   |         |           |     X    |    X   |          |
|--------|--------|--------|---------|-----------|----------|--------|----------|

The maximum we can get is 5 points. Since there's no solution that can get full marks of 7 points while satisfying all rules.
Question that I have:

*

*How do we set rules with soft constraints? Since it is impossible to respect all the rules under soft constraints above, have to decide which one to take base on highest points.

*How to represent a 2d array such as above in prolog? I have read about List, but not sure how to represent a 2d List.

Thanks in advance!

A: Plain Prolog is probably not the best choice here.  Such problems are most easily modelled using 0/1 Integer Programming, and solved with an IP or Finite-Domain solver, which several enhanced Prologs provide.  Here is a solution in ECLiPSe (disclaimer: I'm a co-developer).  The soft constraints are handled via an objective function.
:- lib(ic).
:- lib(ic_global_gac).
:- lib(branch_and_bound).

schedule(Points, As, Bs) :-
    As = [_ASu,_AMo, ATu,_AWe, ATh,_AFr,_ASa],
    Bs = [_BSu,_BMo,_BTu, BWe,_BTh,_BFr,_BSa],

    As :: 0..1,
    Bs :: 0..1,
    ( foreach(A,As), foreach(B,Bs) do A+B #= 1 ),    % Rule 1
    ATu = 1,                                         % Rule 2
    sequence(0, 2, 3, As),            % 0..2 out of 3, Rule 3
    sequence(0, 2, 3, Bs),

    Points #= 2*ATh + 5*(1-BWe),                     % Soft

    Cost #= -Points,
    append(As, Bs, ABs),
    minimize(labeling(ABs), Cost).

?- schedule(P, As, Bs).
P = 5
As = [0, 0, 1, 1, 0, 0, 1]
Bs = [1, 1, 0, 0, 1, 1, 0]
Yes (0.03s cpu)

A: In Prolog, for simple problems, we can try to apply a simple 'pattern', plain old generate and test, interesting for its simplicity. We 'just' provide appropriate domain generator and test.
generate(D0, D) :-
    length(D0, DL),
    length(D, DL),
    maplist(dom_element, D).
dom_element(a).
dom_element(b).

test(D, Score, D) :-
    D = [_Sunday, _Monday, Tuesday, Wednesday, Thursday, _Friday, _Saturday],

    % 1. In a single day, either A or B (but not both) must be working
    %    Here True by construction

    % 2. A must work on Tuesday
    Tuesday = a,

    % 3. no one can work continuously for more than 2 days
    no_more_than_2(D),

    % soft 1. A prefers to work on Thursday (add 2 points if A works on Thursday )
    ( Thursday = a -> S1 is 2 ; S1 is 0 ),

    % soft 2. B dislike to work on Wednesday (add 5 points if B doesn't work on Wednesday)
    ( Wednesday \= b -> S2 is 5 ; S2 is 0 ),

    Score is S1 + S2.

% edit: jshimpfs suggestion, beside being much better, highlights a bug
no_more_than_2(D) :-
    nth0(I, D, E),
    length(D, L),
    J is (I+1) mod L,
    nth0(J, D, E),
    K is (J+1) mod L,
    nth0(K, D, E),
    !, fail.
no_more_than_2(_).

solve(D0, Best) :-
    D0 = [sun,mon,tue,wed,thu,fri,sat],
    setof(Score/Sol, D^(generate(D0, D), test(D, Score, Sol)), All),
    last(All, Best).

test:
?- solve(_,L).
L = 5/[b, b, a, a, b, b, a].


Q: Selenium | Unable to create new service: ChromeDriverService | Driver info: driver.version: unknown (SessionNotCreated)' | C# Try to start selenium with chrome by remoteDriver with a hub.
I create a config.json for capabilities, configuration etc...
I manage to run tests with IE and Firefox but can't with Chrome.
When start my test with chrome, I get this mistake :
System.InvalidOperationException : 'Unable to create new service: ChromeDriverService
... Driver info: driver.version: unknown (SessionNotCreated)'

I run my test with chrome V84 also I use chromeDriver84. I define my version like this :
 "browserName":"chrome",
     "browserVersion" : 84.0,
     "maxInstances":10,
     "seleniumProtocol":"WebDriver",
     "webdriver.chrome.driver": "D:/Tools/Selenium/WebDrivers/chromedriver84.exe"

I try  "version" : 84.0 and  "version" : "84.0" and  "version" : 84 and  "version" : "latest" etc...
But i understand why driver.version is unknown .
Thanks in advance !


Q: Node.JS - How to identify which async HTTP GET response is returning data in a callback? I'm trying to follow the NodeSchool tutorials on async principles.  There is a lesson with the requirement to:

*

*make asynchronous GET requests to 3 URLs

*collect the data returned in HTTP responses using callbacks

*print the data collected from each response, preserving the order of the correlating input URLs
One way I thought of doing this was to make 3 separate callbacks, each writing to its own dedicated buffer.  But this seemed like a poor solution to me, because it requires code duplication and is not scalable.  However, I am stuck on figuring out another way to get a callback to remember "where it came from" for lack of a better term.  Or what order it was called in, etc.
I feel like I'm close, but I've been stuck at 'close' for long enough to look for help.  Here's the closest I've felt so far:
var http = require('http');

var replies = 0;
var results = ['','',''];
var running = '';

for(var i = 2; i < 5; i++) {
    http.get(process.argv[i], function (response) {
        response.setEncoding('utf8');
        response.on('data', handleGet);
        response.on('error', handleError);
        response.on('end', handleEnd);
    });
}

function handleGet(data) {
    running += data;
}

function handleError(error) {
    console.log(error);
}

function handleEnd() {
    results[replies] = running;
    running = '';
    replies++;
    if(replies === 3) {
        for(var i = 0; i < 3; i++) {
            console.log(totals[i]);
        }
    }
}

How can I get the callback to recognize which GET its response is a response to?
Note: the assignment specifically prohibits the use of 3rd party libs such as async or after.
Edit: another thing I tried (that also obviously failed), was inlining the callback definition for handleGet like so, to try and preserve the 'index' of the callback:
response.on('data', function(data) {
    results[i-2] += data;
});

On execution, this always indexes to results[3] because the async callbacks don't happen until after the for loop is already long done.  (Actually I'm not sure why the value of i is preserved at 5 at all, since the completed for loop would go out of scope, as I understand it... I would have thought it'd be undefined in retrospect.)

A: I will suggest using your second solution but passing the value of i and creating another function which encloses that variable. By this I mean the following:
(function(){
  var index = i;
  http.get(process.argv[i], function (response) {
        response.setEncoding('utf8');
        response.on('data', handleGetFrom(index));
        response.on('error', handleError);
        response.on('end', handleEnd);
    })
}());

and the handleGetFrom:
var handleGetFrom = function(i) {
    return function(data) {
     results[i-2] += data;
    }
}

Edited my original answer.

A: You can use the 'this' object:
var http = require('http');

http.get('http://www.google.com', function (response) {
    response.setEncoding('utf8');
    response.on('data', function(chunk) {
        console.log(this); // Holds the respons object
        console.log(this.headers.location); // Holds the request url
    });
});


Q: Receiving IrDA message on STM32H7 I'm trying to receive some data using USART in IrDA mode on an STM32H7 board with HAL drivers.
I get the reply as I expect it on the gpio pin (baud rate, logic, and timing are ok) but for some reason the data is never moved to the RDR register of the USART and when I try to read it I just get zeroes on the first try and a timeout after that (polling mode).
After filling the IRDA handle structure I call HAL_IRDA_DeInit() and HAL_IRDA_Init(). I configure the GPIO in HAL_IRDA_MSP_Init() and send the first message that reaches the target (with HAL_IRDA_Transmit() ). The target then is sending a reply that I can check on the UART_RX pin. And here something happens.. or better doesn't happen. If I read the UART with HAL_IRDA_Receive() (1 byte at a time) I get only zero and then timeouts.
IRDA_HandleTypeDef hirda4;

void vIrdaInit(void)
{
    hirda.Instance = USART3;
    hirda.Init.BaudRate = 60100;
    hirda.Init.WordLength = IRDA_WORDLENGTH_9B;
    hirda.Init.Parity = IRDA_PARITY_NONE;
    hirda.Init.Mode = IRDA_MODE_TX_RX;
    hirda.Init.Prescaler = 1;
    hirda.Init.PowerMode = IRDA_POWERMODE_NORMAL;

    /* Initialize the IRDA registers. Here also HAL_IRDA_MspInit() will be called */
    if (HAL_IRDA_Init(&hirda4) != HAL_OK)
    {
        Error_Handler();
    }

}

/* Initialize IrDA low level resources. This function is called by HAL_IRDA_Init() */
void HAL_IRDA_MspInit(IRDA_HandleTypeDef* irdaHandle)
{

    GPIO_InitTypeDef GPIO_InitStruct = {0};
    if(irdaHandle->Instance==USART3)
    {
        /* UART4 clock enable */
        __HAL_RCC_USART3_CLK_ENABLE();
        __HAL_RCC_GPIOB_CLK_ENABLE();

        /**UART4 GPIO Configuration
        PB10     ------> USART3_RX
        PB11     ------> USART3_TX
        */
        GPIO_InitStruct.Pin = GPIO_PIN_10;
        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_NOPULL;
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
        GPIO_InitStruct.Alternate = GPIO_AF7_UART3;
        HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

        GPIO_InitStruct.Pin = GPIO_PIN_11;
        GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
        HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
    }
}

here the call to HAL_IRDA_Transmit()/HAL_IRDA_Receive():
if(HAL_IRDA_Transmit(&hirda (uint8_t*)TxBuf, sizeof(RxBuf), 5000)!= HAL_OK)
{
    Error_Handler();
}

memset(RxBuf, '\0', sizeof(RxBuf));
for (i = 0; i < 8; i++)
{
    // blocks here until timeout or data
    if(HAL_IRDA_Receive(&hirda, (uint8_t*)RxBuf, 1, 500)!= HAL_OK)
    {
        Error_Handler();
    }
}

With the first time in the loop, I have the RXNE flag raised but in RDR there is only 0. The following iterations are resulting always in a timeout (from IRDA_WaitOnFlagUntilTimeout()). I have no idea where to look... The pulses I receive are bigger than the 3/16 of a period, the levels are ok but seem I cannot get the message through the SIR receive decoder and in the data register.
UPDATE: here a screenshot with the received signal:

Baud rate is fine, start and stop bits are present and the message (9 bits) is what I am waiting for. But is not recognized by the decoder and passed to the UART.

A: Adding a dummy read of 1 byte just after calling the init function allowed me to successfully read once without Timeouts. The problem is that after that, the Receive() function starts again to return Timeouts. The only workaround I could find was to re-init the UART just before calling the Receive() function. This allows me to retrieve the full message. It is sloppy, but it works.
I tried to find the registers that change but I was not able to isolate what is causing the problem.


Q: lodash break down array based on sub-array retaining the array record I have an array like below. As you can see, a book can have many authors. But I want to group the book by an author. But regardless I want to get to break the array first so that the multiple authors will be broken down to a single author and the other one will go to create a new set of an array.
[0]
    'book_name': 'book1'
    'authors': array(1)
             0:
                author_id:'value2'
                author_name: 'Name2'
[1]
    'book_name': 'book2'
    'authors': array(2)
             0:
                author_id:'value1'
                author_name: 'Name1'
             1:
                author_id:'value2'
                author_name: 'Name2'

I want to have expected output like this
[0]
    'book_name': 'book1'
    'authors': array(1)
             0:
                author_id:'value2'
                author_name: 'Name2'
[1]
    'book_name': 'book2'
    'authors': array(1)
             0:
                author_id:'value1'
                author_name: 'Name1'
[2]
    'book_name': 'book2'
    'authors': array(1)
             0:
                author_id:'value2'
                author_name: 'Name2'

What I have done so far is:
 grouping = _.chain(books)
            .flatMap('authors')
            .groupBy('author_id')
            .value()

My solution actually works since it flattens the array, but my problem is that it only returns the 'authors', I want also to retrieve the 'books' information.

A: Actually you don't need lodash to achieve the result you're expecting:

const books = [
  {
    'book_name': 'book1',
    'authors': [
      {
        author_id: 'value2',
        author_name: 'Name2',
      },
    ],
  },
  {
    'book_name': 'book2',
    'authors': [
      {
        author_id: 'value1',
        author_name: 'Name1',
      },
      {
        author_id: 'value2',
        author_name: 'Name2',
      }
    ],
  },
];

const transformed = books.reduce((accumulator, book) => {
  const authors = book.authors.map(author => ({
      ...book,
      authors: [author]
  }));

  return accumulator.concat(authors);
}, []);

console.log('original', books);
console.log('transformed', transformed);

A: It can be done with simple JavaScript.
const books = [{    'book_name': 'book1',
    'authors': [{author_id:'value2',
                author_name: 'Name2'}] },
   {'book_name': 'book2',
    'authors': [{author_id:'value3',
                author_name: 'Name3'},
                {author_id:'value4',
                author_name: 'Name4'}] }];

const arr = [];
books.map((book)=>{
    book.authors.forEach((author) => {
        arr.push({
               book_name: book.book_name,
               authors: [author]
         });
       });
     })
console.log(arr);


Q: How to change Leaflet Map panes layering order (z-index)? Leaflet maintains that the Map panes elements contain all layers added to the map. The difference between many of the Map panes is strictly the z-index order of layering.
I would like to use a combination of lvector.CartoDB layers, which are essentially overlayPane layers, with TileLayer, such as GeoIQ Acetate-bg and labels.
This is the ordering of the elements as they are added the map:
tileLayer1 = new L.TileLayer();
map.add(tileLayer1);  // add first layer to map

cartoDBLayer1 = new lvector.CartoDB();
cartoDBLayer.setMap(map); // add second layer to map

tileLayer2 = new L.TileLayer();
map.add(tileLayer2);  // add third layer to map

What returns is a map with layers in this order:
tileLayer1,tileLayer2,cartoDBLayer1

tileLayer1 and tileLayer2 are situated in the HTMLElement: TilePane and cartoDBLayer1 is in HTMLElement: overlayPane.
Is there any way to force cartoDBLayer1 to render in the TilePane, such that it falls in order of the z-index that it is added to the map in...
i.e.
z-index[0]:tileLayer1
z-index[1]:cartoDBLayer1
z-index[2]:tileLayer2

A: Update Sept 2014
Leaflet now supports setting the zIndex. Thanks to @knutole in the comments for letting me know.
Old Answer
Have you seen this issue created one the LeafLet github repo:
https://github.com/Leaflet/Leaflet/issues/167
try to use
 addLayer(layer,true);

to add a tile layer to the bottom. I'm afraid that's all there is and this second optional argument is not even documented.


Q: Is apt-get dist-upgrade required in Docker container? Node Source's Docker image of Ubuntu runs apt-get upgrade, not apt-get dist-upgrade, to install latest version of all packages.
apt-get dist-upgrade is considered a command to upgrade kernel related packages. In Docker container, kernel packages are not installed because host's kernel is used, and apt-get upgrade looks enough.
However, man page of apt-get says:
dist-upgrade in addition to performing the function of upgrade,
also intelligently handles changing dependencies with new versions
of packages

According to this, other packages may require to run apt-get dist-upgrade to install latest patch.
Are there such packages which requires apt-get dist-upgrade in the current or past releases of Ubuntu?
If such packages exists, we need to run dist-upgrade even in Docker container.

A: In general, you are going to want to use upgrade rather then dist-upgrade.
In general, unless you have a problem or feel you know more then the docker developers, best go with the defaults.
In the event upgrade has problems, dist-upgrade is a potential solution.
upgrade will update new packages when new versions are available, but will sometimes not remove packages or not install additional packages. dist-upgrade will upgrade and if necessary add or remove packages.
You should always review what apt-get is telling you when you upgrade and review the packages list with dist-upgrade.
For additional information see
What is "dist-upgrade" and why does it upgrade more than "upgrade"?
and
Why use apt-get upgrade instead of apt-get dist-upgrade?

A: I would say you should not even use upgrade: rather rebuild the image with --no-cache and execute the usual update and install pair, which will fetch the latest versions of a package.


Q: Run reducer after state is updated by another reducer Let's say I've got an app with two reducers - tables and footer combined using combineReducers().
When I click on some button two actions are being dispatched - one after another: "REFRESH_TABLES" and "REFRESH_FOOTER".
tables reducer is listening for the first action and it modifies the state of tables. The second action triggers footer reducer. The thing is it needs current state of tables in order to do it's thing.
My implementation looks something like below.
Button component:
import React from 'react';

const refreshButton = React.createClass({
    refresh () {
        this.props.refreshTables();
        this.props.refreshFooter(this.props.tables);
    },
    render() {
        return (
            <button onClick={this.refresh}>Refresh</button>
        )
    }
});

export default refreshButton;

ActionCreators:
export function refreshTables() {
    return {
        type: REFRESH_TABLES
    }
}

export function refreshFooter(tables) {
    return {
        type: REFRESH_FOOTER,
        tables
    }
}

The problem is that the props didn't update at this point so the state of tables that footer reducer gets is also not updated yet and it contains the data form before the tables reducer run.
So how do I get a fresh state to the reducer when multiple actions are dispatched one after another from the view?

A: Seems you need to handle the actions async so you can use a custom middleware like redux-thuk to do something like this:
actions.js
function refreshTables() {
  return {
    type: REFRESH_TABLES
  }
}

function refreshFooter(tables) {
  return {
    type: REFRESH_FOOTER,
    tables
  }
}

export function refresh() {
  return function (dispatch, getState) {
    dispatch(refreshTables())
      .then(() => dispatch(refreshFooter(getState().tables)))
  }
}

component
const refreshButton = React.createClass({
  refresh () {
    this.props.refresh();
  },
  {/* ... */}
});

A: Although splitting it asynchronous may help, the issue may be in the fact that you are using combineReducers. You should not have to rely on the tables from props, you want to use the source of truth which is state.
You need to look at rewriting the root reducer so you have access to all of state. I have done so by writing it like this.
const rootReducer = (state, action) => ({
  tables: tableReducer(state.tables, action, state),
  footer: footerReducer(state.footer, action, state)
});

With that you now have access to full state in both reducers so you shouldn't have to pass it around from props.
Your reducer could then looks like this.
const footerReducer = (state, action, { tables }) => {
...
};

That way you are not actually pulling in all parts of state as it starts to grow and only access what you need.


Q: Can't list_options for capture card in ffmpeg : "Unable to BindToObject" I'm trying to list the options of a "AJA Kona3G Quad" device on Windows 10 using ffmpeg.

[dshow @ 000001343e7d9740] DirectShow video devices (some may be both
  video and audio devices) [dshow @ 000001343e7d9740]  "AJA S-Capture
  Kona3GQuad - 0"
[dshow @ 000001343e7d9740]     Alternative name
  "@device_sw_{860BB310-5D01-11D0-BD3B-00A0C911CE86}{89BB1170-565C-49B6-9DED-D6D2DFCA06A8}"
[dshow @ 000001343e7d9740] DirectShow audio
[dshow @ 000001343e7d9740]  "AJA S-Capture [Audio] Kona3GQuad - 0"
[dshow @ 000001343e7d9740]  Alternative name
  "@device_sw_{33D9A762-90C8-11D0-BD43-00A0C911CE86}{89BB1190-565C-49B6-9DED-D6D2DFCA06A8}"

Listing the devices seemsok, but once I get my device name and try to list it's options ffmpeg returns the following

[dshow @ 000001aeac2a96c0] Unable to BindToObject for AJA S-Capture Kona3GQuad - 0
[dshow @ 000001aeac2a96c0] Could not find video device with name [AJA
  S-Capture Kona3GQuad - 0] among source devices of type video.
video=AJA S-Capture Kona3GQuad - 0: I/O error

Have any of you already encountered this issue, and if so could you point me in the right direction
Thanks and take care during these stressful times

A: The symptoms you mention indicate a problem in AJA Kona3G driver (actually, not even a driver per se but it's DirectShow integration implemented as a custom AJA DirectShow filter).
The system has this integration but it is either broken or out of date and so you see the DirectShow API issue coming from third party component and forwarded to FFmpeg.
You need to have AJA stuff re-installed and/or contact their support for a solution.
It is not really a programming question.


Q: I need a way to make sure that words that are given to an array are real words.(RTP-hsa,console) I solved the issue with making sure that only letters in the array are used, now I need a way to import or load a dictionary into the console so fake words can't be used. I had the idea of finding a txt document and load it into an array when the program starts, but I haven't had any luck finding one. If anyone finds a way, please provide a good description of how to load it into the hsa.console form. Thanks. (Java Ready to Program hsa.console)

A: Here is some that solves the does a word exist.  I wasn't sure how you were storing the array of characters so I guessed it was a 2d array of chars.  The method wordExists is the one used to check if the word exists.  I used a test to check that it worked and it did on multiple inputs. Edit: I just realized that this could cause the words to cycle back onto itself if its a palindrome, ill post the fixed code as soon as I make it
public static boolean wordExists(char[] [] characters, String word)
{
    char[] word_as_char = word.toCharArray();
    for (int i = 0; i < characters.length; i++)
    {
        for (int j = 0; j < characters[0].length; j++)
        {
            boolean wordExists = checkWord(characters, word_as_char, 0, i, j);
            if (wordExists)
            {
                return true;
            }
        }
    }
    return false;
}

public static boolean checkWord(char[] [] characters, char[] word, int index, int x, int y)
{
    boolean wordExists = false;
    if (index < word.length) {
        if (characters[x] [y] == word[index])
        {
            if (x + 1 < characters.length)
            {
                wordExists = wordExists | checkWord(characters, word, index + 1, x + 1, y);
            }
            if (x - 1 > 0)
            {
                wordExists = wordExists | checkWord(characters, word, index + 1, x - 1, y);
            }
            if (y + 1 < characters[0].length)
            {
                wordExists = wordExists | checkWord(characters, word, index + 1, x, y + 1);
            }
            if (y - 1 > 0)
            {
                wordExists = wordExists | checkWord(characters, word, index + 1, x, y - 1);
            }
        }
    }
    if (index == word.length - 1 && characters[x] [y] == word[index])
    {
        wordExists = true;
    }
    return wordExists;
}

}

A: CheckLetter != (" ") doesn't check content equality, it checks reference equality - are these 2 variables referring to the same object. Use !" ".equals(CheckLetter). Better yet, don't use String for holding single characters, there is char for this and there is Character class that has some methods for handling them (like toUpperCase).


Q: Using the '-' sign in jQuery Selector gives error I am trying the run the following code:
$(document).ready({

    $("#menu-nav a").hover(
         function () {
           $(this).css ( marginRight: '20px' );
         },
         function () {
            $(this).css ( marginRight: '10px' );
         }
     );

}); //end ready

But, my dreamweaver reports and error on the line $("#menu-nav a").hover(. Is it okay to use the selector as #menu-nav a or should it be something else ?

A: The problem is instead of this:
$(document).ready({

You need this:
$(document).ready(function () {

I am sure you knew that, but it's easy to overlook since the error is shown to be in the following line.

Another issue:
I think you will also run into problems here:
 $(this).css ( marginRight: '20px' );

Per the jQuery docs, you should use this:
 $(this).css ('margin-right', '20px');

An alternative:
Here's one more thing, just to give a complete answer. As is noted in the comments, you really don't need jQuery at all for this, if you don't want to use it. Try this:
#menu-nav a:hover { margin-right: 20px; }

You can add whatever styles you want like that.

A: In your example
$(document).ready({...});

should be
$(document).ready(function(){
    //...
});

And also change
$(this).css ( marginRight: '20px' );

to
$(this).css('marginRight','20px');

or
$(this).css({'marginRight':'20px'});

in both lines

A: You don't pass an object, so you cannot use property: value, you can code:
$(this).css({ marginRight: '20px'});

or:
$(this).css( 'marginRight', '20px' );

A: I use this convention to avoid getting lost and confused in a myriad of brackets and parenthesis:
$(document).ready(DocReady);

function DocReady()
{
       // More code here
}

An advantage is that you can also call the DocReady function from a button click (maybe to test it).


Q: Use a crawled/mapped property to search I've created a site column which has a crawled and managed property.  The site column name is for example: DocType.  If I search for DocType:Memorandum, it show in the results all files that have DocType as Memorandum.
But I want to create a search functionality/screen/web part (I don't know) that displays 'Document Type' with a field next to it.  And when the user enter "Memorandum" in the field and click search, it should search through the site where DocType:Memorandum.
So basically I want to make the search functionality easier for the end user, not to have to remember the name of the mapped properties, but rather just type in the phrase and search should know to search for DocType=Memorandum.  I hope I make sense?

A: One idea would be to use a resultpage instead of a web part and modify the refinement panel.
It is very easy to get the managed property as a refinement value with just editing the panel and adding the property (https://blogs.technet.microsoft.com/sharepoint_made_easy/2013/03/19/step-by-step-configuration-to-add-custom-refiners-in-the-refinement-panel-of-search-results-page-for-sharepoint-online/)
You could also modify the behavior and displayed information by writing your own refiner control template in html / JS (good tutorial could be found here https://www.eliostruyf.com/part-1-create-first-search-refiner-control-template/).
The major drawback would be, that the user has to issue a query first, and then choose to refine for the contenttype after seeing the "unfiltered" results.
It depends on how many different types should be searchable, but you could also create a web part with a search input to type and a choice / button segment beneath it. Depending on the button /choice clicked by the user you add that "refinement" to the query before sending it back.


Q: Proper mass and space-time wrap question I still haven't tackled GR equations because I still don't have the mathematical tools, but that didn't stop me from looking into it. I have a question and was hoping someone would clear things up for me. Tell me if I made a mistake along the way:

*

*As far as I know the metric tensor is invariant meaning the curvature of space looks the same for all frames.

*I think that means that "relativistic mass" doesn't determine the curvature but the rest mass does.

*The rest mass is the total internal energy in the object divided by $c^2$. right? My mass is basically the energy of the particles in my body.

*So I concluded that even if I speed up and move at high speed I won't curve space any further than I did when I'm at rest. Otherwise if I get real close to light speed I would eventually would turn into a black hole.

*Photons do not have rest mass, but you can put a photon in a mirror box (0 mass) and see that the mass of the box would turn out to be $hf/c^2$.
Here is my question: I've read everywhere that photons do in fact bend space and contribute to the stress tensor, very very very little tho, so how can that be possible if their rest mass is zero? Are massless objects treated differently because their rest frame of reference is kinda weird?

A: Nice question. I'll try to answer, but as always the sad truth (or happy truth, that's up to you) is that to fully understand these things you just gotta learn the math.
This question is a bit tough to answer because the metric is not invariant, it's covariant. What this means is that in a given coordinate system the metric is represented as a matrix, and the components of this matrix depend on your coordinates, even if the metric tensor as a mathematical object doesn't. This is much like how you can think of a vector as something that exists independently of the frame, but if you want its components, they do depend on the frame.
The reason this makes the question hard to answer is that "curvature" is not a coordinate independent number. There are some scalar (i.e. invariant) quantities you can form like the Ricci scalar $R$ or the Kretchmann scalar $R_{abcd} R^{abcd}$, but these don't tell the whole story. In other words, there isn't an unambiguous "curvature" which you can use to say that this place has high curvature and that place has low curvature.
Now to your question: what determines curvature is the energy momentum tensor. This includes the energy density and also the momentum density/energy flow and the pressure. For a point particle the energy density is the relativistic mass, so your speed does matter if you want to calculate the metric tensor. Similarly, it doesn't matter that light is massless, because we care about its energy and momentum, not its mass.
The conclusion here is that the curvature tensor is, in a sense, dependent on the frame. However, some things are not dependent of the frame. For example, the formation of a black hole. If you're not a black hole when standing still then you're not going to become one when moving, because of relativity. Even though your energy increases, everything works out in such a way that the formation of a black hole depends only on invariant quantities.


Q: How to fetch Images from server Using API and push in Array I want to fetch images from my server using API and then I want to push in array so that I can show this images in loop or as slideshow, I have page named common service where I  have mentioned image API url. now I just want to know how to get it in my component.ts and want to push in array.
I am Using Angular 4
I have tried to create a function in .ts to get images  but not working.
common.service.ts
this.surveyImageUrl = this.authService.website_url + '/SurveyImages/';

here i tried to get images in ts.file
optionimage: any[] = [{}];
surveyImageUrl = function () {
    debugger;
    this.commonService.surveyImageUrl().subscribe(data => {
        if (data.success) {
            data.survey.array.forEach(element => {
                var obj = {
                    is_optionimages: true,
                    surveyImage: element.surveyImage,
                }
                this.optionimage.push(element);
            });
        }
    });
}

Just want to get images then want to push in array and want to display in HTML page as loop.

A: Try this
    optionimage: any[] = [];
    surveyImageUrl = function () {
    debugger;
    this.commonService.surveyImageUrl().subscribe(data => {

      if (data.success) {
        data.survey.array.forEach(element => {
          var obj = {
            is_optionimages: true,
            surveyImage: element.surveyImage,

          }
          this.optionimage.push(obj);
        });

      }

    });
  }

Then you can bind your image urls to View as below.
<div *ngFor="let image of optionimage">
<img [src] = "image.surveyImage"/>
</div>


Q: cross fading multiple images gallery autoplay id lke to create a fixed gallery as a background on my main page, cross fadinging 90 pictures in autoplay... and i get the code but when im gonna preview, theres a lot of glitch and not working as expected.... as you can see here
i did this code with js but i dont know why its glitching ...
anyone can help to understand this prob?
thanks so much
i got this code:
HTML

CSS:
@keyframes fadey {
    0% {
    opacity: 1; }
    16.66% {
    opacity: 1; }
    25% {
    opacity: 0; }
    91.66% {
    opacity: 0; }
    100% {
    opacity: 1; }
}

#fadey {
        position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    width: 100%;
      height: 100vh;

    max-height: 100vh;
}

#fadey img {
  display: block;
  width: 100%;
  font-size: 0;
}

and JS:
var cssFadey = function(newOptions) {
    var options = (function() {
        var mergedOptions = {},
        defaultOptions = {
            presentationTime: 25,
            durationTime: 15,
            fadeySelector: '#fadey',
            cssAnimationName: 'fadey',
            fallbackFunction: function() {}
        };
        for (var option in defaultOptions) mergedOptions[option] = defaultOptions[option];
        for (var option in newOptions) mergedOptions[option] = newOptions[option];
        return mergedOptions;
    })(),
    CS = this;
    CS.animationString = 'animation';
    CS.hasAnimation = false;
    CS.keyframeprefix = '';
    CS.domPrefixes = 'Webkit Moz O Khtml'.split(' ');
    CS.pfx = '';
    CS.element = document.getElementById(options.fadeySelector.replace('#', ''));
    CS.init = (function() {
        if (CS.element.style.animationName !== undefined) CS.hasAnimation = true;
        if (CS.hasAnimation === false) {
            for (var i = 0; i < CS.domPrefixes.length; i++) {
                if (CS.element.style[CS.domPrefixes[i] + 'AnimationName'] !== undefined) {
                    CS.pfx = domPrefixes[i];
                    CS.animationString = pfx + 'Animation';
                    CS.keyframeprefix = '-' + pfx.toLowerCase() + '-';
                    CS.hasAnimation = true;
                    break;
                }
            }
        }
        if (CS.hasAnimation === true) {
            function loaded() {
                var imgAspectRatio = firstImage.naturalHeight / (firstImage.naturalWidth / 100);
                var imageCount = CS.element.getElementsByTagName("img").length,
                totalTime = (options.presentationTime + options.durationTime) * imageCount,
                css = document.createElement("style");
                css.type = "text/css";
                css.id = options.fadeySelector.replace('#', '') + "-css";
                css.innerHTML += "@" + keyframeprefix + "keyframes " + options.cssAnimationName + " {\n";
                css.innerHTML += "0% { opacity: 1; }\n";
                css.innerHTML += (options.presentationTime / totalTime) * 100+"% { opacity: 1; }\n";
                css.innerHTML += (1/imageCount)*100+"% { opacity: 0; }\n";
                css.innerHTML += (100-(options.durationTime/totalTime*100))+"% { opacity: 0; }\n";
                css.innerHTML += "100% { opacity: 1; }\n";
  css.innerHTML += "}\n";
                css.innerHTML += options.fadeySelector + " img { position: absolute; top: 0; left: 0; " + keyframeprefix + "animation: " + options.cssAnimationName + " " + totalTime + "s ease-in-out infinite; }\n";
              css.innerHTML += options.fadeySelector + "{ box-sizing: border-box; padding-bottom: " + imgAspectRatio + "%; }\n";
              for (var i=0; i < imageCount; i++) {
                css.innerHTML += options.fadeySelector + " img:nth-last-child("+(i+1)+") { " + keyframeprefix + "animation-delay: "+ i * (options.durationTime + options.presentationTime) + "s; }\n";
                }
            document.body.appendChild(css);
        }
        var firstImage = CS.element.getElementsByTagName("img")[0];
        if (firstImage.complete) {
            loaded();
        } else {
            firstImage.addEventListener('load', loaded);
            firstImage.addEventListener('error', function() {
                alert('error');
            })
        }
    } else {
        // fallback function
        options.fallbackFunction();
        }
    })();
}
cssFadey();


Q: Can I judge my status by android sensor, moving or motionless? we can do many things by android sensor.  However, can I judge my status, such as moving, motionless.

A: The simplest way is to use Activity Recognition API  http://developer.android.com/training/location/activity-recognition.html .
Or you could read raw data from sensors to recognize patterns. But eventually you'll come the same functionality.


Q: How to detect colors one at a time I need to detect two colors, one after one.
So this is an example of my program workflow:
detect and object with a specific color, after that object is close enough(specified how much) to the camera, the program should try to start looking for another color.
this what i tried so far
# All python's imports

vs = VideoStream(src=0).start()
# Defining the two colors bound
blueLower = np.array([110, 50, 50])
blueUpper = np.array([130, 255, 255])

greenLower = np.array([29, 86, 6])
greenUpper = np.array([64, 255, 255])

# Defining a function to start the loop so i can later rerun it with different color bounds
def loop(lower, upper):

    while True:
    ....
    ....

# If the object is close enough, change the loopj arguments to search for a new color
    if radius > 250:
      loop(greenLower, greenUpper)

What happens, is when the radius is bigger than 250, it just reruns the original

A: You can achieve this with itertools that is in the standard library (you do not need to install, just import). Although there are other ways you can toggle between values, this one is convenient. I changed some parts of you code, you can let me know if theres something you do not understand.
import itertools

blueLower = [110, 50, 50]
blueUpper = [130, 255, 255]

greenLower = [29, 86, 6]
greenUpper = [64, 255, 255]

greenBounds = (greenLower, greenUpper)
blueBounds = (blueLower, blueUpper)

def loop(colorBounds, iterator):
    radius = 0
    lower, upper = colorBounds
    print(lower, upper)
    while True:
        radius += 1
        if radius > 250:
            loop(iterator(), iterator)

toggle = itertools.cycle([greenBounds, blueBounds]).__next__
loop(greenBounds, toggle)

To clarify, I added radius=0 and radius += 1 for my own testing purposes.


Q: Error in subset "incorrect number of dimensions" when using "last" and "lag" After downloading stocks data using Quantmod package I want to subset the data and also compare the last row data in the xts with the previous row  using (last / lag).
First I created a function to classify the volume in its quartile.
Second I create a new dataset to filter out which stocks in the list get yesterday a volume of 3(3rd quartile) = "stocks_with3"
Now I'd like to subset again the newly created "stocks_with3" dataset.
Specifically what I'm trying to get is TRUE/FALSE of comparing the "Open" of Yesterday (using last) and the "Close" of before yesterday "(using lag).
Exactly what I'm trying to get is if the "Open" was less or equal than the "Close" before yesterday of the stocks that yesterday had a volume in the 3rd quartile.
But when running the subset I'm getting an error message: "incorrect number of dimensions"
My approach for the subset is using last(to get the last available data in the xts) and lag ( to compare it with the immediately previous row)
#Get stock list data

library(quantmod)
library(xts)
Symbols <-   c("XOM","MSFT","JNJ","IBM","MRK","BAC","DIS","ORCL","LW","NYT","YELP")
start_date=as.Date("2018-06-01")
getSymbols(Symbols,from=start_date)

stock_data = sapply(.GlobalEnv, is.xts)

all_stocks <- do.call(list, mget(names(stock_data)[stock_data]))

#function to split volume data quartiles into 0-4 results

Volume_q_rank <- function(x) {
stock_name <- stringi::stri_extract(names(x)[1], regex = "^[A-Z]+")
stock_name <- paste0(stock_name, ".Volqrank")
column_names <- c(names(x), stock_name)
x$volqrank <- as.integer(cut(quantmod::Vo(x),
                                  quantile(quantmod::Vo(x),probs=0:4/4),include.lowest=TRUE))
x <- setNames(x, column_names)return(x)
}

all_stocks <- lapply(all_stocks, Volume_q_rank)

#Create a new dataset using names and which with stocks of Volume in the 3rd quartile.

stock3 <- sapply(all_stocks, function(x) {last(x[,         grep("\\.Volqrank",names(x))]) == 3})

stocks_with3 <- names(which(stock3 == TRUE))

#Here is when I get the error.

stock3_check <- sapply(stocks_with3, function(x) {last(x[,    grep("\\.Open",names(x))]) <= lag(x[, grep("\\.Close", 1), names(x)])})

#Expected result could be the same or running this for a single stock but applied to all the stocks in the list:

 last(all_stocks$MSFT$MSFT.Open) <= lag(all_stocks$MSFT$MSFT.Close, 1)

#But I'm having the error when trying to apply to whole list using "sapply" "last" and "lag"

Any suggestion will be appreciated.

Thank you very much.

A: You have 2 mistakes in your sapply function. First you are trying use a character vector (stock_with3) instead of a list (all_stocks). Second the function used inside the sapply is incorrect. the lag closing bracket is before the grep.
This should work.
stock3_check <- sapply(all_stocks[stocks_with3], function(x) {
  last(x[, grep("\\.Open", names(x))]) <= lag(x[, grep("\\.Close", names(x))])
  })

additional comments
I'm not sure what you are trying to achieve with this code. As for retrieving your data, the following code is easier to read, and doesn't first put all the objects in your R session and then you putting them into a list:
my_stock_data <- lapply(Symbols , getSymbols, auto.assign = FALSE)
names(my_stock_data) <- Symbols


Q: gradle exclude external resource folder from all jars Using gradle 5.4 with a project dependency from external folder in a netbeans project.
The external folder contains resources like images, xml and custom objects that can only be created by this netbeans project. These external assets are then used to create binary files that get packed into a separate jar by that netbeans project.
These same external resources are also used during runtime for development in the gradle project. While I need the resources for development in the gradle project, I do not need or want them to be included in any jars anywhere for any reason when using the task build command because only the binaries are needed for distribution.
How to exclude the external resources from any and all jar files in the gradle project but allow them to be used for the classPath so I can run the project?
Some code examples of failure.
apply plugin: 'java'
apply plugin: 'application'
apply plugin: 'idea'

sourceSets {
   main {
      resources {
         srcDir '../ExternalResourceFolder/assets'
      }
   }
}

jar {
    exclude('../ExternalResourceFolder/assets/**')
}

dependencies {
    runtimeOnly files('../ExternalResourceFolder/assets')
}

jar {
    exclude('../ExternalResourceFolder/assets/**')
}

distributions {
    main {
        contents {
            exclude '../ExternalResourceFolder/assets/**'
        }
    }
}

Tried many more things like adding to classPath and exclude but it would just be clutter to add them. Changing from sourceSet to dependency only moves the problem around from "build/lib" folder to "build/distributions" folder.

A: Had to exclude per file type in the end.
    sourceSets {
    main {
        resources {
            srcDir '.'
            exclude ('**/*.j3odata','**/*.mesh','**/*.skeleton',\
                    '**/*.mesh.xml','**/*.skeleton.xml','**/*.scene',\
                    '**/*.material','**/*.obj','**/*.mtl','**/*.3ds',\
                    '**/*.dae','**/*.blend','**/*.blend*[0-9]','**/*.bin',\
                    '**/*.gltf')
        }
    }
}


Q: preparing a private message system I am working on preparing a private message system
the problem is here and now that it will only show one even though there are 4 into the database.
I want it to display all 4 at once, not just one of them.
The problem can be seen here
http://billedeupload.dk/?v=rXFTj.png
$sql = "SELECT id, title, datoTime, checkpm FROM pm WHERE til=? ORDER BY datoTime DESC";
    if ($stmt = $this->mysqli->prepare($sql))
    {
    $stmt->bind_param('i', $til);
    $til = $_GET["id"];

    $stmt->execute();
    $stmt->store_result();
    $stmt->bind_result($id, $title, $datoTime, $checkpm);
    $stmt->fetch();
    $count = $stmt->num_rows;
    $stmt->close();

        if($count >= 1)
        {
            ?>

                <a href="/pm-set/<?php echo $id;?>/"><?php echo $title;?>

                <?php
                if($checkpm == 0)
                {
                ?>
                <a href="/pm-set/<?php echo $id;?>/">
                <?php
                }
                else
                {
                ?>
                <a href="/pm-set/<?php echo $id;?>/">
                <?php
                }
                ?>

                <?php echo date("H:i - d, M - Y", strtotime($datoTime));?>
                Slet

            <?php
        }
        else
        {
            ?>

Ingen besked

            <?php
        }
    }
    else
    {
        echo 'Der opstod en fejl i erklæringen: ' . $this->mysqli->error;
    }

A: At the moment you read one line and then close the result.
You need to loop through the results reading and processing one line at a time and then only once you are done close the result.


Q: MYSQL select 3 results of each "page id" I have two tables... the first is a page list with (page_id, page_title) rows.  The second is a list of items ON those pages each with a price (item_id, page_id, item_title, item_price).
I'd like to grab the top three items from each page (ordered by highest item_price first) with the page having the cumulatively highest price ordered first.  This is quite beyond my MYSQL abilities and I'm looking for advice on how to make this the most efficient! :)  Thanks!

A: You could do this a few different ways. What I would do is run one query that says "get me all pages ordered by the sum total of their items" then loop through them in php, and for each one, do a "get me the top 3 items for the current page".
Make sense?
Query one (untested, written on my phone):
SELECT p.page_name, (SELECT SUM(item_price) FROM items WHERE page_id = p.page_id) AS cumulative_price FROM pages p ORDER BY cumulative_price DESC;

Query two (also untested) looping through results of query one:
SELECT * FROM items WHERE page_id = '$currentPageId' ORDER BY item_price DESC LIMIT 3;

A: *

*I'm assuming every page_id is equal to item_id, and that's how they're linked together. (If not, please correct me.)

*I'm just going to call the second table "table2" and the item_id I'm looking up "SOME_ITEM_ID"
SELECT * FROM `table2` WHERE `item_id` = 'SOME_ITEM_ID' ORDER BY `item_price` DESC;

In English what this is saying is:
Select everything from table2 where the item_id is this, and order the list by item_price in descending order
This SQL statement will return every hit, but you would just output the first three in your code.

A: My gut tells me that there is probably no faster way to do this than to do a for-loop in the application over all of the pages, doing a little select item_price from item where page_id = ? order by item_price desc limit 3 for each paqe, and possibly sticking the results in something like memcached so you aren't taxing your database too much.
But I like a challenge, so i'll attempt it anyhow.
SELECT p1.*, i1.*,
 (SELECT count(*)
  FROM items i2
  WHERE i1.item_price < i2.item_price
  AND p1.page_id = i2.page_id) price_rank,
FROM pages p1
LEFT OUTER JOIN items i1
 ON p1.page_id = i1.page_id
WHERE price_rank < 3;

That odd sub-select is going to probably do an awful lot of work for every single row in items.  many other RDBMses have a feature called window functions that can do the above much more elegantly.  For instance, if you were using PostgreSQL, you could have written:
SELECT p1.*, i1.*,
    RANK(i1.item_price)
    OVER (PARTITION BY p1.page_id
          ORDER BY i1.item_price DESC) price_rank
FROM pages p1
LEFT OUTER JOIN items i1
 ON p1.page_id = i1.page_id
WHERE price_rank <= 3;

And the planner would have arranged to visit rows in an order that results in the rank occurring properly.


Q: Why is my basic Ajax script not working? I have been playing around with Javascript and now I came to Ajax. I am trying to write very simple script that would get the file contents - print the txt file contents in the div with id=test. This is the script :
function loadXMLDoc(url)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("GET" , url ,false);
    xmlhttp.send(null);
    document.getElementById('test').innerHTML = xmlhttp.responseText;
}

when I use it on this website :
<div id="test"  name="test"> HELLo </div>
<button type="button" onclick="loadXMLDoc('test1.txt')">ClickMe1</button>

With this script HELLo is substituted by nothing - the script empties the container.
Maybe I am missing something trivial but do I need PHP installed ? I don't think so but... I am not sure what is happening in here. When I am debugging the xmlhttp is empty the whole time. Why ?

A: You'll need to check for readyState and the HTTP response status before replacing the text;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("test").innerHTML=xmlhttp.responseText;
    }

example on http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
Please let me know if it works.

A: For browsers other than IE
IE's active X object seems not to care much about the ready state, other browsers may not have the text loaded quickly enough at the time you run your function (hence why you are getting the blank instead of file contents).  IE's active X seems to handle this automatically and ignores the ready state, so you have to break up the code differently as below.  Normally you check the status of the request to see if it's been fully read or not before accessing the responseText.
Add onreadystatechange you cannot check the status attribute since there is no HTTP requests being made on a file system request.  (The status will always be 0 for request not made via HTTP) The best I can offer is this:
function loadXMLDoc(url)
{
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
        document.getElementById('test').innerHTML = xmlhttp.responseText;
        }
       xmlhttp.open( "GET", url );
       xmlhttp.send(null);

    }
    else
    {// code for IE6, IE5
       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

       xmlhttp.open( "GET", url );
       xmlhttp.send(null);
       document.getElementById('test').innerHTML = xmlhttp.responseText;
    }

}

For CHROME
If you are using CHROME you must start chrome up with the --allow-file-access-from-files switch.  Otherwise, it will refuse file system ajax requests.  (You will have to set this even if using a so-called "easier" library such as jQuery).
Running AJAX apps on File System In General
Not usually a good idea, a lot of caveats to this route.  Typically local development is done with a web server installed to localhost on your development machine.

A: Today its old fashion to call ajax like xmlhttp = new XMLHttpRequest();
You have many other options for this.

*

*http://api.jquery.com/jQuery.ajax/

*http://www.w3schools.com/jquery/jquery_ref_ajax.asp

*http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

A: Firstly, you have to fight with Same Origin Policy.
A simple working code for a synchronous request is following:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {

if (req.status == 200 && req.readyState == 4) {
    ...
}

req.open('GET', url, true);
req.send(null);

Note this is working for Firefox/Opera/Chrome. If IE, use:
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

A: Try with jQuery. Download the last version here and write this code snippet:
function loadXMLDoc(url) {
  $("#test").load(url);
}

It's much simpler and less error prone

A: You need a server to listen up to requests. Your regular file system will not be able to respond to AJAX requests.
You don't need PHP, however you'll need apache or a similar web server.


Q: Collecting names/ids of failing items in Camel I would like to implement an aggregator-splitter pattern using Camel where I process a list of files. removeOnFailure(true) would help remove files that would cause/trigger a failure from the list and the process will complete successfully as shown in the code below.
def files(exchange: Exchange): java.util.Iterator[Path]
def fileProcessor(exchange: Exchange): Unit

from(aDirectEndpoint) ==> {
    aggregate(
      split(files _)
        .streaming
        .parallelProcessing
        .idempotentConsumer(_.in)
        .eager(true)
        .skipDuplicate(true)
        .repository(aRepository)
        .removeOnFailure(true)
        .process(fileProcessor _),
      new GroupedExchangeAggregationStrategy
    )
    .completionTimeout(completionTimeoutMillis)
    .process(jobProcessor)

I'm wondering if there is a way to collect those failing files using Camel API?


Q: How to append to the beginning of an int in Python? First of all, is it possible to append to an int ? If not I guess i'll have to convert it to a string first. I know how to append to a list
Anyways, how would you append a digit to the beginning of a number(instead of appending it to the end). Say number = 345, and you'd like to append super which is equal to 2 to the beginning of "number" to make it "2345".
How would you do it ?
To append it to the end of a list i'd use:
alist.append("hello")

A: To "append" to numbers, you need to convert them to strings first with str(). Numbers are immutable objects in Python. Strings are not mutable either but they have an easy-to-use interface which makes it easy to create modified copies of them.
number = 345
new_number = int('2' + str(number))

Once you are done editing your string, you can easily convert it back to an int with int().
Note that strings don't have an append method like lists do. You can easily concatenate strings with the + operator however.

A: As @Fredrik comments, you can get from any integer to any other integer by a single addition - and this is how you should probably do it, if you deal with integers only.
>>> i = 345
>>> 2000 + i
2345

There are, however,  many way to express "prepend a 2 to 345", one would be to use format:
>>> '2{}'.format(345)
'2345'


Q: Accessing an element in django (for) I have a Django template with the following code which creates multiple buttons and tries to hide/show description text on a click (on the same button in each card):
{% for comida in comidas %}

            {% if comida.slug_food == page.slug  %}

{{comida.titulo}}

{{comida.precio|floatformat:"-1"}}€

                <button class="button" onclick="showDescription()">ver+

                {{comida.descripcion|safe}}

                </button>

AÑADIR AL PEDIDO

                {% if comida.imagen != null %}

                {% endif %}

                {% endif %}

        {% endfor %}

where comidas is a list of strings, and later in the script block I have
function showDescription(){
    var showText = document.getElementById("food-description");
    if (showText.style.display === "block"){
        showText.style.display = "none";
    } else {
        showText.style.display = "block";
    }
}

The function runs, but as you may expect, it runs only on the first element of my for loop.
My question is ¿anyone can help me? i want work all my buttons and not only the first element.

A: Use {{comida.id}} to get unique ids :
{% for comida in comidas %}

    {% if comida.slug_food == page.slug  %}

{{comida.titulo}}

{{comida.precio|floatformat:"-1"}}€

        <button class="button" onclick="showDescription('{{comida.id}}')">ver+

        {{comida.descripcion|safe}}

        </button>

AÑADIR AL PEDIDO

        {% if comida.imagen != null %}

        {% endif %}

    {% endif %}

{% endfor %}

And javascript :
function showDescription(comidaId){
    var showText = document.getElementById("food-description-" + comidaId);
    if (showText.style.display === "block"){
        showText.style.display = "none";
    } else {
        showText.style.display = "block";
    }
}


Q: Visual Studio 2015 Xamarin freezing I have an Android app on Visual Studio 2015 with Xamarin and it is freezing frequently.
The only scenario I can reproduce every time is right after deploy. VS freezes right after the app is deployed on emulator or device. The app works fine, but the VS stands frozen for several seconds. It also freezes in other scenarios too.
VS doesn't show the "not responding" message no matter what I do. It seems like it's doing some background work and it's not really frozen, but I can't figure out what the problem is.
I recreated my project from scratch and the problem started to happen again when I added my resources and installed some NuGet packages (appcompat v7 and firebase cloud messaging).
I'm guessing it's somehow related to VS not recognizing some attributes in some layout files, like
.
1 - Any help on the freezing problem?
2 - What can I do to VS recognize those attributes?
3 - Can I configure the resources.cs to be regenerated only on build?
Update
Found this, but didn't worked for me!
Update 2
Ok, now I'm 100% sure the problem is with the generation of android resources. The aapt.exe is the villain of this history, but I still can't make it stop executing and freezing Visual Studio every time. Is there some setting to ignore xml errors on layout files or something like that?

A: I am the guy who created the bugzilla post you are referencing.
Are you sure you have the <AndroidResgenExtraArgs>--no-crunch </AndroidResgenExtraArgs> on the right place? It must be inside the configuration you are using, i.e. the .csproj must be like this if you are deploying in Debug | AnyCPU configuration:
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<AndroidResgenExtraArgs>--no-crunch </AndroidResgenExtraArgs>

(also notice the trailing space after --no-crunch)
BTW I also have trouble with aapt.exe when installing Nugets and --no-crunch does not help with this. What helps is temporarily renaming aapt.exe to aapt2.exe - Visual Studio does not run the aapt process, because it can't find the exe file and Nuget installations are fast. But this would probably not work for build and deploy, I think it throws an error.

A: Well, after trying a lot of stuff I made a lucky guess and it worked.
I was looking to my csproj and noticed some weird things, like:
<ItemGroup>
    <AndroidResource Include="Resources\layout\onefile.axml" />
</ItemGroup>
<ItemGroup>
    <AndroidResource Include="Resources\layout\anotherfile.axml" />
</ItemGroup>
<ItemGroup>
    <AndroidResource Include="Resources\layout\onemorefile.axml">
        <SomeOtherAttributes />
    </AndroidResource>
</ItemGroup>

So I imagined that organizing the ItemGroups would worth a try and put all ItemGroups (class, layout, image, string, etc) together like:
<ItemGroup>
    <AndroidResource Include="Resources\layout\onefile.axml" />
    <AndroidResource Include="Resources\layout\anotherfile.axml" />
    <AndroidResource Include="Resources\layout\onemorefile.axml" />
</ItemGroup>

And it worked beyond what I expected. Not only fixed my freezing problems... it made VS faster than before of my freezing problems... REALLY faster!
I don't know if reorganizing the csproj file can cause any kind of problems, but I'll do the same with other projects and see what happen.
I did a quick research about csproj and ItemGroup and found nothing relevant... I believe it's kind a bug!


Q: No value given for one or more required parameters. c# oledb Not sure where the problem is. No value given for one or more parameters. I've tried moving the code out of the if statements but it hasn't helped. Not sure if the data adapter requires me to enter all of the column values.
        int ID = Convert.ToInt32(txtStudent.Text);
        string grade = "A";
        int result = Convert.ToInt32(txtResult.Text);

        string sql = "UPDATE Student SET grade=@grade WHERE ID = ?";

        OleDbCommand command = new OleDbCommand(sql, connectionString);

        if ((result >= 70) && (result <= 100))
        {
            grade = "A";
            MessageBox.Show("Result is: A");

            command.Parameters.Add("@grade", OleDbType.VarChar).Value = grade;
            command.Parameters.Add("@ID", OleDbType.VarChar).Value = ID;

        }

        else if ((result >= 60) && (result < 70))
        {
            grade = "B";
            MessageBox.Show("Result is: B");

            command.Parameters.Add("@grade", OleDbType.VarChar).Value = grade;
            command.Parameters.Add("@ID", OleDbType.VarChar).Value = ID;
        }

        else if ((result >= 50) && (result < 60))
        {
            grade = "C";
            MessageBox.Show("Result is: C");

            command.Parameters.Add("@grade", OleDbType.VarChar).Value = grade;
            command.Parameters.Add("@ID", OleDbType.VarChar).Value = ID;
        }

        else if (result < 50)
        {
            grade = "F";
            MessageBox.Show("Result is: F");

            command.Parameters.Add("@grade", OleDbType.VarChar).Value = grade;
            command.Parameters.Add("@ID", OleDbType.VarChar).Value = ID;
        }

        else
        {
            MessageBox.Show("Incorrect data entered");
        }

        OleDbDataAdapter dataadapter = new OleDbDataAdapter(command);

        DataSet ds = new DataSet();

        dataadapter.Fill(ds, "Student");
        dataGridView1.DataSource = ds;
        dataGridView1.DataMember = "Student";

A: I think the problem on that line;
OleDbDataAdapter dataadapter = new OleDbDataAdapter(sql, connectionString);

You add your parameters on your command but you still using sql string which expects parameter and their values in OleDbDataAdapter constructor.
Use your command instead of your sql query;
OleDbDataAdapter dataadapter = new OleDbDataAdapter(command, connectionString);

And use using statement to dispose your OleDbConnection, OleDbCommand and OleDbDataAdapter automaticaly.
As your second problem, from the documentaion of OleDbCommand.Parameters:

The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text.

Actually, it does support named parameters but names are negligible. Only matter is your parameter orders. Since you add @ID parameter your command first, this will be added to your first parameter in your command that you defined which is @grade. As you can see, this will generate a problem.
Change your parameters order as well;
command.Parameters.Add("@grade", OleDbType.VarChar).Value = grade;
command.Parameters.Add("@ID", OleDbType.VarChar).Value = ID;