text:
Q: unable to set header in php and send email from cpanel I am unable to set header in php for from address I have tried all possible values :
The code below is correct but code is not attached to header .
It shows this as default from but does not change.
From :  webhost:cpanel@hosting

Is this the problem with cpanel ?
Please help me out really appreciate the help.
Thanks in Advance.
<?php

$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
$phone = $_REQUEST['contact'];

$subject = "feedback";
$question = $_REQUEST['question'];

$body = "

";
$mime_boundary = "<<<--==+X[".md5(time())."]\r\n\r\n";
$headers = "MIME-Version: 1.0"."\r\n" ."Content-Type:text/html;"."\r\n";
$headers .= 'From:'.$email. "\r\n";

$to ='example@example.com';
mail($to,$subject,$body,$headers);
echo "";

?>

also tried :
<?php
$headers   = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: Sender Name <sender@domain.com>";
   $headers[] = "Reply-To: Recipient Name <receiver@domain3.com>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();

mail($to, $subject, $email, implode("\r\n", $headers));
?>

Only this works:
    $to ='example@example.com';
$subject="subject";
$body="body";
    $mime_boundary = "<<<--==+X[".md5(time())."]\r\n\r\n";
    $headers = "MIME-Version: 1.0"."\r\n" ."Content-Type:text/html;"."\r\n";
    mail($to,$subject,$body,$headers);

A: try this :
$to = 'me@gmail.com';

$subject = "Email from me by: John";
$body = "my body";
$headers = "From: "."hello@world.com"."\r\n" .
"Reply-To: "."hello@world.com"."\r\n".
 "X-Mailer: php";
 $sent=mail($to, $subject, $body, $headers);

if ($sent) {

 echo "good!";

} else {
echo("
Message delivery failed...
");
}


text:
Q: NodeJS FTP not throwing error when trying to delete non-existent file I am working with ftp-npm and I am currently facing a weird bug...
I have a method called refreshStore that contains this part of code :
c.delete('/pathToMyFileOnFTPServer', function(err) {
            console.log('117');
            if (err) throw err;
          });

This is not throwing error and even not logging the '117' string even though my file does not exist on the server... Why is this like this ?
Thanks all!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Появление ошибки tshark: Syntax error near ">" при попытке запуска с параметрами В данном коде я пытаюсь запустить tshark с параметрами, которые изначально вписываются в консоль. в итоге я должен получить *.txt файл. После "1>" в консоли записывается директория и название файла. Но после запуска команды tshark ругается на синтаксическую ошибку
using System;
using System.IO;
using System.Diagnostics;

//Запуск Tshark с заданными параметрами
Process LaunchTshark = new Process();
ProcessStartInfo LaunchInfoTshark = new ProcessStartInfo();
LaunchInfoTshark.FileName = @"C:\Program Files\Wireshark\tshark.exe";
LaunchInfoTshark.Arguments = "-C \"PHY Parameters\" -r C:\\enb_11.11-14-03.pcap 1> \"C:\\enb_11.11-14-03.txt\"";
LaunchTshark.StartInfo = LaunchInfoTshark;
LaunchTshark.Start();
LaunchTshark.WaitForExit();

Вот такая ошибка
tshark: Syntax error near ">"


text:
Q: How can I avoid using variables How can I convert this piece of code to functional approach? In akka I've seen Aktor::become() method that allows to overwrite the behaviour. How can I achieve something similar?
class Updater {
  var move: String = ""
  val step = 50

  def handler(key: KeyEvent) = {
    if (key.getCode.equals(KeyCode.Up.delegate)) move = "up"
    if (key.getCode.equals(KeyCode.Down.delegate)) move = "down"
    if (key.getCode.equals(KeyCode.Left.delegate)) move = "left"
    if (key.getCode.equals(KeyCode.Right.delegate)) move = "right"
  }

  def update(state: State): State = {
    val result = move match  {
      case "up" => State(state.x, state.y - step)
      case "down" => State(state.x, state.y + step)
      case "left" => State(state.x - step, state.y)
      case "right" => State(state.x + step, state.y)
      case _ => state
    }

    move = ""
    result
  }
}

A: You can transform the behaviour and put a lambda that directly will do the behaviour expected. Something like this:
case class Updater(step = 50) {
  val goUp: State => State = x => State(state.x, state.y - step)
  val goDown: State => State = x => State(state.x, state.y + step)
  val goLeft: State => State = x => State(state.x - step, state.y)
  val goRight: State => State = x => State(state.x + step, state.y)
  val doNothing: State => State = x => x

  var behaviour: State => State = doNothing

  def handler(key: KeyEvent) =
    behaviour = key.getCode.equals match{
    case KeyCode.Up.delegate => goUp
    case KeyCode.Down.delegate => goDown
    case KeyCode.Left.delegate => goLeft
    case KeyCode.Right.delegate => goRight
    case _ => doNothing
  }

  def update(state: State): State = behaviour(state)
}


text:
Q: Ajax GET request does not show parameters in the URL I'm trying to do GET request onclick using jQuery AJAX function, but the problem is that I dont see the parameters in the URL:
Here is the code:
<a href="#" class="md-list-content" data-invoice-id=<?php echo $invoiceId; ?>  onclick="myFunction('<?php  echo $invoiceId;  ?>')">

Here the Javascript code:
function myFunction(id) {
var invoice_detailsid = id;
//alert(id);
 $.ajax({
    url:"invoice_details", //the page containing php script
    type: "GET", //request type
    data: ({invoice_detailsid: invoice_detailsid}),
    success:function(data){
              console.log("success);
      }
   });
}

After I do submit, I want the URL to look like this:
http://localhost/project/page_invoices/a0yO01t8ZUIAY

I need to do it this was without refreshing the page, and at the same time, I want to see the params when I do GET request.
Please help!
Thanks.

A: When making a ajax request the url of the current page is not changing. The request it's not related to current page. That's the advantage of ajax request that you stay in current page and you make a request in background.
If you want to change the url of the current page without leaving it (or refresh) you will have to use history library from js.
Here you can find more information about history: https://developer.mozilla.org/en-US/docs/Web/API/History_API

A: data takes in a string and not an object.
Try something like this
data: "paramName="+paramValue


text:
Q: Exception: The number of rows in the range must be at least 1. Issue with the code I'm having issues with the below code, the error I receive is specifically

Exception: The number of rows in the range must be at least 1.

The purpose of the script is as follows. The are two files located in the google drive, one Pipe pipe delimited txt, and a google spreadsheet. The script is supposed to pull the date from the txt, put it into the spreadsheet-sheet1, and then copy it over to an archive on sheet2. I receive the above error. I'd appreciate a clear solution as I'm very much a rookie.
function pricing() {
  convert_txt_gsheets();
  lastrow2();
}

function convert_txt_gsheets() {
  var source = SpreadsheetApp.openById('ID1').getSheetByName('Daily Report');
  var targetrange = source.getRange(2, 1, source.getLastRow(), source.getLastColumn());
  targetrange.clear();

  var file = DriveApp.getFileById('ID2');
let body = file.getBlob().getDataAsString().split('\r'); //
let results = body.map( row => row.split('|') ); // split into columns
    results = results.map( col => col.map( cell => cell.replaceAll(`"`, ``) ) );
    console.log(results);
  SpreadsheetApp.getActive().getSheetByName('Daily Report').getRange(1, 1, results.length, results[0].length).setValues(results);
  return;
}

function lastrow2() {
var source = SpreadsheetApp.openById('ID1').getSheetByName('Daily Report');
var target = SpreadsheetApp.openById('ID1').getSheetByName('Permanent Record');
var target = target.getRange(target.getLastRow()+1, 1, source.getLastRow(), source.getLastColumn());
var rangeValues = source.getRange(2, 1, source.getLastRow(), source.getLastColumn()).getValues();
target.setValues(rangeValues);
}

Example of the TXT Data:

COLUMN1
COLUMN2
COLUMN3
COLUMN4
COLUMN5
COLUMN6
COLUMN7
Date
COLUMN9

"Item"
"5.99"
"5.39"
"5.39"
""
"5.39"
"5.39"
"7.7.2022"
"Wobble"

"Lime"
"3.99"
"3.49"
"3.49"
""
"3.49"
"3.49"
"7.7.2022"
"Dobble"

"House"
"17.69"
"16.99"
"16.99"
""
"16.99"
"16.99"
"7.7.2022"
"Wobble"

"Door"
"7.99"
"8.99"
"7.99"
""
"7.99"
"7.99"
"7.7.2022"
"Dobble"


text:
Q: How to plot scatter plot for range data I'm having range data for example an educational institute is charging fee for batch of students for online courses.

If 1-4 students join the fee is 10000/per batch
If 5-10 students join the fee is 15000/per batch
If 11-20 students join the fee is 22000/per batch

x = ['1-4','5-10','11-20']
y = [10000,15000,20000]

The x and y is my xlable and ylable for matplotlib. In this case how to transform the data of x and plot as xlable.

A: The x and y arrays can be converted into arrays of numeric values that can be used to create a scatter plot:

*

*convert the x string into ranges

x_ranges = [list(range(int(xi[0]), int(xi[1])+1)) for xi in [xi.split('-') for xi in x]]
#[[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]]

*add one y element per entry in the corresponding x range

y_expanded = [(x[0], [x[1]]*len(x[0])) for x in zip(x_ranges,y)]
#[([1, 2, 3, 4], [10000, 10000, 10000, 10000]),
# ([5, 6, 7, 8, 9, 10], [15000, 15000, 15000, 15000, 15000, 15000]),
# ([11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
#  [20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000])]

*re-group the x and y arrays

xy_sorted = list(map(list, zip(*y_expanded)))
#[[[1, 2, 3, 4], [5, 6, 7, 8, 9, 10], [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]],
# [[10000, 10000, 10000, 10000],
#  [15000, 15000, 15000, 15000, 15000, 15000],
#  [20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000, 20000]]]

*flatten the list for the x and y values

x_result = [x for sublist in xy_sorted[0] for x in sublist]
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
y_result = [y for sublist in xy_sorted[1] for y in sublist]
#[10000, 10000, 10000, 10000, 15000, 15000, ...]

*create the scatter plot

plt.xticks(x_result)
plt.ylim(0, max(y_result)+1000)
plt.scatter(x_result, y_result)
plt.show()


text:
Q: apn_for_rails gem implementation problem I have the apn_for_rails gem installed and configured correctly, the problem I'm running into is probably a syntax problem due to my newness to Ruby on Rails.
I have this in /models under the file push_notification.rb
class ApnDevice < ActiveRecord::Base

end

in routes.rb
match '/api/v2.0/RegisterIOSDevice',              :to => Api::V_2_0::ApiNotifications

and then I have another file in /lib/api/v_2_0 called api_notifications.rb
require 'rubygems'
require 'sinatra/base'
require 'nokogiri'
require 'apn_on_rails'

module Api
  module V_2_0
    class ApiPushNotification < sinatra::Base
      include ApplicationHelper
      include Api::V_2_0::ApiResponse
      include ApiUtil

      def push_notification(params)
        status = -1
        error = nil
        begin
          if params[:device_token].blank?
            return status_respnse(params,status,'device_token cant be blank')
          end
          existing_device_token = ApnDevice.find_by_token(params[:device_token])
          if existing_device_token
            return status_response(params,status,'Token already exists for device')
          end
          token = ApnDevice.create!(:token => params[:device_token])
        rescue Exception => e
          error = e.message
          Rails.logger.info "#{e.class} : #{e.message}"
          Rails.logger.info e.backtrace.join("\n")
        rescue => e
          error = e
          Rails.logger.info "Caught exception: #{e}"
          Rails.logger.info e.backtrace.join("\n")
        end #end of rescue
        status_response(params,status,error)
      end
      get '/api/v2.0/RegisterIOSDevice.:format' do
        push_notification(params)
      end
      post '/api/v2.0/RegisterIosDevice.:format' do
        push_notification(params)
      end
    end #end of class ApiPushNotification
  end #end of module V_2_0
end #end of module Api

but it gives me this huge error when I run my server, I won't post the whole thing, but it says this basically
/lib/api/v_2_0/api_notifications.rb:7: invalid multibyte char (US-ASCII) (SyntaxError)
/lib/api/v_2_0/api_notifications.rb:7: syntax error, unexpected $end, expecting keyword_end

this is followed by a stack trace which I will not post but I can't seem to find the problem, any ideas?
Edit:
ok I added the utf-8 suggestion, now I'm getting a new error:
lib/api/v_2_0/api_notifications.rb:46: syntax error, unexpected keyword_end, expecting $end (SyntaxError)

A: I don't know what you are doing there, but why are you using Rails if you use Sinatra instead in lib?
To your error, add the following code at the first line:
# encoding: utf-8


text:
Q: Suspended user can still upload an offensive profile picture using the new "Upload Picture" functionality Normally, moderator actions can't be reversed.  This is especially true if a user is suspended.  We generally allow people to do whatever they wish with their profiles (within reason), but profile pictures are visible on every post that someone makes, so we are more strict about them.
Ergo, if a user is suspended, they shouldn't be able to change their profile picture.  Case in point.

A: Personally, I'd vote for extirpating the account in place of the suspension in response. Why would you want to let someone back after that charming gesture?

A: Starting in the next build, suspended users will not be allowed to upload a new profile image.


text:
Q: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128) I'm currently writing a program which utilizes the Python NLTK library to determine whether a review is positive or negative. When trying to tokenize and store each word in an array, I keep getting the above error. The lines of code before and up to the error lines are:
from nltk.tokenize import word_tokenize

...

short_pos = open("reviews/pos_reviews.txt", "r").read()
short_neg = open("reviews/neg_reviews.txt", "r").read()

documents = []

for r in short_pos.split('\n'):
    documents.append( (r, "pos") )

for r in short_neg.split('\n'):
    documents.append( (r, "neg") )

all_words = []

short_pos_words = word_tokenize(short_pos)
short_neg_words = word_tokenize(short_neg)

The second to last line is where it's saying I have an error. If I comment out that line, the error appears on the following line. I'm not sure where this error would arise, as I didn't think I was working with unicode at all. Any help would be appreciated!

A: In Python 2.7, try to use io module to specify file encoding, see Difference between io.open vs open in python
Also, context manager is your friend (i.e. with ... as ...), esp. when it comes to I/O https://jeffknupp.com/blog/2016/03/07/python-with-context-managers/
import io

from nltk.tokenize import word_tokenize

documents = []

with io.open("reviews/pos_reviews.txt", "r", encoding="utf8") as fin:
    for line in fin:
        documents.append((line.strip(), "pos"))


text:
Q: cout is not a member of std, and other issues regarding c++ Allow me to preface this by saying that I do have  included (also applies to string, endl, and quite literally everything doesn't work); my IDE is showing no errors as far as syntax goes; and I cannot understand why this issue is happening? It works fine in one of my other C++ code samples I wrote.
So I am trying to make a small game, bulls and cows. My main code looks as follows:
#include <iostream>

#include "stdafx.h"
#include "BullsAndCows.h"

using std::cout;
using std::endl;
using std::cin;
using std::string;

int main()
{

    string userInput = "";
    bool playAgain = false;

    int gameDiff;

    constexpr char * GREETING = "Welcome to Bulls and Cows! Please enter the difficulty level: (1) Easy, (2) Medium, (3) Hard";

    cin >> gameDiff;

    do
    {
        BullsAndCows *bc = new BullsAndCows();
        bc->playGame(gameDiff);

    } while (playAgain);

    constexpr char * INFORMATION = "Total Word Length  is: ";

    //Introduce the game.

    cout << GREETING <<endl;

    return 0;
}

My header:
#ifndef BULLSANDCOWS_H
#define BULLSANDCOWS_H

class BullsAndCows {

public:

    void playGame(int gameDiff);

};

#endif

Finally, my BullsAndCows.cpp file:
#include <iostream>
#include <string>
#include "stdafx.h"
#include "BullsAndCows.h"

using std::cout;
using std::endl;
using std::cin;
using std::string;

void BullsAndCows::playGame(int gameDiff) {

    string wordGuess = "";
    string secretWord = "";
    int numBulls = 0;
    int numCows = 0;
    int numGuesses = 0;

    switch (gameDiff)
    {

    case 1: {
        numGuesses = 30;

        secretWord = "Hello";

        for (int i = 0; i < 30; i++) {

            numBulls = 0;
            numCows = 0;

            cout << "Word Length to Guess Is Five, you have " << numGuesses << " guesses remaining" << endl;
            cout << "Enter your word guess";
            cin >> wordGuess;

            for (int j = 0; j < wordGuess.length; j++) {
                if (wordGuess.at(j) == secretWord.at(j)) {
                    numBulls++;
                }
                else if (secretWord.find(wordGuess.at(j)) != -1) {
                    numCows++;
                }
            }

            cout << "Bulls: " << numBulls << endl;
            cout << "Cows: " << numCows << endl;

            if (numBulls == secretWord.length) {
                cout << "YOU WIN!" << endl;
                break;
            }

        }

        break;
    }
        case 2:
            numGuesses = 20;
            break;
        case 3:
            numGuesses = 10;
            break;
    }

}

Errors I am getting as "cout is not a member of std", cout symbol cannot be used in a using declaration. Before that I was using "using namespace std" and that would return errors like "BullsAndCows" is not a namespace or class (if it is not a class, then I must be a martian). Also something about a missing ";" before userInput for example in my main.cpp code; which makes no sense as there is nothing that is missing that. I am using VS2017. Why is C++ such an annoying language to work in?

A: Place the directive
#include "stdafx.h"

before any other include directives.


text:
Q: When i run pip3 freeze or pip3 list there is no output As the title says, when i run pip3 freeze or pip3 list there is no output on the terminal!
Virtualenv seems also to be broken cause when i was inside of the env it was using the global django-admin.
I did  sudo pip3 install --upgrade pip and after that i think it broke.

*

*OS: Manjaro Linux

*Python3 Version: Python 3.7.4

*Pip3 Version: pip
19.2.3 from /usr/lib/python3.7/site-packages/pip (python 3.7)

A: Find out how to cleanly reinstall pip (or even Python) from your operating system and really try to avoid anything with sudo pip or even sudo python. My recommendation is to not even install pip at all and use the one preinstalled in the virtual environments (when you do python3 -m venv .venv) instead, this is to avoid any conflict with the Python packages installed by your operating system.


text:
Q: Qt 4.x: how to implement drag-and-drop onto the desktop or into a folder? I've written a little file-transfer application written in C++ using Qt 4.x ... it logs into a server, shows the user a list of files available on the server, and lets the user upload or download files.
This all works fine; you can even drag a file in from the desktop (or from an open folder), and when you drop the file icon into the server-files-list-view, the dropped file gets uploaded to the server.
Now I have a request for the opposite action as well... my users would like to be able to drag a file out of the server-files-list-view and onto the desktop, or into an open folder window, and have that file get downloaded into that location.
That seems like a reasonable request, but I don't know how to implement it.  Is there a way for a Qt application to find out the directory corresponding to where "drop event" occurred, when the icon was dropped onto the desktop or into an open folder window?  Ideally this would be a Qt-based platform-neutral mechanism, but if that doesn't exist, then platform-specific mechanisms for MacOS/X and Windows (XP or higher) would suffice.
Any ideas?

A: Look at QMimeData and its documentation, it has a virtual function
virtual QVariant retrieveData  ( const QString & mimetype, QVariant::Type type ) const

this means to do you drag to the outside you implement this functions accordingly
class DeferredMimeData : public QMimeData
{
  DeferredMimeData(QString downloadFilename) : m_filename(downloadFilename)

  virtual QVariant retrieveData (const QString & mimetype, QVariant::Type type) const
  {
    if (mimetype matches expected && type matches expected)
    {
       perform download with m_filename
    }
  }
}

The delayed encoding examples shows this principle.
You will probably also have to override hasFormat and formats to provide the appropriate types, application/octet-stream probably being the one that might get you the most play, you will probably have to read up on how windows specifically handles drag and drop using mime types.
I don't know how you will supply the file name under which the file is saved, but you will probably have to get into the windows side of things. Looking at the source of QWindowsMime might also help. There might me a multiple step process where you will get requests for text/uri-list data for the filenames and then application/octet-stream for the data.
Hope this helps

A: I think you are going about that in the wrong way.
You don't care where the drop goes to, you just know it was dropped.  In the DropEvent, download the file to a temporary location and then set the mime data to be what was downloaded.  Granted this may end up with a second copy to the hard drive, it will be cross platform from the start.  You may be able to optimize it afterward with platform specific calls.
Take a look at Dropsite example to see how the mime data works from other sources...
Edit:
It looks like the double copy method is the standard if you don't write a shell extension (for windows at least).  Filezilla and 7zip both do that, they return a "text/uri-list" mime type with a temp location.  This way explorer copies the data from the temp location to the real one.  Your application can do the same, create a temp file (or just the name) with no data.  Using the delayed encoding example, create the data on the drop.  This whole operation is very platform specific it appears.  On Linux (running KDE) I can drag and drop just based on mime type.  It appears that windows is not as flexible.

A: You just implement the drag part. You don't need to know where the drop happen because the application receiving it will handle it and decide where to store your file.
You create a QMimeData, not sure which type but from what i saw here and here, maybe "application/octet-stream" with your file as data in a QByteArray or "text/uri-list" with url to your file.
You create a QDrag, and use its setMimeData() method and exec() (not sure about which QT::DropAction to choose).
Here is an example (disclamer : i did it with color not files) :
void DraggedWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
        start_pos = event->pos();
}

void DraggedWidget::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        int distance = (event->pos() - start_pos).manhattanLength();
        if (distance >= QApplication::startDragDistance())
        {
            /* Drag */
            QMimeData *mime_data = new QMimeData;

            mime_data->setData( ... );

            QDrag *drag = new QDrag(this);
            drag->setMimeData(mime_data);
            drag->exec(Qt::CopyAction);
        }
    }
}

Sorry it's quite incomplete, i hope it helps a little.


text:
Q: Arrays in MASM Assembly (very confused beginner) I have a pretty basic question:
How do you populate arrays in assembly? In high level programming languages you can use a for-loop to set a value to each index, but I'm not sure of how to accomplish the same thing assembly. I know this is wrong, but this is what I have:
ExitProcess PROTO
.data
warray WORD 1,2,3,4
darray DWORD ?

.code
main PROC
mov edi, OFFSET warray
mov esi, OFFSET darray
mov ecx, LENGTHOF warray

L1:
mov ax, [edi]          ;i want to move a number from warray to ax
movzx esi,ax           ;i want to move that number into darray...
add edi, TYPE warray   ;this points to the next number?

    loop L1

    call ExitProcess
main ENDP
END

Each time the loop runs, ax will be overwritten with the value of the array's index, right? Instead how do I populate darray with the array elements from warray? Any help would be very much appreciated...I'm pretty confused.

A: There are more than one way to populate an array and your code is almost working. One way is to use counter in the indirect address so you don't have to modify destination and source array pointers each loop:
ExitProcess PROTO
.data
    warray WORD 1,2,3,4
    darray DWORD 4 dup (?) ; 4 elements

.code
main PROC
    mov edi, OFFSET warray
    mov esi, OFFSET darray
    xor ecx, ecx                ; clear counter
L1:
    mov ax, [edi + ecx * 2]     ; get number from warray
    movzx [esi + ecx * 4], ax   ; move number to darray
    inc ecx                     ; increment counter
    cmp ecx, LENGTHOF warray
    jne L1

    call ExitProcess
main ENDP
END

Of course this code could be modified to fill the array backwards to possibly save couple of bytes like you probably meant to do in your original code. Here is another way that has more compact loop:
ExitProcess PROTO
.data
    warray WORD 1,2,3,4
    darray DWORD 4 dup (?) ; 4 elements

.code
main PROC
    mov edi, OFFSET warray
    mov esi, OFFSET darray
    mov ecx, LENGTHOF warray - 1    ; start from end of array
L1:
    mov ax, [edi + ecx * 2]     ; get number from warray
    movzx [esi + ecx * 4], ax   ; move number to darray
    loop L1

    ; get and set element zero separately because loop terminates on ecx = 0:
    mov ax, [edi]
    movzx [esi], ax

    call ExitProcess
main ENDP
END

You should also note that when working with arrays of the same type you can do simple copy very efficiently using repeat prefix with instructions like MOVSD:
ExitProcess PROTO
.data
    array1 DWORD 1,2,3,4
    array2 DWORD 4 dup (?)

.code
main PROC
    mov esi, OFFSET array1      ; source pointer in esi
    mov edi, OFFSET array2      ; destination in edi
    mov ecx, LENGTHOF array1    ; number of dwords to copy
    cld                         ; clear direction flag so that pointers are increasing
    rep movsd                   ; copy ecx dwords
    call ExitProcess
main ENDP
END

A: You're probably not "supposed to know" this, but anyway, there were (way back when) an instruction and an instruction prefix that were made to do exactly this.
Take a look here at this Microsoft page:  HERE (click on it)
On that page scroll down until you find this phrase...
"...These instructions are remnants of the x86's CISC heritage and in recent processors are actually slower than the equivalent instructions written out the long way...."
What you do is...

*

*Put the size of the array in Ecx

*Point Edi at the start of the arry

*Use the appropriate string instruction to populate it

The syntax (Masm/Tasm/etc.) will probably look something like this...
 Mov       Ecx, The_Length_Of_The_Array            ;Figure this out somehow
 Lea       Edi, The_Target_You_Want_To_Fill        ;Define this somewhere

Now, if you want to copy from one place to another, do this...
 Lea       Esi, The_Source_You_Want_To_Copy         ;Whatever, define it
 Cld                                                ;This is the direction flag, make it inc
 Rep       Movsb                                    ;Movsb means move byte for byte

Now, if you want to stuff the same value in each byte in the arrray do this...
 Mov       AL, The_Value_You_Want_To_Stuff          ;Define this to your liking
 Cld                                                ;This is the direction flag, make it inc
 Rep       Stosb                                    ;Stosb means store AL into each byte

Again, these instructions are, for reasons others will elucidate, not cool anymore and if you use them you will get cooties or something.
There are also string instructions for comparison, "Scanning", "Loading", and so on. They were once quite useful (and still are, but the "modern" gang today won't admit it) particularly with the Rep prefix added to them.
If this helps, but you need more detail, feel free to ask.


text:
Q: C++ Accessing to begin()/end() methods of container inside a class i would like to access the begin() and end() methods of a Container inside a class without incurring in const_iterator to iterator conversion problems. So i made a get method to return the container and access it:
#include <iostream>
#include <vector>

class SpecialList {
  public:
    std::vector<int> getVett(void) const { return vettore; }

    void getFull(void) {
      std::vector<int>::iterator it1;

      for (size_t i = 0; i < 10; ++i)
        vettore.push_back(i);
    }

    void print(void) {
      std::vector<int>::iterator it1;

      std::cout << std::endl;

      for (it1 = vettore.begin(); it1 != vettore.end(); ++it1)
        std::cout << " " << *it1;

      std::cout << std::endl;
    }

  private:
   char some_data;
   std::vector<int> vettore;
};

int main(void) {
  std::cout << "Some output" << std::endl;

  SpecialList listspec;
  listspec.getFull();
  listspec.print();

  std::vector<int> pVet = listspec.getVett();

  std::cout << "Size = " << pVet.size() << std::endl;
  std::cout << "pVet[1] = " << pVet[1] << std::endl;

  std::vector<int>::iterator it2;

  std::cout << std::endl;

  for (it2 = listspec.getVett().begin(); it2 != listspec.getVett().end(); ++it2)
    std::cout << " " << *it2;

  std::cout << std::endl << "pVet[1] = " << pVet[1] << std::endl;
  return 0;
}

The code works from a compiler perspective, but it gives the wrong output:

Some output
0 1 2 3 4 5 6 7 8 9
Size = 10
pVet[1] = 1
0 0 2 3 4 5 6 7 8 9
pVet[1] = 1

Why does it not read correctly the vector printing a 0 istead of a 1? Is this a good approach to access a container inside a class through iterators?
Thanks.

A: Your function std::vector<int> getVett(void) const { return vettore; } creates a copy of your vector vettore. You have to return a reference to your vector. Because of that you have undevined behaivor in your for loop. Change your function like this:
const std::vector<int>& getVett(void) const { return vettore; }

Since your function is const and your return reference is const you have to use const_iterator, cbeginand cend in your for loop.
std::vector<int>::const_iterator it2;
for (it2 = listspec.getVett().cbegin(); it2 != listspec.getVett().cend(); ++it2)
    std::cout << " " << *it2;

Note: You can use auto instead of const_iterator:
for (auto it2 = listspec.getVett().cbegin(); it2 != listspec.getVett().cend(); ++it2)
    std::cout << " " << *it2;

You also can you give up const:
std::vector<int>& getVett(void) { return vettore; }

std::vector<int>::iterator it2;
for (it2 = listspec.getVett().begin(); it2 != listspec.getVett().end(); ++it2)
    std::cout << " " << *it2;


text:
Q: Galois group of a polynomial with coefficients in $\mathbb{C}(x)$ and deck transformations of the covering of $\mathbb{C}$ Let $w(x,y) \in \mathbb{C}[x,y]$ be an irreducible polynomial. The vanishing locus $Z=\{(x,y) \in \mathbb{C}^2 | w(x,y)=0 \}$ with projection to $x$-coordinate is a ramified covering $\pi : Z \to \mathbb{C}$. Lets remove ramification locus $D$ and get unramified (topological) covering  $\pi' : Z' \to \mathbb{C}\backslash D$. Denote $G_1$ the group of deck transformations of this covering.
On the other hand, we have finite extension of fields $\mathbb{C}(x) \to \mathbb{C}(x)[y]/(w(x,y))$, let $G_2$ be the group of automorhisms of the extension.
For coverings and for field extensions we have notion of normality. Is this covering normal iff extension is normal?
What are relations between groups $G_1$ and $G_2$? Are they isomorphic?


text:
Q: How to Connect 3 Networks With Ethernet and WIFi/VPN? I have two computers on a robot that are directly connected via Ethernet. Called" Magni" and "Jetson". Magni is connected to a wireless network. On this wireless network, there is a third computer "PC" that is connected to the Magni via Wireguard VPN.
I have two computers on a robot that are directly connected via Ethernet. Called" Magni" and "Jetson". Magni is connected to a wireless network. On this wireless network, there is a third computer "PC" that is connected to the Magni via Wireguard VPN.

The goal is to be able to send and receive messages from all components of the system to one another. The Magni - Jetson and Magni - PC pairs can ping, discover, and publish to each other. The issue I am having is communication between my PC and the Jetson. I attempted to do some IP forwarding. Where first on the jetson I added a route from the static 192.168.131.1 IP to the Magni's VPN 10.0.0.161. After doing so I am able to ping the Magni's VPN address 10.0.0.161 from the jetson.
sudo route add -net 10.0.0.0  netmask 255.255.255.0 gw 192.168.131.1

Then on my PC, I attempted to add a similar route...
sudo route add -net 192.168.131.0  netmask 255.255.255.0 gw 10.0.0.161

From my PC I then tried to communicate with the jetson (via ping). However, I am not able to successfully communicate with the Jetson. From the PC when trying to ping the Jetson, I get this error with my current set up.
PING 192.168.131.2 (10.0.0.66) 56(84) bytes of data.
From 10.0.0.66 icmp_seq=1 Destination Host Unreachable
ping: sendmsg: Required key not available

I have also tried other routes to no avail. I was wondering if someone could point me in the right direction as to how to resolve this issue as I am not too experienced in networking.
PC's Kernel IP routing table
Destination   Gateway     Genmask       Flags Metric Ref    Use Iface

0.0.0.0           10.147.x.x      0.0.0.0         UG   600    0        0  wlp2s0

10.0.0.0        0.0.0.0         255.255.255.0   U     0      0        0 wg0

10.147.x.x      0.0.0.0         255.255.0.0     U     600    0        0 wlp2s0

169.xxx.x.x     0.0.0.0         255.255.0.0     U     1000   0        0 wlp2s0

192.168.131.0   10.0.0.161      255.255.255.0   UG    0      0        0 wg0

Magni's Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface

0.0.0.0         10.147.x.x      0.0.0.0         UG    600    0        0 wlan0

10.0.0.0        0.0.0.0         255.255.255.0   U     0      0        0 wg0

10.19.xxx.xxx   10.147.x.x      255.255.255.255 UGH   600    0        0 wlan0

10.147.x.x      0.0.0.0         255.255.0.0     U     600    0        0 wlan0

192.168.131.0   0.0.0.0         255.255.255.0   U     0      0        0 enxb827eb452fa3

Jetson's Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface

10.0.0.0           192.168.131.1   255.255.255.0   UG    0      0        0 eth0

169.xxx.x.x       0.0.0.0         255.255.0.0     U     1000   0        0 eth0

192.168.131.0   0.0.0.0         255.255.255.0   U     100    0        0 eth0

A: ping: sendmsg: Required key not available means it's a WireGuard cryptokey routing issue. In WireGuard, the key has an association to the route and vice versa. This is an internal WireGuard routing made in addition to the standard routing:

At the heart of WireGuard is a concept called Cryptokey Routing, which
works by associating public keys with a list of tunnel IP addresses
that are allowed inside the tunnel.

That means you didn't add the required AllowedIPs (wg-quick) / allowed-ips (direct wg command) parameters.
When a WG interface is about to send a packet it matches the destination IP to a public key's AllowedIPs in order to encrypt it with this key. When a WG interface received a packet, it validates the source IP with the peer's public key's AllowedIPs: this value is used both ways.
To fix this, on the PC add in the configuration, under the relevant Magni Peer public key entry in the wg-quick configuration and restart the tunnel:
AllowedIPs = 192.168.131.0/24

Actually for this specific case AllowedIPs = 192.168.131.1,192.168.131.2 would be sufficient.
If you could already ping the Magni (192.168.131.1) from the PC, that should be enough, assuming Magni was set as router.

Else, there's the equivalent to do on the other WireGuard peer, Magni. Do the equivalent to match the PC, under the PC's Peer public key entry:
AllowedIPs = 10.0.0.0/24

Again AllowedIPs = 10.0.0.66 would be sufficient to reach only the PC here.
It could be done directly with a wg command instead for immediate (and not saved) effect (as an example a randomly generated Peer's public key value ukFU7nbX5NoEJTLb5rizqcfB093fv8VfuLFA57q3oG4= is used here, please change it to the PC's public key):
wg set wg0 peer ukFU7nbX5NoEJTLb5rizqcfB093fv8VfuLFA57q3oG4= allowed-ips 10.0.0.0/24


text:
Q: Print each element of a CArray I have this CArray
import qualified Data.Array.CArray as CArr
import qualified Data.Array.IArray as IArr

arr :: CArr.CArray Int Double
arr = IArr.array (1, 4)  $ zip [1..4] [1..4]

How do I print each element of CArray? Something like this pseudocode if arr is a list:
mapM_ print arr

A: mapM_ print (IArr.elems arr)

This looks like the easiest solution.


text:
Q: set position, top and left for a draggable object I have a draggable object set to position:relative but I need to change it from relative to absolute  only when I drag it and I want the object to stay in its initial space.
I tried to set "drag" in this way:
$('obj').draggable({
    cursor: 'move',
    revert: true,
    drag: function () {
        var posizione = $(this).position();
        var posizione_x = posizione.left;
        var posizione_y = posizione.top;
        $(this).css({
            "left": posizione_x,
            "top": posizione_y,
            "position": "absolute"
        });
    },
    stop: function () {
        $(this).css("position", "relative");
    }
})

or in this way:
$('obj').draggable({
    cursor: 'move',
    revert: true,
    drag: function () {
        var posizione_x = $(this).offsetLeft;
        var posizione_y = $(this).offsetTop;
        $(this).css({
            "left": posizione_x,
            "top": posizione_y,
            "position": "absolute"
        });
    },
    stop: function () {
        $(this).css("position", "relative");
    }
})

but it doesn't work.

A: I think you need .offset().left and .offset().top
Could you detail "does not work" (error in the console? what happend? how is positionned the element?)
And $('obj') target a <obj> tag, are you certain you element is well targeted?
Maybe you try to do something like that: http://jsfiddle.net/KyleKatarn/awjh79uw/1/


text:
Q: QQuickwidget grab image outside window area This is a sequel to another question here in which I was not precise while describing my goal.
As mentioned in the linked question, I wish to save a QML which is embedded in a QQuickWidget and it is larger than the window size. The QQuickWindow grabWindow() method captures only the window area and hence I tried the following code after I visually displayed it:
QQuickWidget* content..
content->setSource(QUrl("qml:/main.qml"));
QPixmap *pm = content->grab(QRect(QPoint(0,0),QSize(-1,-1));
pm->save("someFilename.png", 0, 100);

So, it is definitely not the issue of saving image after rendering. The used QML code is just a plain Rectangle. The proposed solutions in the previous question only grabs content falling within the window.
Any suggestions? Thanks! :)
Addendum:
I have tried the following but didn't work:
QImage paintdev(largeWidth, largeHeight, QImage:Format_RBG32);
content->render(paintdev, QPoint(0,0), QRegion(QRect(0,0,largeWidth, largeHeight), QWidget::DrawChildren);
paintdev.save(fileName, 0, 100);

This should by logic solve the issue of window size since there is no window. Any comments?

A: Ok, so I solved it by manually shifting the QML by the window height and saving all the images from the window captures and collate it to form the original image.
Not too much work though, but I am still mystified by the QWidget render() method which did not work.
Thanks for all the replies!

A: If your QML content is larger than the window size, the part that is out of screen is not drawn. Hence, there is no way to capture something out of screen, unless you use 2 monitors and extend view. This last approach would work.


text:
Q: zend framework 2 - Translation Process i am developing web app with ZF2. It is a multilingual website. I would like to use ZF2 Translator for translation. Because, admin can modify the language variables. So, i planned to use the language folder files. I will update the language files while the admin modifying the language variables. Can anyone suggest ideas for this implementation? Thanks.

A: Translating based on user input can get a little messy. There is no easy way of doing that right now, as the currently supported formats are all file formats: php files with arrays, a gettext .po file or Tmx/Xliff files. For the easiest access, you would likely store the translations in a database.
You therefore need to write your own loader, loading the translations from the database. An alternative is you will write the translations in a php array and export that to a file, but I would not recommend that. For the database loader, you must implement the RemoteLoaderInterface. In very simple terms:
use My\DbTable;
use Zend\I18n\Translator\Loader\RemoteLoaderInterface;
Zend\I18n\Translator\TextDoamin;

class DbLoader implements RemoteLoaderInterface
{
    protected $table;

    public function __construct(DbTable $table)
    {
        $this->table = $table;
   }

    public function load($locale, $textDomain)
    {
        $data = $this->table->loadFromLocale($locale);

        // process $data into $messages
        // $messages is array(key=>value) with key translation key

        $domain = new TextDomain($messages);
        return $domain;
    }
}

The db table loads the messages in the locale you specify. If you use text domains, pass that on too. Then you need to configure your Translator such it uses this loader too to load the message. Everything else should be fine then. In your views, you can create translations like this:
<?php echo $this->translate('my original text'); ?>

A: The SkeletonApp comes with Translation support built-in. However further details on how to use it can also be found in the manual -> http://zf2.readthedocs.org/en/latest/modules/zend.i18n.translating.html
I personally keep all my language files in a folder called /language
In your views you could also simply call
$this->translate('text_you_want_to_translate');


text:
Q: Would a commutative power operator simplify some equations of physics? Hypertype Theory makes the radical suggestion that a commutative power operator would be preferable to the traditional non-commutative power operator $a^b$. Are there any equations in physics that would be simplified by using such an operator?
Non-commutative Power Operator: $a^b = e^{\lg(a)×b}$
Commutative Power Operator: $a \# b = b \# a = e^{\lg(a)×\lg(b)} = a^{\lg(b)} = b^{\lg(a)}$
Identity Element: $a\#e = e\#a = a$
Inverse Operator: $a \backslash b = e^{\frac{\lg(a)}{\lg(b)}} = a^{\frac{1}{\lg(b)}}$
Traditional Connection: $a^b = a\#e^b$
Terminology:
The $\#$ operation is called expansion and $a \# b$ reads "a expands b".
The $\backslash$ operation is called contraction and $a \backslash b$ reads "a contracts b".
Obviously, many equations like $e = mc^2$ would suffer from such a replacement and should be left untouched. The question is interested in more complex equations that could be simplified.
Note: This is important because addition and multiplication are commutative, but exponentiation is not. If one thinks of a multiplication as doing multiple additions and an exponentiation as doing multiple multiplications, the lack of commutativity for exponentiation is bothersome. Instead, one should think of addition, multiplication, and expansion as being the same operation applied to different exponential scales. Obviously, the same goes for subtraction, division, and contraction.
Algebraic Foundations: Hypertype Theory shows that an infinite number of such pairs of operators can be created in a recursive manner using very simple equations. The simplicity and beauty of the model suggests that we are looking at something interesting.

A: I think this question gets the point of notation backwards. Good notation is invented when you notice that your calculations would look nicer if you made a few new definitions. You're trying to start with a definition you like for non-practical purposes and looking for a context where it would be practical.
You will surely find some equations out there that are shorter with your notation, but that's true for any notation. I could define $\biguplus = 27$ and use that to shorten some equations. Feynman gives the example of defining $\mathscr{U} = |\mathbf{F} - m \mathbf{a}|^2$, so that Newton's second law simplifies to the "elegant" form
$$\boxed{\mathscr{U} = 0.}$$
As always, the benefit of the notation has to be traded against the mental overhead of "unpacking" it. For example, with differential forms we can boil down Maxwell's equations to
$$d \star F = \star J.$$
This elegance is worth the overhead because we actually can compute within it; we don't have to unpack it to regular tensor notation to actually use it. But I suspect that most people who encounter your # notation will immediately unpack it to regular exponentials, because those are so much more familiar, completely negating the benefit. It's like a fancy new programming language. If you build it, they'll won't come unless it's useful.
The other roadblock, of course, is that most quantities in physics have dimensions, while your expression only makes sense if both $a$ and $b$ are dimensionless. That's why you're having more luck looking at pure math.

A: Every operator can be symmetrized, antisymmetrized, and potentially broken down into just about any combination of internal and external group structures. For your particular case, see the BCH (Baker-Campbell-Hausdorff) formula.
The operators you put forward are wrong because $a^{\log b}$ does not equal $b^{\log a}$ unless $a$ and $b$ commute to start with. You can confirm this easily by writing out the power series for $e^{\log a \log b}$ versus $e^{\log b \log a}$.
The short answer to your question is, though, that any operator which can be linearized can be put in matrix form. From there you can simply replace powers of the operation (or transcendentals in series of powers) with functions on the sum of functions of the eigenvalues.


text:
Q: macOS NO new file here, advantages? On macOS Finder we don't have a new file here by default. So they created it somewhere else (https://langui.net/new-file-here/) and people have to pay extra for that.
In principle it seems to me a new file here is a good thing to have. But many times apple cut stuff out, and then we notice we actually don't need it.
I trying to understand if that idea is being applied to the missing new file here case.
However I'm having a hard time to understand the benefits of not having a new file here.
What are the advantages of not having a new file here?

A: This is likely to get closed as opinion-based, but I'd ask "What's the perceived benefit of being able to create a blank file to then have to open it in a separate action?"
Why not just generate new files in the application you're going to use them in?
You can, if you need for arcane or esoteric purposes, easily create a blank file in Terminal with touch.


text:
Q: Using multiple if else to check for content and member status I am trying to check if a user is logged in as a member and also if a meta field in a WordPress custom post type has content and then need to display content based on 4 possible outcomes. I am using WordPress membership plugin woomembers

*

*user is logged in as a member and content exists - display content

*user is logged in as a member and content field is empty - display nothing

*user is not a member and content exists - display some content and sign up

*user is not a member and no content exists - display sign up

I have this code partly working but can't get item 3 to work?
The code I have is:
<?php $meta_content_field = get_post_meta($post->ID, "meta-content-field",
$single = true);

   if (wc_memberships_get_user_active_memberships() &&
   $meta_lighting_diagram != '') {

       // Active member and has content- do something here

       ?>
       html content here

   <?php
   } elseif (wc_memberships_get_user_active_memberships() &&
   empty($meta_content_field) ) {

        // No content but active member - do something here
        echo "No content but active member";

   } elseif ( ! empty( wc_memberships_get_user_active_memberships() ) &&
   ($meta_content_field) ) {

       // content but non-member - do something here - this is not working?
       echo "Has content but NOT active member";

   } else {

        // Non-member - do something here ?>
        html content here

  <?php }
  ?>

A: Your loop is wrong. First check should be member or not.
if ( $member) {
 // do something for the member
} else {
 // do something for the non-member
}

Then you want to check whether or not there is content.
Do this within the if-loop
if ( $member ) {
 // do something for the member
  if ( $content ) {
   // member and content
  } else {
   // member no content
  }
} else {
 // do something for the non-member
  if ( $content ) {
   // non-member and content
  } else {
   // non-member no content
  }
}

a maybe even better approach would be to use switch(). Could look like this:
$status = '';
if ( $member ) $status = 'member';
  else $status = 'nonmember';
if ( $content ) $status .= 'content';
  else $status .= 'nocontent';

switch ( $status ) {
   case 'membercontent':
        // do something
        break;
   case 'membernocontent':
        // do something
        break;
   case 'nonmembercontent':
        // do something
        break;
   case 'nonmembernocontent':
        // do something
        break;
}

This can be simplified (shortened) in combination with default:.


text:
Q: Four-layer stack-up in PCB design Folks, I am planning to design 4-layer PCB.
I came across the following website which has excellent pointers:
http://www.hottconsultants.com/techtips/pcb-stack-up-2.html

Here is an excerpt:

A fourth possibility, not commonly used, but one that can be made to perform very well, is shown in Fig. 4.  This is similar to Fig  2, but with the power plane replaced with a ground plane, and power routed as a trace on the signal layers.

This stack-up overcomes the rework problem mentioned before, and still provides for the low ground impedance as a result of two ground planes.  The planes however do not provide any shielding.  This configuration satisfies objectives (1), (2), and (5) but not objectives (3) or (4).
So, as you can see there are more options available, than you might have originally thought, for four layer board stack-up.  It is possible to satisfy four of our five objectives with a four layer PCB.  The configurations of Figures 2, 3b, and 4 all can be made to perform well from an EMC point of view.

My question is why the SIG/GND/PWR/GND variation of Figure 4 in the website is not discussed? Is something fundamentally wrong with the above stack-up?

A: I have heard some issues with sig/gnd/pwr/sig. You have to remember that a signal on layer 4's path to ground is thru the nearest bypass cap. With sig/gnd/gnd/sig-pwr you can shorten the return path by just putting a ground via from layer 2 to 3 right next to your signal via going from 1 to 4.
I guess you have to figure out if your signals are fast enough to really worry about it though. There are millions of 2 layer micocontroller boards out there and the world hasn't ended yet.


text:
Q: error 1258 when restoring from Actifio I am using ActifioGo on Google Cloud and took a snapshot. When I try to restore it, I get an error message like:
1258: Cloud VM creation failed. 155: VM task failed. Error: Cloud task failed
gcp:createvmfromimage:us-central1-a:123456....789:projectname:
act-image-snap-bastion-123-456.

What can I do?

A: This worked for me:
The service account used by Actifio must have the privileges to perform the restore operation. To make sure this is the case, go to Actifio Go Manager - manage - credentials. Note the service account name, it will be similar to 123465789-compute@developer.gserviceaccount.com
Go to Google Cloud Console, change to the correct project (the error message contains the project name). Select IAM & Admin -> IAM. Select the service account (in this example 123456789-compute...) and assign the role Custom -> ActifioGo which has been installed by Actifio.


text:
Q: How to consume REST API (Liverail) via webservice using Java I am a complete newbie to webservices but have some experience in Java. We have been provided with Liverail API documentation with a list of Entities that we can consume. This is what their doc says:
"Logical flow An API client must always use the /login method followed by the /set/entity method. All the remaining APIcalls will be executed on the selected entity. If you need to switch the current entity, you should use /unset/entity followed by a new /set/entity with the new entity ID as parameter. It is also recommended to call /logout once the API client ends its execution"
XML response format
The LiveRail API XML response is always formated like bellow.
My dilema is that i dont know how to make the GET calls.
What i would like to do in java is :

*

*Create a http login to API webservices

*Fetch a list of data (response is in XML format)
3 Convert this XML response into CSV file.

Any help will be highly appreciated.

A: Why not using RestTemplate?
final String uri = "http://localhost:8080/springrestexample/employees/{id}";

Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");

RestTemplate restTemplate = new RestTemplate();
EmployeeVO result = restTemplate.getForObject(uri, EmployeeVO.class, params);

System.out.println(result);

Here is for more tutorials http://howtodoinjava.com/2015/02/20/spring-restful-client-resttemplate-example/


text:
Q: How to disable certain pop up when typing? When writing code in Visual Studio Code, these kind of things keep popping up:
Image
I would be really grateful if someone could tell me how to disable these as they keep obstructing my code and aren't very useful to me.
Thanks!

A: That's the suggestion box. It's part of Visual Studio Code's "IntelliSense" functionality.
If you find it annoying (some people do), you can disable it using the following steps:

*

*Open your settings file. (Pro Tip: Open the "Quick Open" interface using the Ctrl/Cmd + P keyboard shortcut, and insert "> Open User Settings", then press enter. This will open your settings file in Visual Studio Code)

*Add the "editor.quickSuggestions" property to your settings file.

*Give the [previously added] "editor.quickSuggestions" property a value of false.

And that's really all there is to it.


text:
Q: django restful framework's request.user has two different type and different value? i'm a newbie of django-rest-framework, i try a very simple web app
one programe
url.py
urlpatterns = [
    url(r'^admin/$', "app.views.admin_index"),
]

views.py
def admin_index(request):
    print request
    print type(request.user)
    return render(request, "admin/index.html")

output is
AnonymousUser
<class 'django.utils.functional.SimpleLazyObject'>

anthoner programe
url.py
urlpatterns = [
    url(r'^admin/$', AdminViewSet.as_view({'get':'list'})),
]

views.py
class AdminViewSet(viewsets.ViewSet):
    permission_classes = (permissions.IsAdminUser,)
    renderer_classes = (renderers.TemplateHTMLRenderer,)
    def list(self, request):
        print request
        print type(request.user)
        return Response(template_name='admin/index.html')

output is
admin
<class 'django.contrib.auth.models.User'>

so, request.user has two different output, most important is one is AnonymousUser another one is admin, why? something wrong?
=========solution========================
settings.py
REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.AllowAny'
    ),

    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    )
}

it has 'rest_framework.authentication.BasicAuthentication', so it make request.user store in http header, but not in session, so django.contrib.auth's logout failed.
solution is only use 'rest_framework.authentication.SessionAuthentication'

A: class 'django.utils.functional.SimpleLazyObject' is a type of promise. When evaluated, it will act as a proxy to the delayed object. There's nothing wrong here; django uses this type in a lot of places to implement laziness.


text:
Q: How should I treat background radiation in an experiment? I am performing an experiment to verify the inverse-square law for the intensity of a beam of $\gamma$ rays emitted by a sample of $^{60}\text{Co}$. The set-up is as follows:

*

*A Geiger-Müller tube connected to an electronic counter is set up.

*A background reading is first taken, by performing 10 measurements of $100\text{ s}$ each with no source nearby.

*The average count is taken: in my experiment, I have a value of $c_{BG} = 28.5$, with a standard deviation, $\sigma_{BG}=3.837$, represented as $28.5 \pm 3.837$.

*Now, the radioactive source is placed at a fixed position, and the GM tube is placed at a distance $d\text{ cm}$ away from the source.

*10 readings lasting $100\text{ s}$ each are taken, and the average count for 100 seconds, $\langle c_d \rangle$ is calculated at this distance $d$.

*Steps 4 and 5 are repeated for other values of $d$.

Now, for each distance $d_i$, I have an average count over 100 seconds, $\langle c_i\rangle$, and an associated standard deviation of the 10 readings, $\sigma_i$.
I then have a set of $\left\{c_i \pm \sigma_i\right\}$.
My question is therefore this: can I simply subtract $c_{BG} \pm \sigma_{BG} $ from each $c_i \pm \sigma_i$, and then propagate the errors to find the average count rate, $\left\langle N\left(c_{{d}_{i}}\right)\right\rangle$ at each $d_i$? If not, how else should I go about dealing with the background radiation?
My end goal is to plot the logarithm of the average count rate, $\ln(\left\langle N\left(c_{{d}_{i}}\right)\right\rangle)$, on $\ln d$ and determine the gradient—ideally $\thicksim -2$.

A: If you think of the problem in terms of random variables, it becomes easy. You have two random variables: The first one $X_1$ for the background noise, and the second one $X_2$ for the radioactive decay.  Both follow a Poisson distribution.
\begin{align}
X_1 &\sim Pois(\lambda_1) \\
X_2 &\sim Pois(\lambda_2)
\end{align}
For the Poisson distribution we know that the decay rate is equal to the expectation value as well as to the variance, $\lambda = E[X_1] = Var[X_1]$. Thus, the expectation value is a "good" estimator for the rate parameter. Hence, we use $\lambda_1 \approx \bar{N}_{BG}$.
Now, we can show that the sum of two independent Poissonian random variables is again Poissonian,
$$
X_1 + X_2 \sim Pois(\lambda_1 + \lambda_2)
$$
(Note that here we assume that the decay product is not radioactive)
Thus, the estimate of $\lambda_2$ is given
$$
E[X_1 + X_2] = E[X_1] + E[X_2] \Rightarrow \lambda_2 = E[X_2] = \ldots$$
For the standard deviation of $\lambda_2$ we use $Var[X_1 + X_2] = Var[X_1] + Var[X_2]$. Solving for $Var[X_2]$ and taking the square root, we obtain
$$
\sigma_2 = \sqrt{Var[X_1 + X_2] - Var[X_1]}
= \sqrt{E[X_1 + X_2] - E[X_1]}
$$


text:
Q: How to use GStreamer interlace element? I have a source of progressive video that I want to convert to interlaced fields. From one progressive frame, I want to generate two interlaced fields, each containing either the odd or the even lines.
In GStreamer terminology, each input buffer contains one progressive frame that I want to convert into two buffers, each containing one field.
I was expecting the first pipeline below to produce 20 files of size 640 * 240 * 2 and the second one to produce 10 files of size 640 * 480 * 2.
But they both produce 10 files of size 640 * 480 * 2, so the interlace element seems to do nothing.
Where am I going wrong here?
gst-launch-1.0 -v videotestsrc pattern=ball num-buffers=10 ! video/x-raw,format=YUY2,width=640,height=480 ! interlace ! multifilesink location=c:\x_%d.raw

gst-launch-1.0 -v videotestsrc pattern=ball num-buffers=10 ! video/x-raw,format=YUY2,width=640,height=480 ! multifilesink location=c:\x_%d.raw


text:
Q: Date based validations in asp.net My requirement is like so.
I need to maintain a holiday list. For that I need some validations while saving/editing an entry.
My DB contains a table with HolidayDate column. I have a textbox(jquery date picker) in the page. If the date what I choose has already been saved to the table, I should display an alert message.
Can anyone help me soon, please? Thanks in advance.
Aishvarya.

A: Try this:
<asp:TextBox ID="DateControl" runat="server"></asp:TextBox>
<asp:RangeValidator ID ="DateValidator" runat ="server" ControlToValidate="DateControl" ErrorMessage="Invalid Date" Type="Date" MinimumValue="01/01/1900" MaximumValue="01/01/2100" Display="Dynamic"></asp:RangeValidator>

Also more information about RangeValidator here:
http://msdn.microsoft.com/en-us/library/f70d09xt(v=vs.71).aspx
Sample:
http://www.w3schools.com/aspnet/showasp.asp?filename=demo_rangevalidator
Simplest way of server-side validation:
code behind:
protected void Button1_Click(object sender, EventArgs e)
{
     DateTime result;
     if (DateTime.TryParse(DatePicker.Text, out result))
     {
           //handle results
     }
     else
     {
           // e.g. highlight DatePicker or handle error
     }
 }

Form:
<asp:TextBox ID="DatePicker" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

Jquery validation sample:
<!doctype html>

  <meta charset="utf-8" />
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />

  <link rel="stylesheet" href="/resources/demos/style.css" />

Date: <input type="text" id="datepicker" />


text:
Q: MS Access Moving records into fields I have an ODBC connection to a database I don't own and can't change.  What I am looking to do is to make related records merge into one record.  The relationship is a 1 to many.
I have a student managment system and want to export a call out list which feeds an automated callout service (charged by Call).  I want to be able to call a house only once if there are multiple students living there.
Desired Call out file structure:
PHONE     Inst1                  Inst2                  Inst3
555-5555  John was absent today  Jane was absent today  Joe was absent today

as apposed to existing data:
PHONE     Inst
555-5555  John was absent today
555-5555  Jane was absent today
555-5555  Joe was absent today

Any suggestions?

A: My first inclination was to use a crosstab query; however, that could get a bit hairy.
What about cutting some VBA code in a module to concatenate them together and then insert in the other table (something like the following - completely untested and probably broken somewhere)?
dim strAbsent as string
dim currPhone as string
dim lastPhone as string
Dim db As Database
Dim rstAbsent As Recordset
Dim rstAbsentReport As Recordset

Set db = CurrentDb
Set rstAbsent = dbV.OpenRecordset("select * from Absent", _
                                    dbOpenDynaset, dbSeeChanges)
Set rstAbsentReport = dbV.OpenRecordset("select * from AbsentReport", _
                                        dbOpenDynaset, dbSeeChanges)

'...
do while not rstAbsentReport.EOF
    currPhone = rstAbsentReport("phone")
    lastPhone = currPhone
    do while currPhone = lastPhone _
            and not rstAbsentReport.EOF
        strAbsent = strAbsent & ";" & rstAbsentReport ("comment")
        'Yes I know concatenating strings this way is terribly inefficient

        rstAbsentReport.MoveNext
        if not rstAbsentReport.EOF then
            currPhone = rstAbsentReport("phone")
        end if
    last
    rstAbsent.AddNew
    rstAbsent ("call") = strAbsent
    rstAbsent.Update
loop
'... clean up of recordset variables left as an exercise


text:
Q: Angular template variable not getting updated I am facing difficulty in populating channels field which is part of md-select, I am evaluating and populating channels array in preInit function after making a websocket call,
<bunch of imports>

@Component({
  selector : 'app-ipmi',
  template : `
  <md-select name="channel" placeholder="Channel" (change)="switchChannel()" options = "channels">
  </md-select>
  <entity-form [conf]="this"></entity-form>
  `,
  providers : [ TooltipsService ],
})
export class IPMIComponent {
  @Input('conf') conf: any;

<bunch of variable declarations>

  public channels = [];
  public fieldConfig: FieldConfig[] = [

    {
    ...
    },
    .....,

  ];

  constructor(...) {}

  preInit(entityEdit: any) {
    entityEdit.isNew = true;
    this.ws.call('ipmi.query', []).subscribe((res) => {
      for (let i = 0; i < res.length; i++) {
        this.channels.push({label: res[i].channel, value: res[i].channel})
      }
    });
  }

}

A: <md-select> should contain <md-option> elements, and to display options based on channels array, you can iterate through it using *ngFor directive, like *ngFor="let channel of channels". So your HTML should be something like this:
<md-select name="channel" placeholder="Channel" (change)="switchChannel()">
  <md-option *ngFor="let channel of channels" [value]="channel.value">
    {{channel.label}}
  </md-option>
</md-select>


text:
Q: Convert data frame with following format into time series I have a data set as follows for the rainfall received by Karnataka. How can I convert it into a time series format in R?

A: With tidyr and zoo, this only takes a few steps. If you also load dplyr, you can pipe it. Assuming your table is called df...
library(dplyr)
library(tidyr)
library(zoo)

df %>%
    # use tidyr to convert the wide data to long
    gather(key = month, value = value, -Year) %>%
    # use zoo to create a year-month index
    mutate(yearmon = as.yearmon(paste(month, Year))) %>%
    # now make a zoo object of the values with that index
    with(., zoo(value, order.by = yearmon))


text:
Q: Relativistic free fall if I wanted to calculate how far a proton moving at horizontal speed of $0,96 c$ would fall (due to gravity $g$ vertically) passing through a space of $1$m (horizontally) - how do I calculate that? Do I need to use special relativity? Probably.. how do I do that?
Could I even use "normal" newtonian thoughts (as an approximation)?
Thank you

A: In relativity, an inertial frame of reference is a free-falling frame. In such a frame, there are no (local) effects of gravity. Suppose we adopt such a frame that has no horizontal motion relative to the lab. Then the floor of the lab is accelerating upward at $g$. Therefore the result is exactly what you would have expected from Newtonian physics: $(1/2)gt^2$, where $t$ is the time of flight.


text:
Q: How to serve a request by responding with another website's response? I have setup an e-commerce store using a e-commerce provider. I have my own subdomain (mysubdomain.ecommerce.com). I own mydomain.com. I'd like my store to live at mydomain.com/store. In other words, I'd like mydomain.com/store to display whatever mysubdomain.ecommerce.com displays, without changing the url in the browser.
How would I accomplish this in Django?

A: What you are thinking is called proxying. Any web server can do it (Nginx, Apache). Unlike Django, web servers are designed to accomplish this function and give better performance and reliability with much less hassle.
In theory one can write custom views to do proxying in Django, but it is approach of more pain.
I suggest you take a look example for Nginx.
However the client application (mysubdomain.ecommerce.com) must support rewriting URL and setting canoncial URL of the site to mydomain.com/store. If your ecommerce providing doesn't support it you might have a lot of issues. Again, in theory, you can parse proxyed HTML and rewrite links, but it rarely works very well.
My suggestion is simply to contact your eCommerce provider (sounds like commercial, closed solution) and ask them how to do it.


text:
Q: How to permanently alter a js array object So I have a object array I am using to store data for my app. It's in a store file, using mobx. How come when I write some code to alter or add to a object in the array, that data is deleted upon a refresh?
Is there anyway to permanently alter the object so it persists through different sessions? (trying to avoid using a database, using the object as my database).
Here's a sample of the data
Bars: [
    {
      Name: "Bull and Finch Neighborhood Pub",
      Address: "11520 24 St SE",
      Latitude: 50.95231,
      Longitude: -114.00132,
      Reviews: [],
      Likes: 0,
      Specials: [
        {
          Monday: [
            { Desc: "Burgers", Price: "50% Off", Cat: "Burgers" },
            { Desc: "Coors Banquet Pints", Price: 5.5, Cat: "Drinks" }
          ],
          Tuesday: [
            { Desc: "Pizza and a Jug", Price: 26, Cat: "Pizza" },
            { Desc: "Draft Jugs", Price: "2$ Off", Cat: "Drinks" }
          ],
          Wednesday: [
            { Desc: "Wings", Price: 0.45, Cat: "Wings" },
            { Desc: "Import Draught", Price: "1$ Off", Cat: "Drinks" }
          ],
          Thursday: [
            { Desc: "Steak Sandwich", Price: 7.99, Cat: "Sandwiches" },
            { Desc: "Desserts", Price: "50% Off", Cat: "Dessert" },
            { Desc: "Bottles of Wine", Price: "50% Off", Cat: "Drinks" }
          ],
          Friday: [
            { Desc: "Entrees", Price: "2$ Off", Cat: "Entrees" },
            { Desc: "Original 16 Pints", Price: 5.5, Cat: "Drinks" }
          ],
          Saturday: [
            { Desc: "Boneless Wings", Price: 7.95, Cat: "Wings" },
            { Desc: "Specialty Drinks", Price: "1$ Off", Cat: "Drinks" }
          ],
          Sunday: [
            { Desc: "BBQ Brisket", Price: 14.99, Cat: "Entrees" },
            { Desc: "Ribs", Price: 0.45, Cat: "Entrees" },
            { Desc: "Jack Daniels", Price: 5.25, Cat: "Drinks" }
          ]
        }
      ]
    }

A: Simply put your data needs to be persisted and reloaded upon each request either using a database or local storage.

A: It sounds like the best way forward for you would be to use Node.js to write to file, and save your object to file. Then later read from file.
Take a look at the fs API for how to do that.
https://nodejs.org/api/fs.html


text:
Q: istream operator skips space characters void transferData(ifstream& input_file, ofstream& output_file)
{
    char ch;
    while (input_file >> ch) {
        if ((ch >= 97 && ch <= 118) || (ch >= 65 && ch <= 86)) {
            ch += 4;
            output_file << ch;
        }
        else if ((ch >= 87 && ch <= 90) || ch >= 119 && ch <= 122) {
            ch -= 22;
            output_file << ch;
        }
        else if (ch == 32) {
                output_file << '\t';
        }
        else
            output_file << ch;

    }
}

The code works, but it does not add spaces between the words in the output file. What is the reason for that?
Input: "This text is to test the program."
Output: "Xlmwxibxmwxsxiwxxlitvskveq."

A: You use std::noskipws.
while (input_file >> std::noskipws >> ch)

By default the streams skip white space before reading into a variable. This is somewhat of a hangover from C scanf() functions (which skipped white space before reading into a variable).
Note: This is a property of the operator>>.
You can also use iterators to do the job:
std::istreambuf_iterator loop(input_file);
std::istreambuf_iterator end;

for(;loop != end; ++loop) {
   ch = *loop;
   // STUFF
}

If you have C++20 we can make that look nicer with a range based loop:
// Note I don't have a C++20 compiler so sort of guessing based on API.
for(char ch: std::ranges::range(std::istreambuf_iterator loop(input_file), std::istreambuf_iterator{}) {
     // STUFF
}


text:
Q: Flutter : insert data to tables in sqflite at initialaztion database I have created helper class for sqlite database and tried to insert data to tables in intialzing database as this :
class DbHelper {
  static final DbHelper _instance = DbHelper.internal();
  factory DbHelper() => _instance;
  DbHelper.internal();
  static Database _db;
  //---------------- Create database method-------------------
  Future<Database> createDatabase() async {
    var teamsTable = SqliteData().teams;
    var clubsTable = SqliteData().clubs;
    if (_db != null) {
      return _db;
    }
    String path = join(await getDatabasesPath(), 'clubsFantasy.db');
    _db = await openDatabase(path, version: 1,
        onCreate: (Database db, int v) async {
      await db.execute('''
          create table teams (club varchar(50) ,
          price integer ,
          surename varchar(3),
          id integer,
          league varchar(20))
          ''');
      await db.execute(
         'create table clubs (id integer ,club varchar(50) ,league_id integer,price integer ,surename varchar(3),  league_name varchar(20),counter integer , selected varchar(5))');
      teamsTable.map((e) => {db.insert('teams', e.toMap())}).toList();
      clubsTable.map((e) => {db.insert('clubs', e.toMap())}).toList();
    });

    return _db;
  }
//---------------- load data method---------------------
  Future getTeamsData() async {
    Database db = await createDatabase();
    return db.query('teams');
  }

  Future getClubsData() async {
    Database db = await createDatabase();
    return db.query('clubs');
  }
}

I call database at splash screen to create database and insert data to tables:
DbHelper helper;
  @override
  void initState() {
    helper = DbHelper();
    checkLogin();
    helper.createDatabase();
    super.initState();
  }

now I want to display data and used it in provider ,I did this :
class TeamsProvider with ChangeNotifier {
  DbHelper helper;
  get clubs => helper.getClubsData();
  get teams => helper.getTeamsData();
}

I called teams in future builder in screen :
Widget build(BuildContext context) {
    return Consumer<TeamsProvider>(
      builder: (context, teamsProv, child) {
        return FutureBuilder(
            future: teamsProv.teams,
            builder: (context, snapshot) {
              if (snapshot.hasData) {.....etc

I get error :
The method 'getTeamsData' was called on null. Receiver: null Tried calling: getTeamsData()

A: I am not sure but try declaring your DbHelper like this:
class DbHelper {
    factory DbHelper() => DbHelper._internal()
    DbHelper._internal();

DbHelper methods like:
   static Future<Database> createDatabase() async {...
   static Future getTeamsData() async {...
   static Future getClubsData() async {...

And then:
class TeamsProvider with ChangeNotifier {
    get clubs => DbHelper.getClubsData();
    get teams => DbHelper.getTeamsData();
}


text:
Q: Wordpress do_shortcode function while calling the_slug to replace the category attribute I am trying to use this shortcode in my theme and I want the category to become the slug for whatever page it's on.
<?php echo do_shortcode('[image-carousel category="'.the_slug().'"]'); ?>
Now while this does achieve that function, it is also spitting out the actual text of the slug right above the image. I tried using variables, also tried escaping the quotes, and a bunch of other stuff yet the above script is the only way I've gotten it to display the proper image, the only problem is the visible text.
How can I avoid that from happening?

A: All functions that start with the_ will echo its results, and you don't want that within a do_shortcode().
Use:
$slug = get_post( $optional_id )->post_name;
echo do_shortcode('[image-carousel category="'.$slug.'"]');


text:
Q: Step size for controlling stepper motor I am using a PK243 - 03A unipolar stepper motor, its step angle is 1.8 degrees. I am planning to step the motor periodically on it's starting frequency which is coming out to be 1.3kHz, to see how it makes 200 steps per revolution, what I cannot decide is the step size of the pulse. How long should be the pulse high to get 1.8 degrees?

A: The pulse duration is irrelevant. It's the number of pulses that matter.
In this case, you need 200 step cycles per revolution. You derive the pulse duration from how rapidly you want to step.
I'm assuming you are using a driver IC, which takes step/direction pulses. If you're driving the motor directly, things are more involved.


text:
Q: How to hide cell if "active" column is "no" in Swift 3/Xcode 8 I'm just in the process of putting a prototype app together in Swift 3.0.
At the minute, all API information is Parsed in to table cells. What I was hoping to do was introduce the facility where if I set an "Active" column in my database to "no" then how could I prevent that cell from showing in the table view?
Currently the code is this:
func configure(offence: Offence) {
   if let name = offence.name, let act = offence.act {
       self.textLabel?.text = name
       self.detailTextLabel?.text = act
   }

I've tried playing around with if/else statements but I'm not having much luck.

A: if your Offences have an active property you can use it to filter your server response and only show those with the active property set to true. something like this:
struct Offence {
    var name: String
    var active: Bool
}

class YourViewController: UITableViewController {
    // all the offences you get from the server
    let offences: [Offence] = []

    // only the active offences - use those as your datasource!
    var visibleOffences: [Offence] {
        return offences.filter { $0.active }
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return visibleOffences.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "YourCell", for: indexPath)
        cell.textLabel?.text = visibleOffences[indexPath.row].name
        return cell
    }

}


text:
Q: Session files going over 17GB Got warning from server regarding Disk space getting full.
After checking into file manager I found 17.2 GB of file size in session folder.
When looked into var/session folder, I can see unusual size ranging from 400 MB to 2.5 GB and years of these files as 2031, 1987, 1970, 1990.
Is it normal to have session files with size 2GB and greater?
Even unable to delete these unusual session files (Response:   550 Could not delete sess_2fjtnha6k4be02r2p1ofdh1qt4: Invalid argument)
Any suggestions?

A:
Clear it once or twice a day just to be safe

Don't. Unless you intentionally want to disrupt sales by obliterating customer carts.

I put sessions in RAM

Don't. This is a common (and dangerous) Magento myth.

*

*If its a single-sever deployment, use files and don't look back.

*If its multi-server, use Redis.

Memcache should not be considered unless either you care not for persistence, or you are hitting the single threaded behaviour of Redis (very unlikely).

Traffic is around 2k-5k

Session files are often ~5kB, if you are using 256,000kB, then that's around 50k per user, something isn't right.
I wouldn't be largely concerned about session storage utilisation, if its consuming space, so be it. I'd only be worried when you start seeing >2GB utilisation and it becomes a performance bottleneck.

Is there a way to check this

Open one of the largest session files in a text editor and you'll find the cause. It will be a rogue 3rd party extension storing information in sessions that perhaps shouldn't be.


text:
Q: Is User Input Possible in PDDL I am using PDDL to define a path for a robot. The idea is that the robot should move 'x' no. of items from a room to outside the house . The variable "x" depends on the room. The robot should start from one room which the user tells has x no. of items. After transferring all the items it should move to next room and then the user tells how many items are there. The chain continues like this until all the rooms are emptied. The total no. rooms are finite but unknown.
I wanted to ask is there a way to give user inputs in pddl?
I am using the following example to build my code. In the mentioned code the no. of rooms and items are already initialized which is not the case in my workspace.
http://www.cs.toronto.edu/~sheila/2542/w09/A1/introtopddl2.pdf

A: In short, no that's not possible. You could perhaps have a higher-level executive that queries, and then creates a subproblem that can be solved with a planner. It's unclear if you'd really need a planner at that point, though.

A: You'd need a program that calls your planner and generates PDDL on-the-fly. In that program you elicit the user input, and then add the particular room x as part of the goal definition in your generated PDDL. This you then pass to the planner, possibly via writing it to a file (depending on how you interface with the planner).
See this paper for a related problem where an off-the-shelf planner is integrated into a game: Bartheye, Olivier and Eric Jacopin (2008) Connecting PDDL-based off-the-shelf planners to an arcade game


text:
Q: param is missing or the value is empty: purchase I'm trying to pass the following inside a def create method. The create method is in the transactions controller.
@purchases = current_shop.purchases.build(purchase_params)
@purchases.save!

private

def purchase_params
  params.require(:purchase).permit(:shop_id, :subscription_id, :created_at)
end

And returns this error:
ActionController::ParameterMissing in TransactionsController#create
param is missing or the value is empty: purchase

Update 1
Logs:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"aJWUUEwgtG0o52MEHSOcNETj1Ueo+4NvLBD+y5LMPHxtHnOEe1Zgs3IMADdv5y+dbl7Ecgr8LMEjIG6sws9kqg==", "payment_method_nonce"=>"bf7458d2-d3a4-02c9-2593-526174f50822"}
  Cart Load (0.1ms)  SELECT  "carts".* FROM "carts" WHERE "carts"."id" = ? LIMIT ?  [["id", 93], ["LIMIT", 1]]
  Shop Load (0.3ms)  SELECT  "shops".* FROM "shops" WHERE "shops"."id" = ? ORDER BY "shops"."id" ASC LIMIT ?  [["id", 13], ["LIMIT", 1]]
  LineItem Load (0.4ms)  SELECT "line_items".* FROM "line_items" WHERE "line_items"."cart_id" = ?  [["cart_id", 93]]
  Subscription Load (0.1ms)  SELECT  "subscriptions".* FROM "subscriptions" WHERE "subscriptions"."id" = ? LIMIT ?  [["id", 2], ["LIMIT", 1]]
Completed 400 Bad Request in 2899ms (ActiveRecord: 1.1ms)

ActionController::ParameterMissing (param is missing or the value is empty: purchase):

app/controllers/transactions_controller.rb:60:in purchase_params'
app/controllers/transactions_controller.rb:31:in create'

Update 2

<%= notice %>

New Transaction

  <%= form_tag transactions_path do%>

Please enter your payment details:

    <%=submit_tag "Pay #{@cart.total_price}$", class: "button mt1" %>
  <%end%>


text:
Q: WMS layer is not overlaying exactly when zooming out. How to add WMS layers to google map layer in openlayers? My openlayers code is as follows. But there is shift in between both the layers. How to rectify it?
map = new OpenLayers.Map( 'map_element',{} );
        var gsat = new OpenLayers.Layer.Google(
            "Google Satellite",
            {type: G_HYBRID_MAP,
             numZoomLevels: 22,
             isBaseLayer: true,
             'displayInLayerSwitcher':false},
              {sphericalMercator: true}
            );
        var roads = new OpenLayers.Layer.WMS(
        "Roads", "http://localhost:8088/geoserver/cite/wms",
        {layers: 'cite:viz_roads',
                     isBaseLayer: false,
                     transparent: true,
                     opacity: 1.0}
        );

        var org = new OpenLayers.Layer.WMS(
        "points of interest", "http://localhost:8088/geoserver/cite/wms",
        {layers: 'cite:organisations',
                     isBaseLayer: false,
                     transparent: true, opacity: 1.0}
        );
        map.addLayers([gsat,roads,org]);
        map.addControl(new OpenLayers.Control.LayerSwitcher({}));

if(!map.getCenter()){
map.setCenter(new OpenLayers.LonLat(83.324947,17.732909), 14);
}
    }

This is the snapshot of the map:

Observe the shift from position 1 to 2. 1 is the actual position where the feature should be. It is rectified automatically when I turn layer off and on. But how to rectify this error while zooming?


text:
Q: Why is a disk with a $0$-cell for every boundary point not a CW-complex by the inductive definition? In Hatcher's Algebraic Topology, he defines a CW complex as follows:

He proves in Proposition A.1. that any space constructed this was will satisfy the closure finiteness property, and then gives an example of a cell complex which doesn't:

My question is, how is this a counterexample? It seems to me that this can be constructed in the way he presents in his CW complex definition. Can someone explain to me what's going on?

A: In part (2) of the definition, "map" means continuous map, so the attaching maps $\varphi_\alpha: S^{n-1}\to X^{n-1}$ are required to be continuous.  This is not true in the counterexample: the $0$-skeleton is $S^1$ with the discrete topology (by part (1) of the definition), and so the identity map $S^1\to X^0=S^1$ which would attach the $2$-cell is not continuous (the domain has the usual topology of $S^1$ but the codomain has the discrete topology).


text:
Q: What are evanescent fields? I am not able to understand what is the origin of the evanescent field, how do they interact and what is the physics behind it.

A: I can't give you the full works on this but for a transmitting antenna, the evanescent fields are the E fields and H fields directly produced by the antenna and localized about the antenna. Eventually they can give rise to an electromagnetic wave but this isn't an evanescent field.
Typical usage that I'm aware of is magnetic field coupling between two slightly distance devices such a wireless charger for a phone. Magnetic field flux density generally reduces with distance as a cube law unlike regular EM waves whose E or H content reduce with distance rather than distance squared (EM power).

A: Near field and far field are names given to mathematical expressions. Consider a radiation source and a imaginary sphere around it. The power crossing the sphere is given by
P= (4πr^2)P'= 4π(C1 + C2/r + C3/r^2+ C4/r^3+ ….) , where P' is the power density.
The first term is a constant, so no matter the size of the sphere this power will always be there. In other words, this power will always be radiated from the source. Thus, it is only due to radiated field.
Now, at small r (near source), all terms involving r will be significant and the constant term is insignificant. The power expression at small r thus becomes (approximately) P= (4πr^2)P'= 4π( C2/r + C3/r^2+ C4/r^3+ …). This collective expression is then termed to be the near field.
Hence the equation is then lumped into two terms, the first being the radiated field term, and the exponentially decaying fields lumped into another term called the 'evanescent fields'(since their intensity decay with distance).
This grouping of the exponentially decaying components of the near field non-radiative EM field types are then mathematically examined as a single term called the evanescent fields, which is not in itself a physical entity, but a summation of the effects and characteristics of the various EM waves present near the source.


text:
Q: Audit data changes with Debezium I have a use case where I want to audit the DB table data changes into another table for compliance purposes. Primarily, any changes to the data like Inserts/Updates/Deletes should be audited. I found different options like JaVers, Hibernate Envers, Database triggers, and Debezium.
I am avoiding using JaVers, and Hibernate Envers as this will not capture any data change that happens through direct SQL queries and any data change that happens through other applications. The other issue I see is we need to add the audit-related code to the main application code in the same transaction boundary.
I am also avoiding the usage of database triggers as we are not using triggers at all for any of the deployments.
Then I left with Debezium which is promising. But, the only concern that I have is that we need to use Kafka to leverage Debezium. Is Kafka's usage is necessary to use Debezium if both the primary table and the audit table sit in the same DB instance?

A: Debezium is perfect for auditing, but given it is a source Connector, it represents just one part of the data pipeline in your use case. You will capture every table change event (c=create, r=read, u=update, d=delete), store it on a Kafka topic or local disk and then you need a Sink Connector (i.e. Camel Kafka SQL or JDBC, kafka-connect-jdbc) to insert into the target table.
For the same transaction boundary requirement you can use the Outbox Pattern if the eventual consistency is fine. There is also an Outbox Event Router SMT component that is part of the project.
Note that Debezium can also run embedded in a standalone Java application, storing the offset on local disk, but you lose the HA capability given by KafkaConnect running in distributed mode. With the embedded mode, you are also swtiching from a configuration-driven approach to a code-driven one.

A: I found Debezium to be a very comprehensive solution, and it is open source backed by Redhat. That gives it not only the credibility, but the security that it is going to be supported.
It provides a rich configuration to whitelist, blacklist databases/tables/columns (with wild card patterns), along with controls to limit data in really large columns.
Since it is driven from BinLogs, you not only get the current state, you also get the previous state. This is ideal for audit trails, and you can customize building a proper Sync to elastic topics (one for table).
Use of Kafka is necessary to account for HA and latency when bulk updates are made on DB, even though Primary and Audit tables are in same DB.


text:
Q: AJAX & ASP.net, Referencing server controls in external file I've got some JavaScript in an ASP.NET page that looks like this:
var list = $get('<%=Topics.ClientID %>');

I have many functions written now where this syntax is used, and I would like to centralize my JavaScript and move this into an external JavaScript file.  This breaks however, since 'Topics' cannot be found.
What is the best strategy for getting this to work?  I assume I should pass the control/control information as a parameter to the function, but I can't seem to get the syntax to work.  Any suggestions?

A: You should create a javascript method from inside the usercontol which returns the client side element. Then in your other page/control, just access that method
In User Control
 <script language="javascript">
     function GetTopics() {
          return = $get('<%=Topics.ClientID %>');
     }
 </script>

In other page/control
 <script language="javascript">
     var list = GetTopics();
 </script>

Edit - The problem you are facing is you need Topics.ClientID where it doesn't exist. So the only real way to bridge that gap is to put it in a common place. If you really don't want to do that, you can try and select your element by some other criteria. If you are using jQuery, you could mark an element with a class of Topics then find it with $(".Topics").

A: It's a common problem for ASP.NET JS development. As for me, I'm using same approach each time and it looks fine.
I'm used to OOP in Javascript, so most my JS external files look like:
function CouponManager()
{
}

And in .aspx code i do:
<script language="javascript">
    var couponManager = new CouponManager();
</script>

If I need to pass some parameters I change the declaration of class to:
function CouponManager(params)
{
    // .. stuff here

    this.initialize = function(initParams)
    {
       // .. accessing initParams variable for server control IDs
    };

    this.initialize(params);
}

And from .aspx code I do the following:
<script language="javascript">
    var couponManager = new CouponManager
    ({
        txtCouponNameId = '<%= txtCouponName.ClientID %>',
        txtCouponDescriptionId = '<%= txtCouponDescription.ClientID %>'
    });
</script>

This approach allows me to separate JS from .aspx page and have all server control dependencies in a single  tag.

A: if you know that you only have one server control called "Topics" per page, and you use naming conventions you can inherit from whatever the control Topics is (maybe it's a HiddenField? you don't specify) and override its ClientId getter to return its server id like this:
http://andreascode.wordpress.com/2009/04/27/tiny-drips-of-aspnet-juice/
then you can know in your javascript files that there will be a hidden field in the page with the id set to "Topics" and use that directly.
depending on your domain/situation this could either save you a lot of time or screw you over big time.


text:
Q: linq max lazy evaluation I'm having a bit of trouble understanding how lazy evaluation relates to the linq Max operator.
This is my code:
        var someList = new List<someType>
        {
            new someType { decimalValue = 32 }
        };

line1:     var valA = someList.Any() ? someList.Max(s => s.decimalValue) : 0.0M;
line2:     var valB = someList.Any() ? someList.Max(s => s.decimalValue) : 0.0M;
line3:     var valC = valB;
When stepping through the code I see the following behaviour:
After line 1 has executed, valA = 0, valB = 0, valC = 0
After line 2 has executed, valA = 32, valB = 0, valC = 0
After line 3 has executed, valA = 32, valB = 32, valC = 32
Why does valA only show a value after valB is assigned, and why does valB only show a value once valC is assigned?
Below is a screenshot of my debugger.  I guess there must be something non-standard about my IDE.

(source: toastermagic.co.uk)

A: The Max operator executes immediately, it is not deferred at all.  What you're seeing is just the normal behavior of the debugger.  When it has a line highlighted it means, "I'm about to run this line" rather than, "I just ran this line".  You'll always need to be on the 'next' line to see the results of a given line of code.
It seems that you have accounted for this.  The fact that you are see all changes (this shouldn't be just LINQ specific) a line late probably means your source code and the executable are a bit out of sync.  You should do a clean and re-bulid of the solution and then everything should be fine.  I'm guessing that you made some small modification to the source code that didn't get picked up properly in a build and so the line numbers in the executable vs. the source code are each off by one.
If something is really, really wrong, you can try moving the code to a new project entirely (if your code base is small enough) in an attempt to get rid of whatever corrupted or broken file/setting is causing this problem.

A: Cannot Replicate:
    static void Main(string[] args)
    {
        var data = (from n in Enumerable.Range(0, 10)
                    select new { value = (decimal)n })
                   .ToList();

        var valA = data.Any() ? data.Max(s => s.value) : 0.0M;
        Console.WriteLine("A = {0}, B = {1}, C = {2}", valA, 0, 0);

        var valB = data.Any() ? data.Max(s => s.value) : 0.0M;
        Console.WriteLine("A = {0}, B = {1}, C = {2}", valA, valB, 0);

        var valC = valB;
        Console.WriteLine("A = {0}, B = {1}, C = {2}", valA, valB, valC);

        Console.ReadLine();
    }

Works as expected.
Looks to be a misread of the debugger.