text:
Q: After adding a user document to mongo collection; How to show that name on their profile page? I want a user to be able to create a profile;
then be directed to a page which shows their username.
The user registration part is working correctly:
app.post('/users',
    function (req, res) {
        var hashedPassword = Users.hashPassword(req.body.Password);
        Users.findOne({ Ainm: req.body.Name })
            .then(function (user) {
                if (user) {
                    return res.status(400).send(req.body.Name + "Name already in use.");
                } else {
                    Users
                        .create({
                            Name: req.body.Name,
                            Password: hashedPassword,
                            Email: req.body.Email
                        })
                        .then(function (user) {
                            res.status(201).sendFile(path.join(__dirname, "public", "profile.html"));
                        }).catch(function (error) {
                            console.error(error);
                            res.status(500).send("Error: " + error);
                        })
                }
            }).catch(function (error) {
                console.error(error);
                res.status(500).send("Error: " + error);
            });
    });

but can anybody suggest how to send their data from the server to the client, in order to show  user's name on the profile page to which they are being redirected?
the client side html is like this:

      <form action="/users" method="post">

        <input type="text" name="Ainm"  placeholder="Ainm">

        <input type="password" name="Password" placeholder="Passfhocal" >

        <input type="email" name="Email" id="email" placeholder="seoladh r-post">

        <input class="form-check-input" type="checkbox" value="" id="defaultCheck1">

          Nuachtlitir

        <input type="submit" class="btn btn-success btn-block" id="register" value="cláraigh">
      </form>

A: You can use ,
res.redirect('/users/${req.body.Name}')

and setup a new route to display user details , using their names as id to figure out other details (duplicate names will cause conflict).

A: Use jquery's .ajax() to send the data from clientside to server side, as previously:

$('#btnSendMsg').click(function () {
  $.ajax('/addMsg', {
      type: 'POST',  // http method
      data: { myData: usrMsg },  // data to submit
      success: function () {
          usrMsg = $('#output').html()
          // alert(usrMsg)

          $('#output').fadeOut();
          setTimeout(function () {
              $('#output').empty();
              $('#output').fadeIn();

          }, 500)
      }
  });
});

The server requires a mongoose schema to liase with db. Components should have a few run-throughs implementing data storage.
Respond from server with .json representing eventual db.
>//client-side.js

> let gotIt = [];
> $.ajax('urlOfData', { dataType: 'json' }).then(function
> (response) {  gotIt = response;   //
> alert(JSON.stringify(response)) })


text:
Q: Interaction of matter with EM fields For the interaction between electromagnetic fields and matter,

*

*when do we have to include quantization of the EM field and when we can ignore it?

*when do we have to include quantization of atomic energy levels and when we can ignore it?

Update: I am aware that part of the answer might depend on the accuracy we are looking for. Part of the problem here is that I do not know how to estimate such things, or what quantity will quantify the accuracy we are looking for which can tell us if we can ignore quantization of either energy levels or the fields or not.

A: I'm not sure there is a generic answer to your questions other than the trivial "don't bother including the quantization when the accuracy of your result isn't compromised by making this approximation".  I know that doesn't really help much, because you may not be able to verify this until you've done the calculation including the quantization anyway.  You may have no choice in the matter - modelling everything at a microscopic level may just be intractable.
Sometimes the answers as to when you have to do the full quantum calculation are surprising.  For example, it is a common belief that explanation of the photoelectric effect requires you to treat the electromagnetic field quantum mechanically - i.e. you need photons.  However, computations in Mandel and Wolf reveal that the observed experimental outcome can be obtained by treating the radiation purely classically (but the atomic electrons quantum mechanically).
(Of course light does have a quantum nature, as revealed by photon antibunching).

A: Generally speaking, the answer to both questions is linked to some number becoming increasingly large so that, for atoms you have a large density of higher excited states (think to Rydberg atoms as an example) or for electromagnetic field one has such a large number of photons that a coherent state is a good description of it and an average field can be safely taken. Then, quantum fluctuations are negligible small as these numbers increases.
In order to make all the argument quantitative, let me consider a standard Hamiltonian for radiation-matter interaction for hydrogen-like atoms, in a non-relativistic limit,
$$H=H_a+H_f+H_i=H_f-\frac{\hbar^2}{2m}\Delta_2-\frac{Ze^2}{r}-{\bf d}\cdot{\bf E}$$
where I have used an equivalent form for the interaction. Now, we can always rewrite this through a complete set of atomic states and this will give (the continuous part of the spectrum is implicit in the summation)
$$H=H_f+\sum_nE_n|n\rangle\langle n|+\sum_{m,n}|m\rangle\langle n|{\bf d}_{mn}\cdot{\bf E}$$
but we can do the same also for the field. Assuming this monochromatic and using coherent states $|\alpha\rangle$, that we know are overcomplete $\langle\alpha|\beta\rangle=$, we can use the resolution of identity (e.g. see here)
$$I=\int\frac{d^2\alpha}{\pi}|\alpha\rangle\langle\alpha|$$
that will produce
$$H=H_f+\sum_nE_n|n\rangle\langle n|+\sum_{m,n}|m\rangle\langle n|{\bf d}_{mn}\cdot\int \frac{d^2\alpha}{\pi}\frac{d^2\beta}{\pi}\langle\alpha|{\bf E}|\beta\rangle|\alpha\rangle\langle\beta|.$$
Now, we are a step away from our conclusion. Indeed, we should not that $|\alpha|^2=N$, being $N$ the number of photons. So, the interaction part of the Hamiltonian can be promptly evaluated as
$$\langle\alpha|{\bf E}|\beta\rangle=\tilde{\bf E}(\alpha,\beta)e^{-\frac{1}{2}|\alpha-\beta|^2}$$
and, for a very large $N$, the integral will have a dominant contribution and the coherent state can be assumed practically orthogonal. This will justify the use of a classical approximation through the averaged field.
This argument can be repeated for the atomic states, if we introduce the operators (see here) $\sigma_{nm}=|n\rangle\langle m|$, $\sigma_{nm}^\dagger=|n\rangle\langle m|$ and $\sigma_{nm}^3=(1/2)(|n\rangle\langle n|-|m\rangle\langle m|$ forming an su(2) algebra. We can use now atomic coherent states and arrive to the same conclusion as above, provided the atomic state is large enough. This is the rationale behind this kind of approximations normally used in quantum optics.

A: In general, a semi-classical approach is easier to handle mathematically and is taught before attacking the full quantum description. I don't know if there is are any hard and fast rules on what approach to use, but having experimental data would be the best way to check. I don't know about other areas, but in nonlinear optics when the light fields are intense, a semi-classical approach works just as well as a fully quantum approach. (Semi-classical: Atomic part is quantized while the Optical part is a classical wave). In many cases, it is relatively straightforward to go from the semi-classical picture to the quantum picture (ex: replace a classical EM Field with a coherent state).
There are many cases where a semi-classical approach fails and then you have no choice but to recast the problem using a fully quantum picture. To summarize, it is all about convenience and what you are after. A fully quantum picture is definitely richer, but may not be necessary.

A: This question has been a personal crusade of mine for the last 20 years. Around that time I figured out that the usual explanation for the photo-electric effect was based on basic misconceptions about the way waves transferred energy. To put things in a nutshell, if the usual power density argument were taken literally, then not only the photo-electric effect but such commonplace devices as the crystal radio should be "classically impossible". It was almost ten years later that I figured out the explanation for the Compton effect based on standing waves, and I was hugely disappointed when I learned that Schroedinger had already published my explanation in 1927.
Since then I have put together two more pieces of the puzzle. The Black Body Spectrum was a tough one until I figured out how to calculate the equilibrium between a mechanical oscillator and the radiation field. Then I was able to show that the classical radiation field had to follow the natural equilibrium of a system of mechanical oscillators, and not vice versa. If the equipartition theorem failed at the mechanical level (which it does), then you don't need to quantize the electormagnetic field to get the Planck distribution: it follows automatically from the mechanical equilibrium. I explain this in a series of blogposts beginning with this one in my blog "Why I Hate Physics".
The other big problem I solved was how to explain the very baffling question of the flecks of silver appearing on a photographic plate when exposed to the light of a distant star. According to classical theory the energy of light can be made arbitrarily diffuse. How then can it accumulate with sufficient intensity to provide the significant amount of energy needed to drive the chemical reduction of Ag+ to metallic silver in the silver bromide crystal? I was able to explain this by showing that the energy for the transition is already available in the detector system, namely the silver bromide crystal. It is not enough to look at the enthalpy of the transition; you must really consider the Gibbs Free Energy, which includes a term for the entropy. Treating the crystal as a solid solution of metallic silver and silver bromide, it is easily shown that at the very low concentrations present in a photographic film, the chemical transition is very nearly spontaneous. So no bunching of energy in the form of photons is required.
I also demonstrate a mechanism whereby the energy of the crystal is concentrated at the point of detection. I call this phenomenon Quantum Siphoning and it is explained in the linked article.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extracting characters from a mixed format csv file using Pandas So, I have a .csv file which looks like this:
station_id year january february ... december
210018     1916 nodata  221          417a
210018     1917 17b     98           44
....
210252     1910 54e     110          nodata
210252     1911 99d     24i          77
...

I need to extract letters from a to i (a-i) from the data. These letters mean numbers of missing days per month: a means 1 day and i means 9 missing days. Right now I don't care about 'nodata' cells. After extracting letters from data cells, I want to calculate total number of missing days per month:
station_id year january february ... december N_missingdays
210018     1916 nodata  221          417      1(a)
210018     1917 17      98           44       11(b+i)
....
210252     1910 54      110          nodata   8(e+c)
210252     1911 99      24           77       13(d+i)

Probably, the best way to do it, is to create a dictionary with station_id, year and number of missing days. Here is what I was trying to do:
with open('filepath') as file:
    file_reader = reader(file)
    for i,row in enumerate(file_reader):
        for j,item in enumerate(row):
           if item[len(item)-1]=='a':
                file_reader[i][j]=''
                print file_reader

But this function just deleting letters from the file and it doesn't work correctly. I don't know exactly how to extract letters from the .csv file and calculate their meaning.
The other thing I was trying to do is this:
with open('filepath') as file:
    file_reader = reader(file)
        next(file_reader)
        letters_dict={}
        for row in file_reader:
            station_id,year,months = row[1],row[2],row[4:]
            letters_list[station_id,year] = months.count('[0-9][a]') + ... + months.count('[0-9][i]') + letters_dict.get(year, 0) + letters_dict.get(station_id,0)

But this code writes in a dictionary only zeroes.


text:
Q: Prevent MITM for an AWS RDS MySQL instance What prevents anyone from sniffing (MITM) the traffic between an RDS MySQL instance (outside of a VPC) and a Web server if an SSL connection is not setup (default on AWS) ?

A: Generally nothing can prevent from MITM if both of these conditions are true:

*

*There's no encryption.

*The attacker can see the data i.e. has access to anything the unencrypted data goes through.

There are many Scenarios for Accessing a DB Instance in a VPC. I need to assume, based on your question, the worst case screnario: both DB Instance and EC2 Instance Not in a VPC:

While all the traffic might go inside Amazon's own (but public) network (which you could investigate with traceroute), this means that both of the conditions could be true. Therefore, you should either enable TLS or move your RDS in Amazon Virtual Private Cloud (VPC) – or even both.
This is inline with RDS documentation Security in Amazon RDS (only the related list items cited):

*

*Run your DB instance in an Amazon Virtual Private Cloud (VPC) for the greatest possible network access control. For more information
about creating a DB instance in a VPC, see Using Amazon RDS with
Amazon Virtual Private Cloud (VPC).

*Use Secure Socket Layer (SSL) connections with DB instances running the MySQL, Amazon Aurora, MariaDB, PostgreSQL, Oracle, or Microsoft
SQL Server database engines; for more information on using SSL with a
DB instance, see Using SSL to Encrypt a Connection to a DB Instance.

Even if you follow every step to increase security, you still need to trust in Amazon.


text:
Q: Merge 2 jQuery functions I have 2 jQuery functions that basicly are written the same except for their 1st lines:
$(document).ready(function() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
});

$(window).resize(function() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
});

so I was wondering if its possible to merge them into 1 some how?
As always thanks in advance.

A: You can trigger the resize event manually:
$(function() { // shortcut for $(document).ready(function() {...});
    $(window).resize(function() {   // bind the handler
        $('#foo').css({
            'height': $(window).height(),
            'width': $(window).width()
        });
    }).resize(); // trigger the resize event
});

or create an extra function and bind it to both events:
function resizeHandler() {
    $('#foo').css({
        'height': $(window).height(),
        'width': $(window).width()
    });
}

$(document).ready(resizeHandler);
$(window).resize(resizeHandler);

Btw. $(function(){...}); is a shortcut for $(document).ready(function(){...});.

A: var myFunction = function() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
}

$(document).ready(myFunction);
$(window).resize(myFunction);

A: Like this:
function yourfunc() {
 var h = $(window).height();
 var w = $(window).width();
 $('#foo').css({'height' : h});
 $('#foo').css({'width' : w});
}

$(document).ready(yourfunc);
$(window).resize(yourfunc);

Another way to call it (longer but more understandable) would be:
$(document).ready(function(){
   yourfunc();
});
$(window).resize(function(){
   yourfunc();
});

Both work. Hope this helps. Cheers

A: create a third function
function calculateSomething(){
  var h = $(window).height();
  var w = $(window).width();
  $('#foo').css({'height' : h, 'width' : w}});
}

Then call the function
$(document).ready(calculateSomething);

$(window).resize(calculateSomething);

A: You could also use do:
$(window).bind('load resize', function(e){
    $('#foo').css({'width' : $(window).width(), 'height': $(window).height()});
});


text:
Q: Como eliminar parênteses retos de algumas subpastas que tenho usando uma macro excel? Tenho uma pasta chamada "Franquiados" onde há enumeras subpastas com os nomes dos franquiados. Dentro da pasta de cada franqueado existem algumas subpastas cujos nomes contém parênteses retos.
Quero programar uma macro para eliminar os parênteses retos dessas subpastas sem alterar o restante nome das mesmas.
Por ex:
Nome Atual
C:\Users\jcoutinho006\Desktop\Franquiados\Fernando Soares\[04] Catálogo de Tratamento de Dados Pessoais_
Nome depois de usar a macro
C:\Users\jcoutinho006\Desktop\Franquiados\Fernando Soares\04 Catálogo de Tratamento de Dados Pessoais_
Alguém sabe dizer que código devo usar?

A: Isto pode ser realizado da seguinte maneira:

*

*Escolha da pasta principal

*Loop nas pastas e subpastas para listagem destas

*Escrever as pastas e subpastas encontradas numa planilha temporária chamada "temp", retirando "[" ou "]"

*Renomear com um loop para trás com Step -1 (pois há erros se começar a renomear pelas pastas e não subpastas)

Código de Exemplo
Sub Renomear_Pastas()
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Dim xDir As String
    Dim folder As Object
    Dim i As Long, linha As Long

    'Adiciona Planilha Temporária
    Dim temp As Worksheet
    SheetKiller ("temp")
    ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(Sheets.Count)).Name = "temp"
    Set temp = ThisWorkbook.Sheets("temp")

    'Escolher o Diretório
    Set folder = Application.FileDialog(msoFileDialogFolderPicker)
    With folder
        .Title = "Escolha a pasta"
    End With
    If folder.Show <> -1 Then GoTo CleanExit
    On Error Resume Next
    xDir = folder.SelectedItems(1) & "\"
    'Função para retirar Parêneteses Reto ou Colchetes
    retirar_pr xDir

    'Renomear
    linha = temp.Range("A" & temp.Rows.Count).End(xlUp).Row
    For i = linha To 2 Step -1
        Name temp.Cells(i, "A") As temp.Cells(i, "B")
    Next i

    'Sair do código
CleanExit:

    Set fso = Nothing
    Set fso_FOLDER = Nothing
    SheetKiller ("temp")
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.EnableEvents = True
End Sub

Sub retirar_pr(ByVal xFolderName As String)
    Dim xFileSystemObject As Object
    Dim xFolder As Object
    Dim xSubFolder As Object
    Dim xFile As Object
    Set xFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Set xFolder = xFileSystemObject.GetFolder(xFolderName)
    Dim nome_pasta As String, caminho As String, nova_pasta As String
    Dim linha As Long
    Dim temp As Worksheet
    Set temp = ThisWorkbook.Sheets("temp")

    'Loop em cada Subpasta
    For Each xSubFolder In xFolder.SubFolders
        'Procurar pela pasta e retirar [ ou ]
        nome_pasta = Right(xSubFolder, Len(xSubFolder) - InStrRev(xSubFolder, "\"))
        'Caso possua [ ou ]
        If InStr(nome_pasta, "[") Or InStr(nome_pasta, "]") Then
            linha = temp.Range("A" & temp.Rows.Count).End(xlUp).Row + 1
            nome_pasta = Replace(nome_pasta, "[", "")
            nome_pasta = Replace(nome_pasta, "]", "")
            caminho = Left(xSubFolder, InStrRev(xSubFolder, "\"))
            nova_pasta = caminho & nome_pasta
            'Escreve na planilha temporária os nomes antigos e novo da nova pasta
            temp.Cells(linha, "A") = xSubFolder
            temp.Cells(linha, "B") = nova_pasta
            retirar_pr xSubFolder.Path
        End If
    Next xSubFolder

    Set xFile = Nothing
    Set xFolder = Nothing
    Set xFileSystemObject = Nothing
End Sub

Public Function SheetKiller(Name As String)
    'Remove Planilha
    Dim s As Worksheet, t As String
    Dim i As Long, k As Long
    k = ThisWorkbook.Sheets.Count

    For i = k To 1 Step -1
        t = ThisWorkbook.Sheets(i).Name
        If t = Name Then
            Application.DisplayAlerts = False
            ThisWorkbook.Sheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
End Function


text:
Q: SwiftUI - Firebase, Sign In With Apple, custom Button I would like to create my own SignInWithAppleButton with my own design, following the guidelines of course.
I am having trouble translating the startSignInWithAppleFlow function from Swift to SwiftUI.
struct ContentView: View {

    var body: some View {
        ...
        AuthButton(title: "Connect with Apple", iconName: "appleIcon") {
            authViewModel.signInWithApple()
        }
        ...
    }
}

struct AuthButton: View {
    let title: String
    let iconName: String
    let action: () -> Void

    var body: some View {
        Button {
            action()
        } label: {
            RoundedRectangle(cornerRadius: 16)
                .fill(.clear)
                .frame(height: 80)
                .overlay(
                    Text(title)
                        .font(.regular16)
                        .foregroundColor(.black)
                )
                .overlay(
                    HStack {
                        HorizontalSpacer(width: 32)
                        Image(iconName)
                            .resizable()
                            .frame(width: 30, height: 30, alignment: .center)
                        Spacer()
                    }
                )
        }
        .buttonStyle(AuthButtonStyle())
    }
}

class AuthenticationViewModel: ObservableObject {
    func signInWithApple() {
        Unclear what should be here!
    }

    private func randomNonceString(length: Int = 32) -> String {
        precondition(length > 0)
        let charset: [Character] =
            Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._")
        var result = ""
        var remainingLength = length

        while remainingLength > 0 {
            let randoms: [UInt8] = (0 ..< 16).map { _ in
                var random: UInt8 = 0
                let errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random)
                if errorCode != errSecSuccess {
                    fatalError(
                        "Unable to generate nonce. SecRandomCopyBytes failed with OSStatus \(errorCode)"
                    )
                }
                return random
            }

            randoms.forEach { random in
                if remainingLength == 0 {
                    return
                }

                if random < charset.count {
                result.append(charset[Int(random)])
                remainingLength -= 1
                }
            }
        }

        return result
    }

    private func sha256(_ input: String) -> String {
        let inputData = Data(input.utf8)
        let hashedData = SHA256.hash(data: inputData)
        let hashString = hashedData.compactMap {
            String(format: "%02x", $0)
        }.joined()

        return hashString
    }
}

A: It looks like you're on step 2 of the documentation.
Your function would look like this:
func signInWithApple() {
  let nonce = randomNonceString()
  currentNonce = nonce
  let appleIDProvider = ASAuthorizationAppleIDProvider()
  let request = appleIDProvider.createRequest()
  request.requestedScopes = [.fullName, .email]
  request.nonce = sha256(nonce)

  let authorizationController = ASAuthorizationController(authorizationRequests: [request])
  authorizationController.delegate = self
  authorizationController.performRequests()
}


text:
Q: Implementing OnValueChange to a NumberPicker in Android I"m trying to add the onValueChangeListener to my number picker (np1) in android 4.2.2.
Here's what I have so far
public class main extends Activity  {
ViewFlipper vf = null;
HttpClient client = null;
private ArrayList<String> captionList = new ArrayList<String>();
ListView lv = null;
private String custid = null;
ImageView iv = null;
private int vfloginview = 0;
private int vflistview = 0;
private boolean vfsentinal = false;
NumberPicker np1 = null;
TextView totalcost = null;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mystuffmobile);
    vf = (ViewFlipper) findViewById(R.id.vf);
    client = new DefaultHttpClient();
    lv = (ListView) findViewById(R.id.lv);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    np1 = (NumberPicker) findViewById(R.id.np1);
    np1.setMinValue(1);
    np1.setMaxValue(400);
    //np1.setOnValueChangedListener;
    //np1.setOnValueChangedListener(onValueChange);

}

to try to test it's functionality I've been using this
public void onValueChange (NumberPicker np1, int oldVal, int newVal) {
    Log.v("NumberPicker", np1.getValue() +"");
}

Does anyone know an easy way to implement this listener without having my main activity implement NumberPicker.OnValueChangeListener?
Note: the only reason I'm opposed to having my main activity implement NumberPicker.OnValueChangeListener is because then I have to set main to abstract and my application won't run.

A: You're going to do this just like a click listener on a button.
np1.setOnValueChangedListener(new OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        // do something here
    }
});

A fully working example can be found here: http://samplecodez.com/android/numberpicker.php
Some stylistic points ...

*

*Main should be capitalized and it's a good practice to make it more descriptive like MainActivity.

*Use fields only when necessary.  I'm guessing you're not using most of those variables outside of onCreate() so make them local variables instead.

*TextView totalCost is your best named variable of the lot :)  Consider using verbose names.  You'll thank yourself 6 months down the road when you look back at this code for the first time in a long time.

*No magic values (or Strings)!  Create a constant for your min and max values and those should be private static final int with the your fields.

*In Eclipse setup the java save actions in preferences to auto format all lines of code when you save.

Of course none of those things will make your code run any better, but it sure will be easier to read.


text:
Q: Not able to boot Windows iso on my ubuntu in the Oracle VirtualBox-5.2 I have been stuck at this point for quite a lot time now and didn't get a fix.
I downloaded the Windows iso file from https://www.microsoft.com/en-in/software-download/windows10ISO , i have virtual box 5.2 installed.
So I went to New, created my machine with 2GB RAM allocation and 50GB hard disk allocation. (Tried dynamic and fixed both)
After this, I right clicked on my machine and added the optical drive as my Windows iso file and now, when I open my machine, i should boot. But it isn't.
It says FATAL: No bootable medium found! System halted
Please, provide me with a fix. It's been 2 days since i'm stuck at this point.
I tried everything i found, removed Virtual box and followed steps given in different tutorials but it isn't working out.
Please help, I'd really appreciate.

A: I don't know why you want to install it manually when you can download the virtual box file from M$ official site.
https://developer.microsoft.com/en-us/windows/downloads/virtual-machines
If you really want to create new VM from image ensure that VM settings are correct.

*

*Check if .VDI image is set in Settings > Storage > Sata > Hard Disk

*Check if ISO image is set in   Settings > Storage > Sata > Optical Drive

*Run the VM push F12 and select cd-rom.


text:
Q: Friendlist not complete Facebook Graph API I want to get the list of all my friends using facebook graph api. This is my code using python:
import facebook
import json

def pp(o):
    print json.dumps(o, indent=1)

g = facebook.GraphAPI('ACCESS_TOKEN')

print
print '---------------'
print 'My Friends'
print '---------------'
pp(g.get_connections('me', 'friends'))

But I am not getting complete list of my friends. It shows only 3 friends. What is the problem

A: Probably you're using Graph API v2.0, where the endpoint
GET /me/friends

only

returns the user's friends who are also using your app In v2.0, the friends
  API endpoint returns the list of a person's friends who are also using
  your app. In v1.0, the response included all of a person's friends.

See https://developers.facebook.com/docs/apps/upgrading#upgrading_v2_0_user_ids and https://developers.facebook.com/docs/graph-api/reference/v2.0/user/taggable_friends/ for a possible solution.


text:
Q: Configure Stunnel to provide https to web server I'm using standard httpd BusyBox as web sever ran on localhost:80. httpd doesn't support https.
To make connection between some client and my httpd server, I build and run stunnel with following configuration file:
setuid = www-data
setgid = www-data

debug = 7

output = /var/log/stunnel.log

cert = /etc/stunnel/cert/stunnel.pem
;key = /etc/stunnel/cert/serverkey.pem

sslVersion = all

pid = /tmp/stunnel.pid

socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1

;CAfile = /etc/stunnel/cert/servercert.pem
;verify = 0

;options = NO_SSLv2

[https]
accept = 443
connect = 80
TIMEOUTclose = 0

It ran successfully, but when I try to connect to sever using browser, I cant do that.
Log is following:
1970.01.01 03:04:58 LOG7[main]: Service [https] accepted (FD=19) from 192.168.0.5:48730
1970.01.01 03:04:58 LOG7[11]: Service [https] started
1970.01.01 03:04:58 LOG5[11]: Service [https] accepted connection from 192.168.0.5:48730
1970.01.01 03:04:58 LOG7[11]: SSL state (accept): before/accept initialization
1970.01.01 03:04:59 LOG7[11]: SNI: no virtual services defined
1970.01.01 03:04:59 LOG7[11]: SSL state (accept): SSLv3 read client hello A
1970.01.01 03:04:59 LOG7[main]: Service [https] accepted (FD=20) from 192.168.0.5:48734
1970.01.01 03:04:59 LOG7[11]: SSL state (accept): SSLv3 write server hello A
1970.01.01 03:04:59 LOG7[12]: Service [https] started
1970.01.01 03:04:59 LOG7[11]: SSL state (accept): SSLv3 write certificate A
1970.01.01 03:05:00 LOG5[12]: Service [https] accepted connection from 192.168.0.5:48734
1970.01.01 03:05:00 LOG7[12]: SSL state (accept): before/accept initialization
1970.01.01 03:05:00 LOG7[12]: SNI: no virtual services defined
1970.01.01 03:05:00 LOG7[12]: SSL state (accept): SSLv3 read client hello A
1970.01.01 03:05:01 LOG7[12]: SSL state (accept): SSLv3 write server hello A
1970.01.01 03:05:01 LOG7[12]: SSL state (accept): SSLv3 write certificate A
1970.01.01 03:05:33 LOG7[main]: Service [https] accepted (FD=21) from 192.168.0.5:48738
1970.01.01 03:05:33 LOG7[13]: Service [https] started
1970.01.01 03:05:33 LOG5[13]: Service [https] accepted connection from 192.168.0.5:48738
1970.01.01 03:05:33 LOG7[13]: SSL state (accept): before/accept initialization
1970.01.01 03:05:34 LOG7[13]: SNI: no virtual services defined
1970.01.01 03:05:34 LOG7[13]: SSL state (accept): SSLv3 read client hello A
1970.01.01 03:05:34 LOG7[13]: SSL state (accept): SSLv3 write server hello A
1970.01.01 03:05:35 LOG7[13]: SSL state (accept): SSLv3 write certificate A

What is the problem guys? And is it possible to use stunnel only on server side and not running it on client side?


text:
Q: Creating group based on time interval with stochastic base time in pandas I have a dataframe as:

index
time

0
2021-01-11 08:38:27

1
2021-01-11 08:40:32

2
2021-01-11 09:13:37

3
2021-01-11 11:26:52

4
2021-01-11 12:57:26

5
2021-01-11 13:19:33

6
2021-01-11 15:19:33

7
2021-01-12 10:25:33

8
2021-01-12 10:27:21

9
2021-01-12 11:02:13

I want to create another column based on one hour time difference from a stochastic base time. For example, when time at index 0 is the base time and I take one hour interval then index 0,1 and 2 is in the same group, say group_1. Next we can see that index 3 does not fall on group_1 since 08:38:27 + 1 hr = 09:38:27. So the next base time is at index 3 which is 2021-01-11 11:26:52. And this is group_2 and no other index fall on this group since the next index is more than one hour from this new base time. Then index 4 is the new base time and index 4 and 5 fall on the same group (group_3). And this process goes on upto the last row. The output should look like

index
time
group

0
2021-01-11 08:38:27
group_1

1
2021-01-11 08:40:32
group_1

2
2021-01-11 09:13:37
group_1

3
2021-01-11 11:26:52
group_2

4
2021-01-11 12:57:26
group_3

5
2021-01-11 13:19:33
group_3

6
2021-01-11 15:25:33
group_4

7
2021-01-12 10:25:33
group_5

8
2021-01-12 10:27:21
group_5

9
2021-01-12 11:02:13
group_5

Would really appreciate your time and answers. TIA.

A: You can use cumsum on the negate condition to identify the block:
df['group'] = 'group_' + df['time'].diff().gt('1H').cumsum().add(1).astype(str)

Output:
                      time    group
index
0      2021-01-11 08:38:27  group_1
1      2021-01-11 08:40:32  group_1
2      2021-01-11 09:13:37  group_1
3      2021-01-11 11:26:52  group_2
4      2021-01-11 12:57:26  group_3
5      2021-01-11 13:19:33  group_3
6      2021-01-11 15:19:33  group_4
7      2021-01-12 10:25:33  group_5
8      2021-01-12 10:27:21  group_5
9      2021-01-12 11:02:13  group_5

A: I think this question needs further analysis and requires another solution so hereby would like to review it.
According to the question, any 2 entries with time difference more than 1 hour should be classified in different groups.  So let's say we have the following 2 entries of time:
2021-01-11 08:38:27
2021-01-11 09:40:52

They differs by more than 1 hours and should be grouped under different group, right ?  Obvious, isn't it ?
Ok, let's add 2 more entries with time between them, like below:
2021-01-11 08:38:27      <=== original entry #1
2021-01-11 08:40:32           <=== new entry #1    diff less than 1 hour from previous entry
2021-01-11 09:13:37           <=== new entry #2    diff less than 1 hour from previous entry
2021-01-11 09:40:52      <=== original entry #2    diff less than 1 hour from previous entry

Now, if we run code based on difference between 2 consecutive entries being less than 1 hour, let's see what we get:
df['group'] = 'group_' + df['time'].diff().gt('1H').cumsum().add(1).astype(str)

print(df)

                  time    group
0  2021-01-11 08:38:27  group_1
1  2021-01-11 08:40:32  group_1
2  2021-01-11 09:13:37  group_1
3  2021-01-11 09:40:52  group_1

Oh, how come the last entry is group_1 rather than group_2 ?
This is because the 2 new entries added between the first and last entries somewhat 'bridge up' the first and last entry and make every 2 consecutive entries with difference less than 1 hour.  Hence, the result.
So, what should we do ?   I think we should group the entries base on an absolute base reference point, which is not the previous entry, but an entry that stays constant as long as we are processing entry within one hour from that base reference point.
I have come up with codes below:
base = df['time'].loc[0]
gc_list = []

for _, time in df['time'].items():
    if time - base > pd.Timedelta('1h'):
        base = time
    gc_list.append(time - base)

df['group_cumsum'] = pd.Series(gc_list)

df['group'] = 'group_' + df['group_cumsum'].eq('0h').cumsum().astype(str)

print(df)

                  time    group_cumsum    group
0  2021-01-11 08:38:27 0 days 00:00:00  group_1
1  2021-01-11 08:40:32 0 days 00:02:05  group_1
2  2021-01-11 09:13:37 0 days 00:35:10  group_1
3  2021-01-11 09:40:52 0 days 00:00:00  group_2

Now, you can see that the last entry is correctly grouped under a separate group now.
Here, I adapted @Quang Hoang's code (which is excellent and elegant) and fine-tuned to use the new mechanism of classifying groups.  I had been trying to code in a more idiomatic way without using loop. However, as the logics has to rely on a local variable base, I can't find a better way to do it.  Feel free to suggest if there is any better way.
I enclosed complete codes (with additional test cases) below in case anyone is interested:
Complete Codes
data = {'time': [
'2021-01-11 08:38:27',
'2021-01-11 08:40:32',
'2021-01-11 09:13:37',
'2021-01-11 09:40:52',
'2021-01-11 12:57:26',
'2021-01-11 13:19:33',
'2021-01-11 15:19:33',
'2021-01-12 10:25:33',
'2021-01-12 10:27:21',
'2021-01-12 11:02:13',
'2021-01-12 11:30:00'
]}

df = pd.DataFrame(data)

df['time'] = pd.to_datetime(df['time'])

base = df['time'].loc[0]
gc_list = []

for _, time in df['time'].items():
    if time - base > pd.Timedelta('1h'):
        base = time
    gc_list.append(time - base)

df['group_cumsum'] = pd.Series(gc_list)

df['group'] = 'group_' + df['group_cumsum'].eq('0h').cumsum().astype(str)

print(df)

                  time    group_cumsum    group
0  2021-01-11 08:38:27 0 days 00:00:00  group_1
1  2021-01-11 08:40:32 0 days 00:02:05  group_1
2  2021-01-11 09:13:37 0 days 00:35:10  group_1
3  2021-01-11 09:40:52 0 days 00:00:00  group_2
4  2021-01-11 12:57:26 0 days 00:00:00  group_3
5  2021-01-11 13:19:33 0 days 00:22:07  group_3
6  2021-01-11 15:19:33 0 days 00:00:00  group_4
7  2021-01-12 10:25:33 0 days 00:00:00  group_5
8  2021-01-12 10:27:21 0 days 00:01:48  group_5
9  2021-01-12 11:02:13 0 days 00:36:40  group_5
10 2021-01-12 11:30:00 0 days 00:00:00  group_6


text: Q: Difference between Sink and Emit for Flink Can someone explain what is the difference bwtween sink and emit for Flink? I am new and have been searching for the precise meaning of these terms, but it's always just applied and not concretely described.


text:
Q: How does Flask keep the request global threadsafe In flask every function has access to a request global. How do the designers of flask stop that global from being overwritten in the middle of one request when another one starts?

A: It's a threadlocal, not a true global. Since each thread can only be dealing with one request at a time, there's no danger of interference.
In fact there's a full description of exactly this in the Flask docs here.
(Still doesn't necessarily make it a good design, of course.)


text:
Q: [Help]PHP to PDF I have one invoice layout from my company that I transformed into a php file that have many css, my php file generate the invoice using mysql connections to fill some spaces, now I need to transform this html to pdf format. I tried to use tcpdf, but the images and css isnt good, since have many different tables. Does it have a simple tool to convert this generated html output from php, into pdf format ?
Thanks

A: You can use wkhtmltopdf.
example after you have download it,etc:
wkhtmltopdf http://link.com file_name.pdf


text:
Q: How to compare same property value regardless of order or duplication in multiple models What I need to know:

I only require a true or false answer:  Compare each of the Legs by their locations and return true if they are.

What I don't need to know:

Order of locations is irrelevant and duplication is irrelevant.

Data Structure:

CoachDriverItenaryModel (1-*) Leg
Leg (1-*) Exhibitions
(each exhibition has the Location field)

e.g. (simplified in pseudo code... note x,y,z represent locations)

Example 1: The answer should be true...(order is irrelevant)

ListOfLegs.Add(leg1: x,y,z)
ListOfLegs.Add(leg2: z,x,y)
ListOfLegs.Add(leg3: y,z,x)

var answer = ListOfLegs(AreAllLocationsSameOnAllLegs);

Example 2: The answer should be true...(duplication is irrelevant)

ListOfLegs.Add(leg1: x,y,z,y,y,y,y,y)
ListOfLegs.Add(leg2: z,x,y)

var answer = ListOfLegs(AreAllLocationsSameOnAllLegs);

Example 3: The answer should be false...(because no 'z' on leg1)

ListOfLegs.Add(leg1: x,y)
ListOfLegs.Add(leg2: z,x,y)

var answer = ListOfLegs(AreAllLocationsSameOnAllLegs);

Example 4: The answer should be false...(because no 'z' on leg 4)

 ListOfLegs.Add(leg1: x,y,z)
 ListOfLegs.Add(leg2: z,x,y)
 ListOfLegs.Add(leg3: z,x,y,y,y,y)
 ListOfLegs.Add(leg4: x,x,y,x,x)

var answer = ListOfLegs(AreAllLocationsSameOnAllLegs);

I'm looking for a nice Linq statement or something that doesn't require a lengthy algorithm?
below is a project that can be pasted straight in to .Net Fiddle (remember to set the compiler option to Rosyln) and the method to replace is below (it works but is there a better way?)...

public bool CompareAllLegLocations(){}

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var bradford = new Exhibition() { Location = "Bradford", Type = "Eygptian", Price = "£2.00" };
        var leeds = new Exhibition() { Location = "Leeds", Type = "Dinosaurs", Price = "£2.00" };
        var batley = new Exhibition() { Location = "Batley", Type = "Samurai", Price = "£2.00" };
        var york = new Exhibition() { Location = "York", Type = "Vikings", Price = "£2.00" };

        var mondaysItenary = new CoachDriverItenaryModel("Monday");
        mondaysItenary.AddLeg(new Leg { LegNumber = 1, Exhibitions = new List<Exhibition>() { york, leeds, bradford, leeds, york } });
        mondaysItenary.AddLeg(new Leg { LegNumber = 2, Exhibitions = new List<Exhibition>() { batley, leeds, bradford } });

        var tuesdaysItenary = new CoachDriverItenaryModel("Tuesday");
        tuesdaysItenary.AddLeg(new Leg { LegNumber = 1, Exhibitions = new List<Exhibition>() { leeds, batley, leeds } });
        tuesdaysItenary.AddLeg(new Leg { LegNumber = 2, Exhibitions = new List<Exhibition>() { batley, leeds, batley} });

        var wednesdaysItenary = new CoachDriverItenaryModel("Wednesday");
        wednesdaysItenary.AddLeg(new Leg { LegNumber = 1, Exhibitions = new List<Exhibition>() { leeds, bradford, batley } });
        wednesdaysItenary.AddLeg(new Leg { LegNumber = 2, Exhibitions = new List<Exhibition>() { bradford, batley, bradford } });
        wednesdaysItenary.AddLeg(new Leg { LegNumber = 3, Exhibitions = new List<Exhibition>() { bradford, batley, leeds } });

        var thursdaysItenary = new CoachDriverItenaryModel("Thursday");
        thursdaysItenary.AddLeg(new Leg { LegNumber = 1, Exhibitions = new List<Exhibition>() { leeds, bradford, batley, york, leeds } });
        thursdaysItenary.AddLeg(new Leg { LegNumber = 2, Exhibitions = new List<Exhibition>() { batley, bradford, leeds, york } });

        //mondaysItenary.DumpToConsole();
        mondaysItenary.CheckHasSameLocations(); //true:  because same locations on all legs (regardless of order)

        Console.WriteLine("-------------------------------");

        //tuesdaysItenary.DumpToConsole();
        tuesdaysItenary.CheckHasSameLocations(); //false: because "york" is not on both legs

        Console.WriteLine("-------------------------------");

        //wednesdaysItenary.DumpToConsole();
        wednesdaysItenary.CheckHasSameLocations(); //false: because first leg has "batley" on it and the other leg doesn't

        Console.WriteLine("-------------------------------");

        //thursdaysItenary.DumpToConsole();
        thursdaysItenary.CheckHasSameLocations(); //true: because duplication is allowed so it's okay to go to leeds twice

        Console.WriteLine("Finished");
    }
}

public class CoachDriverItenaryModel
{
    private Dictionary<int, Leg> LegNumberToLegIndex { get; set; }

    public IEnumerable<Leg> Legs => LegNumberToLegIndex?.Values;   //null propagation operator (c# 6+) use Rosyln 1.0.0 compiler

    public string Day { get; set; }

    public CoachDriverItenaryModel(string day) //constructor
    {
        LegNumberToLegIndex = new Dictionary<int, Leg>();
        Day = day;
    }

    public void AddLeg(Leg leg)
    {
        if (LegNumberToLegIndex == null)
        {
            LegNumberToLegIndex = new Dictionary<int, Leg>();
        }

        if (!LegNumberToLegIndex.ContainsKey(leg.LegNumber))
        {
            LegNumberToLegIndex.Add(leg.LegNumber, leg);
        }
    }

    public void DumpToConsole()
    {
        Console.WriteLine($"Day: {this.Day}");
        foreach (var displayLeg in this.Legs)
        {
            Console.WriteLine($"leg: {displayLeg.LegNumber}");
            foreach (var exhibition in displayLeg.Exhibitions)
            {
                Console.WriteLine($"Exhibition: {exhibition.Location}, Type: {exhibition.Type}, Price:{exhibition.Price}");
            }
        }
    }

    public bool CheckHasSameLocations()
    {
        if (LegNumberToLegIndex.Count <= 1) return true;

        for (var i=0; i < LegNumberToLegIndex.Count()-1; i++)
        {
            Leg leg = LegNumberToLegIndex[LegNumberToLegIndex.ElementAt(i).Key];
            Leg nextLeg = LegNumberToLegIndex[LegNumberToLegIndex.ElementAt(i + 1).Key];

            var legUnqOrd = from l in leg.Exhibitions.Distinct()
                                orderby l.Location
                                select new { l.Location };

            var nextLegUnqOrd = from l in nextLeg.Exhibitions.Distinct()
                            orderby l.Location
                            select new { l.Location };

            if (!legUnqOrd.SequenceEqual(nextLegUnqOrd))
            {
                Console.WriteLine("!Locations are different!");
                return false;
            }
        }
        Console.WriteLine("Locations Match");
        return true;
    }
}

public class Leg
{
    public int LegNumber { get; set; }
    public List<Exhibition> Exhibitions { get; set; }
}

public class Exhibition
{
    public string Location { get; set; }
    public string Type { get; set; }
    public string Price { get; set; }
}

A: You need to get the distinct locations from all the exhibitions and sort them for each of the legs. Once you have location list for each of the legs you need to pick one list and compare it with rest of all the lists and when the comparision fails that mean that the exhibitions are not equal and that says that the legs are not matching.
Method CompareAllLegLocations would look as following.
public bool CompareAllLegLocations()
    {
        if (_legNumberToLegIndex.Count > 0)
        {
            if (_legNumberToLegIndex.Count == 1)
                return false;

            var legs = _legNumberToLegIndex.Values;
            var firstLeg = _legNumberToLegIndex.FirstOrDefault().Value; // Taking first leg to determine the distinct list of locations.
            var firstLegLocations = firstLeg.Exhibitions.Select(ex => ex.Location).Distinct().OrderBy(x => x); // Determining distinct and ordered list of locations.
            foreach (var leg in legs)
            {
                var locations = leg.Exhibitions.Select(ex => ex.Location).Distinct().OrderBy(x => x); //Determining distinct and order list of locations for each of the leg.

                if (!locations.SequenceEqual(firstLegLocations)) //Comparing the list of locations of current leg to that of the first leg.
                    return true;
            }
            return false;
        }
        return false;
    }

I have assumed, from the question, that the comparison criteria is only location. If you have to compare exhibitions based on all the three properties of it then you need to create an EqualityComparer and use it to get the distinct exhibitions.
public class ExhibitionComparer : IEqualityComparer<Exhibition>
{
    public bool Equals(Exhibition x, Exhibition y)
    {
        return x.Location == y.Location && x.Type == y.Type && x.Price == y.Price;
    }

    public int GetHashCode(Exhibition obj)
    {
        return obj.GetHashCode();

    }
}

And use this comparer as following.
var firstLegExhibitions = firstLeg.Exhibitions.Distinct(comparer).OrderBy(ex => ex.Location).ToList();

This should resolve the issue. You can refine this code and logic as per your convenience.


text:
Q: Performance options I have a 2011 Mac mini and don't want to buy a new mini. It has 12gb ram and a 128gb PNY SSD which reads and writes in the 480mbps range. I'm looking for ways to speed it up, and I've done the basics like blowing out dust to reduce heat throttling etc. My ram pressure is really low since I only do light business apps such as Word, etc.
One thought I had was using its Thunderbolt 2 port (via thunderbolt 3/2 apple adapter and an NVMe enclosure to plug in an external NVMe SSD) and booting from that instead. I know that my Mac only supports Thunderbolt and therefore 20gbps, but that'll be better than SATA since its 4x as fast, right? My goal here is to make it feel as snappy as possible.


text:
Q: How to save ChainMap objects? I have a list of ChainMap objects in python that I'm using for analysis. I need to save them to disk somehow for later use. Is there any possibility to do this?

A: You can use the pickle lib. Here is a toy example that saves cm.pickle as a binary file and reads it again as the unpickled variable.
from collections import ChainMap
import pickle

nums = {"one": 1, "two": 2}
lets = {"a": "A", "b": "B"}

cm = ChainMap(nums, lets)

with open('cm.pickle', 'wb') as f:
    pickle.dump(cm, f)

with open('cm.pickle', 'rb') as f:
    unpickled = pickle.load(f)

print(unpickled)
ChainMap({'one': 1, 'two': 2}, {'a': 'A', 'b': 'B'})


text:
Q: Defining a Equality relationship when it already exists? I'm going crazy
(Equality Relation) There is one familiar relation between a set and itself that we consider every set $S$ mentioned in this text to possess: namely, the equality relation $=$ defined on a set $S$ by
$=$ is the subset $\{(x, x) \mid x \in S\}$ of $S \times S$.
Thus for any $x\in S$, we have $x = x$, but if $x$ and $y$ are different elements of $S$, then $(x,y) \not \in =$ and we write $x \ne y$.

The paragraph above is from the book of algebra by Fraleigh.
I'm really confused here. If you look at the phrase "but if $x$ and $y$ are different elements of $S$," it seems that there is already a equality relationship in the set $S$.
By the way, can we define $=$ again?
Is $=$ the symbol that I used to use here?

A: You could think of "$x,y$ different elements" as meaning $(x,y) \not \in =$.
We define the relation $=$ on $S$, and this gives two further (implicit) definitions:

*

*$x,y$ are the "same" element, if $(x,y) \in =$

*$x,y$ are "different" elements, if $(x,y) \not \in =$
from which we get the answer to your question.
As far as "can I define $=$ again", sure, but you want it to be defined in such a way that encapsulates the given definition. There can be multiple distinct but equivalent definitions of an entity in math.
And yes, $=$ is the desired symbol -- this is how we formally codify what it means for two things to be equal.


text:
Q: Splitting and storing a unsigned char Buffer into a struct Hello fellow stackoverflowers,
For university I have to create a simple TCP/IP stack for a microcontroller.
I have an unsigned char Buffer of the packets that includes the Headers + the data (if present).
I created a struct for the packets that contains a struct for the ethernet header, a struct for the IPv4 Header, a struct for the ARP header and a 2024 Byte buffer for the actual data.
I would like to assign byte 0 dow to 21 to the Ethernet struct.
And 22 down to 53 to the IPv4 Header.
My question now is how do you use memcpy to copy specific intervals from the buffer?
For example if I want to copy buf[21 down to 53] to newbuf[32].
EDIT:
So to clarify the question and what I am Actually trying to accomplish:
I send this packet from the PC via Ethernet Cable to a microcontroller.

On the microcontroller I want to create a struct that contains all the information that you can see in the picture.
My approach so far is:
   struct ethernetHeader{
        unsigned char receiverMac[6];
        unsigned char senderMac [6];
        unsigned char type [2];
    };

    //Not sure how to convert unsigned char to Bit or atleast integer
    struct IPv4Header{
        //4 Bit  Version
        //4 Bit IHL
        //8 Bit Type of Service
        //16 Bit Packet length
        //16 Bit Identification
        // 3 Bit Flags
        //13 Bit Fragment offset
        //8 Bit TTL
        //8 Bit protocol
        //16 Bit Header Checksum
        //32 Bit Source IP
        //32 Bit Destination IP
        //32 Bit Options -> NULL will be discarded

    };

    struct arpHeader{
        //to be defined
    };

    struct frame{
        struct ethernetHeader ethHdr;
        struct IPv4Header ip4Hdr;
        struct arpHeader arpHdr;
        unsigned char buffer[2024];

    };
while(1) {

        //postpones execution if no event is available
        event_mask = Event_pend(my_network_events,NON_EVENT_MASK,(EMAC_RX_EVENT | EMAC_TX_EVENT | EMAC_RX_NO_BUFFER),BIOS_WAIT_FOREVER);

        /*no receiver buffer was available
         * */
        if(event_mask & EMAC_RX_NO_BUFFER) {
            FreeEmacRxBuf();
            EMACRxDMAPollDemand(EMAC0_BASE);
        }

         //
         // Check for an RX Packet and read it.
         //
         if(event_mask & EMAC_RX_EVENT)
         {
             // Get the packet and set uip_len for uIP stack usage.
             //

             eth_rx_ptr =  PacketReceive((int32_t *)(&eth_len));
             if(eth_len > ETH_BUFSIZE)
                 eth_len = ETH_BUFSIZE;//truncate received packet length if necessary

             /* copy to private buffer and free */
             memcpy(eth_buf,eth_rx_ptr,eth_len);
             FreeEmacRxBuf();
             eth_rx_ptr = NULL;
             struct ethernetHeader header;

             memcpy(header.receiverMac, &eth_buf[0], 6);
             memcpy(header.senderMac, &eth_buf[6], 6);
             memcpy(header.type, &eth_buf[12],2);
    }
}

A:
My question now is how do you use memcopy to copy specific intervals from the buffer?
For example if I want to copy buf[21 downto 53] to newbuf[32]

So you will need to use pointer arithmetic in the source, (you have C++ an C tags you should remove one of those).
Something like (C++)
memcpy(newbuf, &buf[21], 32); // from buf[21] with the size of 32 bytes

Note that index 21 to 53 are actually 33 bytes.


text:
Q: Как реализовать сохранение фотографий в Picasso? В моем приложении рецептов есть функция сохранения рецепта для просмотра в оффлайн-режиме. Я реализовал сохранение текста в БД, но не знаю как быть с картинками. Пока что просто качаю Bitmap и сохраняю файл в память, запоминая его имя. Имя файла сохраняю в БД вместо ссылки.
Проблема очевидна - при получении Bitmap большой картинки выбрасывает OutOfMemoryError. Я прекрасно знаю про библиотеки и использую Picasso для показа картинок при подключенном интернете. Я также хорошо знаю, что она кэширует изображения. Также я знаю, что она качает их без OutOfMemory.
НО
Сохранение картинок реализовано в AsyncTask, а работать с Picasso в нем не получается.
Пока что думаю вместо загрузки картинок "руками" выкачивать Bitmap с помощью Picasso, но не понимаю как, нет логов, приложение просто вылетает.

A: Чтобы обратиться к Picasso выхожу в майн поток через publishProgress и в onProgressUpdate() передаю ссылку и имя файла. Также я использую resize. Тем самым картинки сохраняются не полностью, а под нужный размер. Работает отлично)


text:
Q: Drupal webform multi step save step by step I have created a multistep form webform drupal 8 and I want the recording done one by one, means when we click on next we go to the next step and save it from this step at the same time.

A: Webform module does not provide this feature. This will be possible by enabling Draft mode per webform. After enabling that build multi-page forms.
You can be found it under the form settings > Submissions tab > Draft settings.

A: This is a good deal easier now. It does it automatically when you use the "Page" element. Both the saving and a progress bar.
https://www.webwash.net/courses/using-webform-in-drupal-8/lessons/customize-webform-2/topic/create-multi-step-wizard/


text:
Q: Windows Program to Graphically Display Traceroute Is there a windows program that allows you to visualize a traceroute on a geographic map?

A: Visual Trace Route is my go to utility for this.

A: PingPlotter comes to mind.


text:
Q: For which points is there an analytic function through them If $(x_i,y_i)$ is an countable infinite set of points, with $x_i\neq x_j$ when $i \neq j$, does there always exist a sequence of real numbers $a_n$, such that $y_i=\sum_{n>1} a_nx_i^n$ for all $i>0$? Is it unique?
If {${x_i}$}$=\mathbb{N}$, i think its possible, what if {${x_i}$}$=\mathbb{Q}$?
What is required of $(x_i,y_i)$?
And same questions for $a_n\in \mathbb{Q}$?

A: More generally: for any open subset $\Omega$ of the complex numbers,  any sequence of distinct points $z_n$ in $\Omega$  that has no limit point in $\Omega$,  and any sequence $w_n$ of complex numbers, there is a function $f$ analytic in $\Omega$ with $f(z_n) = w_n$.  This is a standard result of complex analysis that follows from Mittag-Leffler's theorem (see e.g. Rudin, "Real and Complex Analysis", theorem 15.15).
On the other hand, for a sequence of distinct points $z_n$ that has a subsequence $z_{n_j}$ converging to $p \in \Omega$, the values $f(z_{n})$ must be far from arbitrary: analyticity of $f$ at $p$ requires $f(z_{n_j})$ to converge to $f(p)$, $(f(z_{n_j}) - f(p))/(z_{n_j} - p)$ to converge to $f'(p)$, etc., and the values of $f(z_{n_j})$ determine the function uniquely in the connected component of $\Omega$ containing $p$.

A: One of the ways this could fail for $\{x_i\} = \mathbb{Q}$ is if the power series ended up having a finite radius of convergence.
For example, take $y_i = (1+x_i^2)^{-1}$ for all $x_i$.  To start, if we're searching for a continuous function $f$ so that $f(x_i) = y_i$ then we are forced to take $f(x) = (1+x^2)^{-1}$ since continuous functions on Hausdorff spaces are uniquely determined by their values on dense subsets of their domains.  Now this function happens to be analytic on $|x|<1$, so it has a power series development there,
$$
f(x) = \sum_{k=0}^{\infty} a_k x^k.
$$
However, this power series diverges for $|x| > 1$, so that
$$
y_i \neq \sum_{k=0}^{\infty} a_k x_i^k
$$
for all $x_i$ satisfying $|x_i| > 1$.  Likewise, $f$ has a Laurent series for $|x| > 1$ which diverges for $|x| < 1$.  There is no power series for $f$ which converges on $\mathbb{R} \setminus \{\pm 1\}$.
Basically, given any $\{y_i\}$, we must at least be able to find a continuous function $f$ such that $y_i = f(x_i)$.  Steven's comment gives a clear counterexample.  In addition, we obviously want the function to be analytic if we're going to even think about representing it with a power series.  And, if we do, this power series must converge on all of $\mathbb{R}$, and hence on all of $\mathbb{C}$.  Thus the admissible $\{y_i\}$ you seek are precisely the values on $\mathbb{Q}$ of an entire function $f(x) = \sum_{k=0}^{\infty} a_k x^k$.


text:
Q: PHP File Not Copying across My issue with the below code is the if(if(empty($fields['Remuse']))) statement everything else works fine.  I only put it in an if statement to make the warning that it was empty go away now it does not copy when there is a file - Shows in cache and db fine why?
Issue:
  $candidateuploaddir = _MYSITEDIR . '/downloads/refocus_candidates/';
        $candiatefilename = $fields['RenamedResume'];
        $candidatefile = $candidateuploaddir . $candiatefilename;

        if(empty($fields['Remuse']))
        {
                echo 'null';
        }else{
        copy($fields['Resume'],$candiatefilename);
        }

Upload Function:
function uploadResume()
{
    if (!isset($_FILES['UploadResume'])) return false;
    $uploaddir = _CACHEDIR.'/resumes/';
    /* create the upload folder if it does not already exist */
    CMS::RecursiveMkdir($uploaddir);
    $extension = CMS::getFileExtension(basename($_FILES['UploadResume']['name']));
    /* keep producing random filenames until we get a unique one */
    while (empty($filename) || CMS::fileExists($uploaddir.$filename)) {
        $filename = CMS::randomString(10).'.'.$extension;
    }

    $uploadfile = $uploaddir . $filename;

    if (move_uploaded_file($_FILES['UploadResume']['tmp_name'], $uploadfile)){

        return $uploadfile;
        //$uploadfile;
    } else {
        return false;
    }
}

On Submit Line:
$fields['Resume'] = CMS::either(CMS_Plugin_plugin_jobs_apply::uploadResume(), CMS::getFormData('Resume', false)); //upload resume to temporary location

A: Is it if(if(empty($fields['Remuse']))) or if(empty($fields['Remuse']))?
Is it $fields['Remuse'] or $fields['Resume']?

if (empty($fields['Resume']))
{
    echo 'null';
}

else
{
    copy($fields['Resume'],$candiatefilename);
}

A: Try adding / between $uploaddir and $filename.


text:
Q: What is causing the abort trap in the output C file for my Brainfuck transpiler? I am working on a C to Brainfuck transpiler, based on the translation described in Brainfuck's Wikipedia page. Each program that I have tested works perfectly, until the end. In the beginning, I allocate an array of 30000 bytes, char* ptr = malloc(30000 * sizeof(char));, and in the end I free it via free(ptr);. My transpiler is below:
def make_tokens(chars):
    return [char for char in chars if char in {">", "<", "+", "-", ".", ",", "[", "]"}]

def translate_instruction(i):
    return {">": "++ptr;",
    "<": "--ptr;",
    "+": "++*ptr;",
    "-": "--*ptr;",
    ".": "putchar(*ptr);",
    ",": "*ptr = getchar();",
    "[": "while (*ptr) {",
    "]": "}"}[i] + "\n"

def to_c(instructions):
    with open("bfc.c", "w") as c_file:
        for header in ("stdio", "stdlib", "string"):
            c_file.write(f"#include <{header}.h>\n")
        c_file.write("\nint main() {\n\tchar* ptr = malloc(30000 * sizeof(char));\n")
        c_file.write("\tmemset(ptr, 0, 30000);\n")

        indentation = 1
        for i in make_tokens(instructions):
            c_file.write("\t" * indentation + translate_instruction(i))
            if i == "[": indentation += 1
            elif i == "]": indentation -= 1

        c_file.write("\tfree(ptr);\n}")

This Brainfuck program is Sierpinski's triangle, from here. I verified it with this online interpreter.
to_c("""++++++++[>+>++++<<-]>++>>+<[-[>>+<<-]+>>]>+[
    -<<<[
        ->[+[-]+>++>>>-<<]<[<]>>++++++[<<+++++>>-]+<<++.[-]<<
        ]>.>+[>>]>+
    ]""")

My program generates the following C code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char* ptr = malloc(30000 * sizeof(char));
    memset(ptr, 0, 30000);
    ++*ptr;
    ++*ptr;
    ++*ptr;
    ++*ptr;
    ++*ptr;
    ++*ptr;
    ++*ptr;
    ++*ptr;
    while (*ptr) {
        ++ptr;
        ++*ptr;
        ++ptr;
        ++*ptr;
        ++*ptr;
        ++*ptr;
        ++*ptr;
        --ptr;
        --ptr;
        --*ptr;
        }
    ++ptr;
    ++*ptr;
    ++*ptr;
    ++ptr;
    ++ptr;
    ++*ptr;
    --ptr;
    while (*ptr) {
        --*ptr;
        while (*ptr) {
            ++ptr;
            ++ptr;
            ++*ptr;
            --ptr;
            --ptr;
            --*ptr;
            }
        ++*ptr;
        ++ptr;
        ++ptr;
        }
    ++ptr;
    ++*ptr;
    while (*ptr) {
        --*ptr;
        --ptr;
        --ptr;
        --ptr;
        while (*ptr) {
            --*ptr;
            ++ptr;
            while (*ptr) {
                ++*ptr;
                while (*ptr) {
                    --*ptr;
                    }
                ++*ptr;
                ++ptr;
                ++*ptr;
                ++*ptr;
                ++ptr;
                ++ptr;
                ++ptr;
                --*ptr;
                --ptr;
                --ptr;
                }
            --ptr;
            while (*ptr) {
                --ptr;
                }
            ++ptr;
            ++ptr;
            ++*ptr;
            ++*ptr;
            ++*ptr;
            ++*ptr;
            ++*ptr;
            ++*ptr;
            while (*ptr) {
                --ptr;
                --ptr;
                ++*ptr;
                ++*ptr;
                ++*ptr;
                ++*ptr;
                ++*ptr;
                ++ptr;
                ++ptr;
                --*ptr;
                }
            ++*ptr;
            --ptr;
            --ptr;
            ++*ptr;
            ++*ptr;
            putchar(*ptr);
            while (*ptr) {
                --*ptr;
                }
            --ptr;
            --ptr;
            }
        ++ptr;
        putchar(*ptr);
        ++ptr;
        ++*ptr;
        while (*ptr) {
            ++ptr;
            ++ptr;
            }
        ++ptr;
        ++*ptr;
        }
    free(ptr);
}

The output of compiling and running that with clang was this:
                               *
                              * *
                             *   *
                            * * * *
                           *       *
                          * *     * *
                         *   *   *   *
                        * * * * * * * *
                       *               *
                      * *             * *
                     *   *           *   *
                    * * * *         * * * *
                   *       *       *       *
                  * *     * *     * *     * *
                 *   *   *   *   *   *   *   *
                * * * * * * * * * * * * * * * *
               *                               *
              * *                             * *
             *   *                           *   *
            * * * *                         * * * *
           *       *                       *       *
          * *     * *                     * *     * *
         *   *   *   *                   *   *   *   *
        * * * * * * * *                 * * * * * * * *
       *               *               *               *
      * *             * *             * *             * *
     *   *           *   *           *   *           *   *
    * * * *         * * * *         * * * *         * * * *
   *       *       *       *       *       *       *       *
  * *     * *     * *     * *     * *     * *     * *     * *
 *   *   *   *   *   *   *   *   *   *   *   *   *   *   *   *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
a.out(91318,0x11b627e00) malloc: *** error for object 0x7fb354808883: pointer being freed was not allocated
a.out(91318,0x11b627e00) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

As you can see, the program runs just fine, just until the end. The free is what causes the abort trap, which I do not understand because I allocated my array via the heap, not the stack. LLDB does not help me very much here. This is so confusing! Does anyone know what I am doing wrong?
Process 93919 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
    frame #0: 0x0000000100003f47 a.out`main at bfc.c:122:7
   119          ++ptr;
   120          ++*ptr;
   121          }
-> 122      free(ptr);
   123  }
Target 0: (a.out) stopped.
(lldb) n
a.out(93919,0x1000e7e00) malloc: *** error for object 0x100808883: pointer being freed was not allocated
a.out(93919,0x1000e7e00) malloc: *** set a breakpoint in malloc_error_break to debug
Process 93919 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
    frame #0: 0x00007fff20340462 libsystem_kernel.dylib`__pthread_kill + 10
libsystem_kernel.dylib`__pthread_kill:
->  0x7fff20340462 <+10>: jae    0x7fff2034046c            ; <+20>
    0x7fff20340464 <+12>: mov    rdi, rax
    0x7fff20340467 <+15>: jmp    0x7fff2033a6a1            ; cerror_nocancel
    0x7fff2034046c <+20>: ret
Target 0: (a.out) stopped.
(lldb) bt
* thread #1, queue = 'com.apple.main-thread', stop reason = signal SIGABRT
  * frame #0: 0x00007fff20340462 libsystem_kernel.dylib`__pthread_kill + 10
    frame #1: 0x00007fff2036e610 libsystem_pthread.dylib`pthread_kill + 263
    frame #2: 0x00007fff202c1720 libsystem_c.dylib`abort + 120
    frame #3: 0x00007fff201a2430 libsystem_malloc.dylib`malloc_vreport + 548
    frame #4: 0x00007fff201a54c8 libsystem_malloc.dylib`malloc_report + 151
    frame #5: 0x0000000100003f50 a.out`main at bfc.c:122:2
    frame #6: 0x00007fff20389621 libdyld.dylib`start + 1
(lldb)

A: Do this:
char* ptr = malloc(30000 * sizeof(char));
memset(ptr, 0, 30000);
char *orig = ptr;

// Code

free(orig);

Since you're incrementing and decrementing the pointer ptr you of course cannot trust it to point at the same place as it did upon initialization. If fact, that would be very unlikely.
And just for good habits:

*

*sizeof(char) is ALWAYS 1, so either use malloc(30000 * sizeof *ptr) (Always works no matter the type) or simply malloc(30000)

*Use calloc instead of malloc to save a call to memset
char *buffer = calloc(30000, sizeof *buffer);
char *ptr = buffer;

// Code

free(buffer);

But to be honest. While making sure that you always free resources is a good thing in general to avoid memory leaks, this is in general not necessary in the end of the main function. Unless you're programming embedded systems, operating systems or something very rare and special, you can trust the operating system to release all allocated memory for you upon program exit. For this application, you can skip the call to free if you want.


text:
Q: Adding a Combobox to a Datagridview So I'm developing a little program and I want to import datas from a SQL table to a datagridview, being one of the columns a ComboBox filled up from another table in the same database.
This is my current code:
Public Sub Load_black(Optional ByVal linhas As Integer = 20)
    i = 0
    black.Columns.Clear()
    black.Rows.Clear()
    black.Clear()
    ProdC.Open()
    Query = "SELECT * FROM [plano2] where familia like '%tpa%'ORDER BY ordem"
    myCMD = New SqlClient.SqlCommand(Query, ProdC)
    myDRR = myCMD.ExecuteReader
    If myDRR.HasRows = True Then
        black.Columns.Add("Order", GetType(String))
        black.Columns.Add("Number", GetType(String))
        black.Columns.Add("Name", GetType(String))
        black.Columns.Add("Cut Style", GetType(String))
        black.Columns.Add("Cicles/cm", GetType(String))
        black.Columns.Add("Leght", GetType(String))
        black.Columns.Add("Colors", GetType(String))
        black.Columns.Add("Date", GetType(String))
        While myDRR.Read And i < linhas
            black.Rows.Add(myDRR.Item("ordem").ToString, myDRR.Item("ref").ToString, myDRR.Item("design").ToString, myDRR.Item("tipodecorte").ToString, myDRR.Item("passagenscm").ToString, myDRR.Item("largura").ToString, myDRR.Item("numcores").ToString, myDRR.Item("dataentrada").ToString)
            str_pb_ref(i) = myDRR.Item("ref").ToString
            i = i + 1
        End While
    Else
        MessageBox.Show("Table is empety.")
    End If
    myDRR.Close()
    ProdC.Close()
    grd_black.DataSource = black
End Sub

What I want to do is to add a new row with that combobox.
I already tried many ways but either I have the value in the database table either I have the combobox with the other table values.
Thanks

A: The way I have solved this problem before was to set up the columns for the datagridview in the form designer, setting the specific combobox columns.
then populate the combobox column options using a SELECT DISTINCT query.
you can hide the column headers until data is in the datagridview if you want beforehand.
its a bit of an ass changing column types in code as each column type is a different column type object
You have to make a new instance of
 System.Windows.Forms.DataGridViewComboBoxColumn

then add that to the datagridview
(First post - Any good?)


text:
Q: jQuery Easing plugin - " 's' is already defined"; "jump" occurring on multiline text I'm trying to use the Easing plugin in order to get rid of the awful jumps and stuttering in my slideDown() effects:
    $('.message').each(function (index) {
        var t = $(this);
        t.hide();
        t.slideDown(3000, 'easeOutQuad');
    });

The effect is still just as choppy, and I noticed 6 instances of the following message in VS 2010:
's' is already defined

coming from the jquery.easing.1.3.js file.
I can't imagine that what the message is referring to would be lousing things up, but I can't figure out what else might be the problem.
Is anyone using the Easing plugin successfully with jQuery-1.4.3 ?  Is there something else that I'm overlooking, or a workaround that I'm unaware of?
Update
I've duplicated the "jump" here
It seems the problem crops up as soon as multiple lines per div are introduced.

A: If you look at the source, the warnings are coming from a few easing methods where s is redefined. For example, look at easeOutElastic:
easeOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},

Note that s is defined in the 2nd line and the redefined on the 4th and 5th lines. I can't determine a reason for the redefinition of s and removing the superfluous "var" keywords in the 4th and 5th lines doesn't affect the easing method as far as I can tell. The warnings appear harmless.
I have created a jsFiddle and don't see any great degree of choppiness in FF4b6, IE8, or Chrome9.
http://jsfiddle.net/TbwPT/
Maybe not as smooth as might be desirable, but my visual impression is that this is due to limitations WRT having to render or not render full pixels. As the easing slows, you'll see entire rows of pixels popping in. This is a limitation of how browsers position text as opposed to the easing function. e.g. You can't position a  at top=3.5px left=2.9px. I suspect that if you want a smoother animation, you'll have to take a look at animating text on a <canvas>.
UPDATE: Taking a look at your jsFiddle (http://jsfiddle.net/hPred/) with multiple lines per div, it looks like the animation is having problems determining the correct final height of the div when it is left unspecified. It properly animates from zero to the height of a single line and then pops to the full height of the div. If you specify the height, it properly animates from zero to the final div height. The following trick works to set the div height:
$('.message').each(function (index) {
    var t = $(this);
    t.height(t.height());  // Read the computed height and then set it explicitly
    t.hide();
    t.slideDown(3000, 'easeOutQuad');
});

This now animates properly for me... http://jsfiddle.net/hPred/3/


text:
Q: iOS detect when point is in rect I am utilizing a split view controller when the user can select an item out of the master view and drag it over to the detail view and place it. While the user is dragging, a UIView appears at the bottom of the detail view where they can drag the item if they change their mind mid-drag and want to remove it. I am having troubles detecting when the touch is in the UIView to remove. Here is what I have so far:
Code that is executed when the user selects the item in the master controller.
MasterViewController:
    // Create pointer to window
    UIWindow *window = [UIApplication sharedApplication].delegate.window;

    // Create draggable view
    self.draggableImageView = [[UIImageView alloc] initWithImage:imageView.image];

    // Adapt to orientation
    [self.draggableImageView rotateToOrientation:[[UIApplication sharedApplication] statusBarOrientation]];

    // Hide detail calloutview if there is one
    [self.detailViewController hideCalloutView:NO];

    // Add drag-view to window
    CGPoint location = [gesture locationInView:gesture.view.window];
    [self.draggableImageView setCenter:location];
    [window addSubview:[self draggableImageView]];

    // Animate the marker to jump up
    [UIView animateWithDuration:0.10
                          delay:0
                        options:UIViewAnimationOptionCurveEaseIn
                     animations:^{

                         // Move the marker up
                         [self.draggableImageView setCenter:CGPointMake(location.x + 75.0f, location.y)];

    } completion:^(BOOL finished) {

    }];

    // Show our remove marker view
    [self.detailViewController showRemoveMarkerView];

While the user is dragging, a method in the detail view controller is being called with the updated point and this is the code within that method:
- (void)pointForMarkerDidChange:(UIImageView *)imageView atPoint:(CGPoint)point
{
    NSLog(@"Point for Marker Did Change, point = %@", NSStringFromCGPoint(CGPointMake(point.x - 75.0f, point.y)));

    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    CGRect removeMarkerFrame = [window convertRect:self.removeMarkerView.frame fromView:self.view];

    if (CGRectContainsPoint(removeMarkerFrame, point)) {

        NSLog(@"YES");
    }
}

EDIT: I changed up the following code and it works now.
- (void)pointForMarkerDidChange:(UIImageView *)imageView atPoint:(CGPoint)point
{
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    CGRect removeMarkerFrame = [self.removeMarkerView convertRect:self.removeMarkerView.round.frame toView:self.view];
    CGPoint point2 = [window convertPoint:point toView:self.view];

    if (CGRectContainsPoint(removeMarkerFrame, point2)) {

        NSLog(@"YES");
    }
}


text:
Q: List cannot be converted to List Why this is not allowed?

error: incompatible types: List<TextBook> cannot be
  converted to List<Book>
process(textBooks);

import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(List<Book> books) {}

    public static void main(String[] args) {
        List<Book> books = new ArrayList<>();
        process(books);
        System.out.println("OK")

        List<TextBook> textBooks = new ArrayList<>();
        process(textBooks); # what is the problem in this statement?
        System.out.println("OK");
    }
}

A: You are trying to pass a List<TextBook> into a method whose signature expects a List<Book>.  This fails at compile time, because if the Java compiler were to allow it, then your process() method might try to use the contents of the list in the wrong way.  Instead, use this version of process():
public static void process(List<? extends Book> books) {}

Now you may pass in any instance of Book, or any subclass of Book.

A: This is not allowed because you started out with an arraylist of Textbook. However you passed it to process as a list of Book. The process function could add something which is not a textbook to the list. At this point your original list would not be an arraylist of Textbook.


text:
Q: How to display last command that failed when using bash set -e? I am using set -e to stop execution of a script on first error.
The problem is that this does not tell me what went wrong.
How can update a bash script so it will display me the last command that failed?

A: *

*make err.sh
set -e
trap 'echo "ERROR: $BASH_SOURCE:$LINENO $BASH_COMMAND" >&2' ERR

*include it (. err.sh) in all your scripts.

*replace any
... | while read X ; do ... ; done
with
while read X ; do ... ; done < <( ... )
in your scripts for the trap to give the correct line number/command in the error message

A: Instead of set -e, use an ERR trap; you can pass $BASH_LINENO in to get the specific line number on which the error occurred. I provide a script taking advantage of this in my answer at https://stackoverflow.com/a/185900/14122
To summarize:
error() {
   local sourcefile=$1
   local lineno=$2
   # ...logic for reporting an error at line $lineno
   #    of file $sourcefile goes here...
}
trap 'error "${BASH_SOURCE}" "${LINENO}"' ERR

A: Have you tried with --verbose?
bash --verbose script.sh

A: You can't use set -e by itself because processing will immediately stop after any error. Take a look at the Set Builtin section of the Bash Reference Manual for more information about the -x and -v options, which you can use for debugging.
Something like:
set -e
set -v

will exit on any error, while showing you each input line as it is read. It will not, however, show you just the line with the error. For that, you will need to do your own explicit error checking.
For example:
set +e
if false; then
    real_exit_status=$?
    echo 'Some useful error message.' >&2
    exit $real_exit_status
fi

A: set -ex will show (all) lines as they are executed and stop at the first command returning nonzero (not as part of if/while/until constructs).


text:
Q: How to get the data for the next two weeks? I've several straight-forward planners, like this:
| date       | person | person 2 | description |
 2013-03-01      peter      pam    painting
 2013-03-18      john       carl   cleaning
 2013-03-20      max        anne   washing

On a different sheet, I want to filter the 'events' for the next 2 weeks only. How can I achieve this? I tried several ways, but none of them are working.
With =ARRAYFORMULA(DAYS360(B2:B;NOW())) I can get a daynumber in a different column. 0 = today, 1 = yesterday, -1 tomorrow et cetera. In fact, I need to filter the days -1 to -14. Sometimes there are only 2 events, sometimes 5 in 2 weeks.
Edit: Some things I found

*

*First, I filter the correct daynumbers with    =filter(A2:A50;A2:A50>-14;A2:A50<0)

*Then, I do a vlookup =vlookup(G32,A1:E49;5;false)
(where G32 is the filtercommand, A2:A50 the daynumbers, A1:E49 all the data)

A: This is a good opportunity for the QUERY command and Query Language.
I'm assuming your data is in 4 columns, A:D, in "sheet 1".
=query('sheet 1'!A:D,"select * where datediff( A, now()) < 14 and datediff( A, now()) > 0")


text:
Q: Matplotlib-like image plotting in Vue 3 frontend I want to transfer the functionality of a currently python based desktop app into a Vue 3 based browser app.
The application loads an image and sends it to a backend where through computer vision certain elements are detected and the position of those elements is send back to the client.
In the client I now want to display the image and overlay the positions with a scatter plot, similiar to what I would do in python with
import matplotlib.pyplot as plt

plt.imshow(image)
plt.scatter(x_coordinates, y_coordinates)
plt.show()

It needs to be in the frontend because the user is supposed to tweak a few parameters to correct the positions all at the same time. This needs to be fast and responsive and I therefore don't want to do it in the backend and send the plot result as base64 or something like that.
I am considering using plotly or chart.js.
Are there any recommendations and experience if this could work? From the chart.js documentation I know that I can plot the coordinates and use an image as background, but is there a way to align the image coordinate system with the coordinate system of my plot in chart.js?
Are there other libraries that might be better suited?


text:
Q: Dynamic table going out of the form tag I have added a dynamic table on page load as follows
  protected void Page_Load(object sender, EventArgs e)
{
    Table tbl = new Table();
    tbl.ID = "table1";

    this.Controls.Add(tbl);

    for (int row = 0; row < 5; row++)
    {
        TableRow rw = new TableRow();
        TableCell cell = new TableCell();

        Label text = new Label();
        text.Text = "text";

        cell.Controls.Add(text);
        rw.Cells.Add(cell);

        tbl.Controls.Add(rw);
     }
}

The problem is, when I inspect the elements in the browser, the table appears to come out of the form tag as follows.

        <form name="aspnetForm" method="post" action="trial2.aspx" id="aspnetForm">
    </form>

            text

            text

            text

            text

            text

I want the table within the form tag, Please help!

A: Add your table before  tag
In ASP.Net better you add it with in form tag with below code
this.Form.Controls.Add(tbl);

instead of this.Controls.Add(tbl);

A: Try this:
Table tbl = new Table();
tbl.ID = "table1";

Form.Controls.Add(tbl);
....


text:
Q: RegionPlot3D not showing 2D shapes I am trying to draw a series of regions in Mathematica (one example below), but the planes I am trying to draw with RegionPlot3D don't show anything.
For example,
RegionPlot3D[((p2 < 247/561 &&
     1/147 (73 - 117 p2) <= p1 <= 1/12 (11 - 21 p2)) || (p2 == 247/
      561 && p1 == 82/561)) && p3 == 1/10 (-1 + 2 p1 + 11 p2),
{p1,0,1}, {p2,0,1}, {p3, 0, 1}]

doesn't yield/show anything in the plot, but if I change p3 == 1/10 (-1 + 2 p1 + 11 p2) to p3 >= 1/10 (-1 + 2 p1 + 11 p2), then I get a (crudely drawn) 3D region.
Is there another 3D plotting option that you would recommend, or a way to make RegionPlot3D show 2d planes, but still in a 3 dimensional plot?
(I'm using Version 11 on Linux Mint)


text:
Q: PySide QTreeview beginRemoveRows wrong index I am using QTreeView, connected to a proxy model QSortFilterProxyModel, that is connected to a model QAbstractItemModel.
I'm struggling with removing the current index's row. What happens instead is that it will always remove its sibling with the last row.
For example, if I want to remove B, it will remove C instead:
A
---- B
---- C
I think my input is right, so I don't know why it's removing the wrong index. Currently my code to remove a row looks like this:
index = tree_view.currentIndex() # Get the current index.

mapped_index = tree_view.proxy_model.mapToSource(tree_view.currentIndex()) # Get the proper index to work with.

tree_view.tree_model.beginRemoveRows(mapped_index.parent(), mapped_index.row(), mapped_index.row()) # Removes wrong index!

tree_view.tree_model.endRemoveRows()

Also trying to remove it this way yields the same result:
mapped_index = tree_view.proxy_model.mapToSource(tree_view.currentIndex())

tree_view.tree_model.rowsAboutToBeRemoved.emit(mapped_index.parent(), mapped_index.row(), mapped_index.row())

tree_view.tree_model.removeRow(mapped_index.row(), mapped_index.parent())

tree_view.tree_model.rowsRemoved.emit(mapped_index.parent(), mapped_index.row(), mapped_index.row())


text:
Q: java Get the list or name of all attributes in a XML element i have an xml element
   <base baseAtt1="aaa" baseAtt2="tt">
        <innerElement att1="one" att2="two" att3="bazinga"/>
   </base>

and i would like to get the list of attributes.
for both the base element and the inner element.
i dont know the name of the innerElement
 it can have many different names.
 NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
 Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

the goal is to get a kind of dictionary as output,
for example for the xml above the output will be a dictionary with those valuse.
baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

i am using jre 1.5

A: Here is plain DOM based solution (however there is nothing wrong to combine XPath with DOM in Java):
NodeList baseElmntLst_gold  = goldAnalysis.getElementsByTagName("base");
Element baseElmnt_gold = (Element) baseElmntLst_gold.item(0);

NamedNodeMap baseElmnt_gold_attr = baseElmnt_gold.getAttributes();
for (int i = 0; i < baseElmnt_gold_attr.getLength(); ++i)
{
    Node attr = baseElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

NodeList innerElmntLst_gold = baseElmnt_gold.getChildNodes();
Element innerElement_gold = null;
for (int i = 0; i < innerElmntLst_gold.getLength(); ++i)
{
    if (innerElmntLst_gold.item(i) instanceof Element)
    {
        innerElement_gold = (Element) innerElmntLst_gold.item(i);
        break; // just get first child
    }
}

NamedNodeMap innerElmnt_gold_attr = innerElement_gold.getAttributes();
for (int i = 0; i < innerElmnt_gold_attr.getLength(); ++i)
{
    Node attr = innerElmnt_gold_attr.item(i);
    System.out.println(attr.getNodeName() + " = \"" + attr.getNodeValue() + "\"");
}

Result:
baseAtt1 = "aaa"
baseAtt2 = "tt"
att1 = "one"
att2 = "two"
att3 = "bazinga"

A: You can use this XPath to retrieve all attributes of 1st element node:
base/element[1]/@*

To get all attributes of all nodes in your XML yo can use this expression:
//@*

A: If you use XPath you will have less code, but for a dom base solution I have a suggestion here:
public void printElementsAndAttributes() throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    org.w3c.dom.Document doc = db.parse(new File("test.xml"));
    NodeList base = doc.getElementsByTagName("base");
    Node basenode = base.item(0);
    System.out.println(basenode.getNodeName() + getAttributesAsString(basenode.getAttributes()));
    NodeList children = basenode.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node item = children.item(i);
        if (item.getNodeType() == Node.ELEMENT_NODE) {
            System.out.println(item.getNodeName() + getAttributesAsString(item.getAttributes()));

        }
    }

}

private String getAttributesAsString(NamedNodeMap attributes) {
    StringBuilder sb = new StringBuilder("\n");
    for (int j = 0; j < attributes.getLength(); j++) {
        sb.append("\t- ").append(attributes.item(j).getNodeName()).append(": ").append(attributes.item(j).getNodeValue()).append("\n");
    }
    return sb.toString();

}

A: Use this method..
 public static void listAllAttributes(Element element) {

             System.out.println("List attributes for node: " + element.getNodeName());

             // get a map containing the attributes of this node
                 NamedNodeMap attributes = element.getAttributes();

             // get the number of nodes in this map

             int numAttrs = attributes.getLength();

             for (int i = 0; i < numAttrs; i++) {
            Attr attr = (Attr) attributes.item(i);
            String attrName = attr.getNodeName();

 String attrValue = attr.getNodeValue();
  System.out.println("Found attribute: " + attrName + " with value: " + attrValue);

             }
 }

call this method by using following call in the main method
  NodeList entries = doc.getElementsByTagName("NameOfTheNode");
                int num = entries.getLength();
                 for (int i=0; i<num; i++) {
                                                  Element node = (Element) entries.item(i);
                                                  listAllAttributes(node);

                          }

A: NodeList bList = eElement.getElementsByTagName("base");
Node node1 = bList.item(0);

if (node1.getNodeType() == node1.ELEMENT_NODE) {
                     Element ele = (Element) node1;
                     System.out.print("Attribute : ");
                     System.out.println(ele.getAttributes());
                  }

Should work.
Very nice explanation is given at https://www.tutorialspoint.com/java_xml/java_xml_quick_guide.htm You can refer that for more clarity.


text:
Q: Creating Large DataFrame from smaller DataFrames I am having an issue with the structure of data as I get it off the PGA website. I have trouble putting the data into a dataframe and merging the data so that I can use the dataframe for analysis later. The dimensions of the scraped data are never right. I get a separate error each time I run the code that I cant seem to reconcile.
I have tried merging and concatenating dataframes but nothing seems to work. ANy help is appreciated
I would really like for my dataframe to contain the individual statistics from the separate sites but on the same row as the other data formatted by the year and PLAYER NAME.
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
import datetime
import socket
import urllib.error
import pandas as pd
import urllib
import sqlalchemy
import numpy as np
import functools

base = 'http://www.pgatour.com/'
inn = 'stats/stat'
end = '.html'
years = ['2017','2016']

alpha = []
#all pages with links to tables
urls =     ['http://www.pgatour.com/stats.html','http://www.pgatour.com/stats/categories.ROTT_INQ.html','http://www.pgatour.com/stats/categories.RAPP_INQ.html','http://www.pgatour.com/stats/categories.RARG_INQ.html','http://www.pgatour.com/stats/categories.RPUT_INQ.html','http://www.pgatour.com/stats/categories.RSCR_INQ.html','http://www.pgatour.com/stats/categories.RSTR_INQ.html','http://www.pgatour.com/stats/categories.RMNY_INQ.html','http://www.pgatour.com/stats/categories.RPTS_INQ.html']
for i in urls:
    data = urlopen(i)
    soup = BeautifulSoup(data, "html.parser")
    for link in soup.find_all('a'):
        if link.has_attr('href'):
            alpha.append(base + link['href'][17:]) #may need adjusting
#data links
beta = []
for i in alpha:
    if inn in i:
        beta.append(i)

gamma = []
for i in beta:
    if i not in gamma:
        gamma.append(i)

jan = []
for i in gamma:
    try:
        data = urlopen(i)
        soup = BeautifulSoup(data, "html.parser")
        for table in soup.find_all('section',{'class':'module-statistics-off-the-tee-details'}):
            for j in table.find_all('h3'):
                y=j.get_text().replace(" ","").replace("-","").replace(":","").replace(">","").replace("<","").replace(">","").replace(")","").replace("(","").replace("=","").replace("+","")
                jan.append([i,str(y+'.csv')])
                print([i,str(y+'.csv')])
    except Exception as e:
            print(e)
            pass

#my problem starts here
#using urls list so that I can find error faster
urls = [['http://www.pgatour.com/stats/stat.02356.html','d']
    ,['http://www.pgatour.com/stats/stat.02568.html','f']
    ,['http://www.pgatour.com/stats/stat.111.html','r']]
list = []
master = pd.DataFrame()
#jan = [['http://www.pgatour.com/stats/stat.02356.html', 'Last15EventsScoring.csv']]
#make a list with url and title name and cleaned csv name
#write to csv
row_sp = []
rows_sp =[]
title1 = []
title = []
for i in urls:
    try:
        for y in years:
            data = urlopen(i[0][:-4] +y+ end)
            soup = BeautifulSoup(data, "html.parser")
            data1 = urlopen(i[0])
            soup1 = BeautifulSoup(data1, "html.parser")
            for table in soup1.find_all('table',{'id':'statsTable'}):
                title.append('year')
                for k in table.find_all('tr'):
                    for n in k.find_all('th'):
                        title1.append(n.get_text())
                        for l in title1:
                            if l not in title:
                                title.append(l)
                rows_sp.append(title)
            for table in soup.find_all('table',{'id':'statsTable'}):
                for h in table.find_all('tr'):
                    row_sp = [y]
                    for j in h.find_all('td'):
                        row_sp.append(j.get_text().replace(" ","").replace("\n","").replace("\xa0"," "))
                    rows_sp.append(row_sp)
            df=pd.DataFrame(rows_sp)
            df.columns = title
            df.drop(df.index[1],inplace = True)
            print(df)
            list.append(df)
    except Exception as e:
        print(e)
        pass
df_merge = functools.reduce(lambda  left,right: pd.merge(left,right,on=['year','PLAYER NAME'], how='outer'), list)


text:
Q: Android Rss onPostExecute how can i update my view in the fragments?
package at.example.gacapp;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Thomas on 18/08/13.
 */
public class News extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.overview, container, false);
        GetRSSDataTask rss = new GetRSSDataTask();
        rss.execute("http://www.grazer-ac.at/index.php?format=feed&type=rss");

        return root;

    }

    private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
        @Override
        protected List<RssItem> doInBackground(String... urls) {

            // Debug the task thread name
            Log.d("ITCRssReader", Thread.currentThread().getName());

            try {
                // Create RSS reader
                RssReader rssReader = new RssReader(urls[0]);

                // Parse RSS, get items
                return rssReader.getItems();

            } catch (Exception e) {
                Log.e("ITCRssReader", e.getMessage());
            }

            return null;
        }
        @Override
        protected void onPostExecute(List<RssItem> result) {

            TextView itcItems = (TextView) getView().findViewById(R.id.tom);
            itcItems.setText("Hans");

        }
    }
}

how can i update my view in the fragments?
my Problem is the onPostExecute Function, i want the items in my view , but i dont know how.
And maybe a Spinner! This where perfekt!
Thanks,
Thomas

A: You have to use a ListView in your layout and in onPostExecute() set an adapter for it
ListView list = (ListView) getView().findViewById(R.id.list);
list.setAdapter(new ArrayAdapter<RssItem>(getActivity(), android.R.layout.simple_list_item_1, result));


text:
Q: Pandas Pivot over a List in DataFrame I need to pivot a pandas dataframe given a "list of components". The idea is to create 1 row per component (item of the list).
The dataframe columns looks like this
 Receipt      Items
 Receipt A   [id1, id2, id3, id4]
 Receipt B   [id4, id5]
 Receipt C   [id6, id7,id8]

What I need to obtain is a row per value (pivoting by Items):
 Receipt      Items
 Receipt A    id1
 Receipt A    id2
 Receipt A    id3
 Receipt A    id4
 Receipt B    id4
 Receipt B    id5
 Receipt C    id6
 Receipt C    id7
 Receipt C    id8

I'm new to Python and Pandas, and can´t imagine how to handle this situation, I need this to accomplish that format in order to apply more calculations in a data viz tool.
Thanks in advance.
Edited to complete scenario
 Receipt      Items                 Quantity
 Receipt A   [id1, id2, id3, id4]   [1, 3, 2, 1]
 Receipt B   [id4, id5]             [1, 2]
 Receipt C   [id6, id7,id8]         [1, 3, 2]

A: Try pandas explode
import pandas as pd

#your data here
A = ['id1', 'id2', 'id3', 'id4']
B = ['id4', 'id5']
C = ['id6', 'id7', 'id8']

#create Dataframe with your data
df1 = pd.DataFrame({'Receipt':['Receipt A','Receipt B','Receipt C'], 'Items':[A, B, C]})

#printing your dataframe
print(df1)

#transforming through explode and print again
df2 = df1.explode('Items')
print(df2)

output:
     Receipt Items
0  Receipt A   id1
0  Receipt A   id2
0  Receipt A   id3
0  Receipt A   id4
1  Receipt B   id4
1  Receipt B   id5
2  Receipt C   id6
2  Receipt C   id7
2  Receipt C   id8