text:
Q: Modifying object at service layer in angular2: Subscription is not assignable to the type observable I am new to Angular2 framework so excuse if this is a basic question.
I am handling an object at service layer returned via a http wrapper. This object should be passed to the component, but first the data should be manipulated and only necessary data extracted and forwarded.
When I attempt to do this i receive an error "Subscription is not assignable to the type observable". Here is the code
return this.httpGet<UserInfo[]>(url, {headers}).switchMap(data => data)
.subscribe(
    data => {
        console.log("new values are going to be" + JSON.stringify( data[0].address.addressLine1));
        this.userInfo[0].name = "test name";
        this.UserInfo[0].address.city = data[0].address.city;
        this.UserInfo[0].address.state = data[0].address.state;
    },
);

Now, what makes sense in my mind is to first convert the data inside the subscription as it is streamed back, and then return the object explicitly  but this also fails to give the desired output, even if the type is an observable. Coming from a java oop background I cannot see what is the issue here an am thoroughly confused. Any insight is appreciated.
edit : for completion here is where the service call is made -
   this.inputFormControl.valueChanges
.debounceTime(4000)
.switchMap(query => this.userService.search(query))
.subscribe(
    data => {
        this.data = data;
    },
);

A: In your current code, you have already subscribed to the observable. So that returns a Subscription instead of an observable . Then in your calling function, you are trying to assign this to a observable.
Try following pattern
   someFunction() {
    return this.httpGet<UserInfo[]>(url, {headers}).switchMap(data => data)
    }

    callingFuction(){
    someFunction().subscribe(
        data => {
            console.log("new values are going to be" + JSON.stringify( data[0].address.addressLine1));
            this.userInfo[0].name = "test name";
            this.UserInfo[0].address.city = data[0].address.city;
            this.UserInfo[0].address.state = data[0].address.state;
        },
    );
    }

A: As mentioned in other answer, you are returning a subscription instead of an Observable. Also I don't see why the use of switchMap would be necessary in your service (I assume you have your http request in a service), as you are using it in your component. So I would do map in service, modify the data there and return it to your component.
To point out one more thing, that in your current code you are not returning anything from the http-request, so you need to add a return statement.
return this.httpGet<UserInfo[]>(url, {headers})
  .map(data => {
     this.UserInfo[0].name = "test name";
     this.UserInfo[0].address.city = data[0].address.city;
     this.UserInfo[0].address.state = data[0].address.state;
     return this.UserInfo; // add return!
  });

Your component code would stay as it is.


text:
Q: Incluindo colunas em um dataframe no R utilizando uma regra Esse é meu dataframe:
df<-as.data.frame(matrix(rexp(200, rate=.1), ncol=10))
colnames(df)<-c("one","two","three","four","five","six","seven","eight","nine","ten")

Esse é o indice que usarei como exemplo:
index<-c(1,2,3,4,5,6,7,8,9,10)

Minha ideia é criar colunas e preenchendo os valores -2, -1, 0, 1 ou 2 nessas colunas criadas de acordo com uma regra.
Seria assim: Vou criar uma coluna AO LADO da coluna "One" e vou chama-la de "One_new":
Na hora de preencher essa coluna com valores seguirei a seguinte regra:
Se o valor na coluna "One" for menor que 1 (index[1]) e maior que -1(-index[1]) recebe o valor 0.
Se o valor na coluna "One" for maior que 1 (index[1]) e menor que 2*(index[1]) recebe o valor 1.
Se o valor na coluna "One" for maior que 2*(index[1]) recebe o valor 2.
Se o valor na coluna "One" for menor que -1*(index[1]) e maior que -2*(index[1]) recebe o valor -1.
Se o valor na coluna "One" for menor que -2*(index[1]) recebe o valor -2.
Vou percorrer essa regra para todas as colunas. O que muda é o valor referencia que para a segunda coluna sera index[2], para a terceira index[3],...,até a para coluna 10 index[10]
Preciso que essas colunas criadas fiquem ao lado das colunas. Ou seja, a coluna One_new deve ficar ao lado da coluna One, a coluna Two_new ao lado da coluna Two e por ai vai.
Consigo fazer isso com o pacote dplyr?
Alguma ajuda?

A: Eu faria da seguinte forma, usando purrr e dplyr.
res <- map2_dfc(df, index, function(x, index) {
  case_when(
    x < -2*index ~ -2,
    x < -1*index ~ -1,
    x <  1*index  ~  0,
    x <  2*index  ~  1,
    TRUE         ~  2
    )
}) %>%
  set_names(paste0(names(.), "_new")) %>%
  bind_cols(df)

A função map2 do purrr é usada para aplicar a função para cada coluna do data.frame e index.
Note que o resultado final não coloca as colunas lado a lado. Isso poderia ser feito usando posteriormente a função select.
Para selecionar na ordem que você quer, é possível fazer assim:
res %>%
  select(flatten_chr(map(colnames(df), ~c(.x , paste0(.x , "_new")))))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extent of uniqueness of QR decomposition I know that if we require the diagonal entries of
$R$ to be positive, then the decomposition is unique, but how to prove the following theorem?
If $A=Q_1R_1=Q_2R_2$ are two distinct QR decompositions of a full rank, square matrix $A$ then
$$Q_2=Q_1D$$
$$R_2=DR_1$$
For some square diagonal $D$ with entries $\pm1$.

A: Given any QR factorization, you can force the diagonal elements of $ R $ to positive by multiplying from the right by a diagonal matrix of that form...  I think you can probably take it from there.
[edit] Hmmm, maybe in this situation it is better to say that any QR factorization can be changed to make the diagonal elements of $ R $ positive by inserting a diagonal matrix with $ \pm 1 $ on the diagonal as follows:  $ Q R = Q D \tilde R $.


text:
Q: Android Studio | Google Maps Api v2 | How to animate Marker? I am currently trying to animate an Marker.
I am trying to change it's Icon so that it looks like its a walking figure.
This is the thread which should deal with it:
package com.example.?;

import android.util.Log;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;

public class MarkerAnimationThread extends Thread {

    Marker currentLocationMarker;
    GameMap map;
    int counter=0;
    MarkerAnimationThread thread = this;
    public MarkerAnimationThread(Marker currentLocationMarker, GameMap map) {
        this.currentLocationMarker = currentLocationMarker;
        this.map = map;
    }

    public final int getCounter() {
        return counter;
    }
    public void setCounter(int counter) {
        this.counter=counter;
    }
    public Thread getThread() {
        return thread;
    }
    @Override
    public void run() {
        synchronized (this) {
            while (true) {
                map.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        switch (getCounter()) {
                            case 0: currentLocationMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.figure_1)); setCounter(getCounter()+1); break;
                            case 1: currentLocationMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.figure_2)); setCounter(getCounter()+1); break;
                            case 2: currentLocationMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.figure_3)); setCounter(getCounter()+1); break;
                            case 3: currentLocationMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.figure_4)); setCounter(0); break;
                            default: currentLocationMarker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.figure_1)); break;
                        }
                        try {
                            getThread().wait(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }
}

However, this is causing following error:

java.lang.IllegalMonitorStateException: object not locked by thread before wait()

Any suggestions what I am doing wrong?
Thanks in Advance!


text:
Q: Using regex (re.search) in a python list I have the following code
import re

pattern = ['A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AUA', 'A-minor Type I AUA', 'A-minor Type II AGC', 'A-minor Type II AGC']

n = len(pattern)
print pattern
pattern_str = ', '.join(pattern)
print pattern_str
for x in range(0, n):
    if re.search(r'\bType I\b', pattern_str):
        print "Hello Type I"
    elif re.search(r'\bType II\b', pattern_str):
        print "Hello Type II"
    else:
        print "An error has occured"

The desired output should be:
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type II
Hello Type II

But I'm not getting the desired output. My current output is:
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I

Can someone point out the problem? I suspect it has to be something to do with the list to str conversion. I have managed to solve the problem using the following code:
for x in pattern:
    if re.search(r'\bType I\b', x):
        print "Hello Type I"
    elif re.search(r'\bType II\b', x):
        print "Hello Type II"
    else:
        print "An error has occured"

But I would like to know why my first code didn't work and how can I make it work. Any help is appreciated

A: You're joining the whole list into a single string, then testing that a whole bunch of times.  Instead, what you want is to test each string in the list like
for pattern_str in pattern:
    if re.search(r'\bType I\b', pattern_str):
        print "Hello Type I"
    elif re.search(r'\bType II\b', pattern_str):
        print "Hello Type II"
    else:
        print "An error has occured"

so you are searching each pattern, one at a time

A: What you want: search through each string in your list.
What your code does
re.search(r'\bType I\b', pattern_str)

It searches through pattern_str in every iteration of the loop. What is pattern_str:
pattern_str = ', '.join(pattern)

Thus, in every iteration, it searches through the same string, which is the concatanation of the whole list, which always matches Type I in A-minor Type I AGC.
Changing in to search through each x in pattern does the trick

A: Your pattern is the same for each iteration. You need to loop through your patterns in your for-loop.
Use for p in pattern
This will mean p is 'A-minor Type I AGC' on the first iteration, 'A-minor Type I AGC' on the second iteration, etc.
import re

pattern = ['A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AGC', 'A-minor Type I AUA', 'A-minor Type I AUA', 'A-minor Type II AGC', 'A-minor Type II AGC']

for p in pattern:
    if re.search(r'\bType I\b', p):
        print "Hello Type I"
    elif re.search(r'\bType II\b', p):
        print "Hello Type II"
    else:
        print "An error has occured"

Output:
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type I
Hello Type II
Hello Type II


text:
Q: SWIFT how to play sound when screen is touched How do i play sound whenever screen is taped? this is a code I have now, where I check if screen has been touched and than it does some things...
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    if TapsValid == true {
        Score++

        if BallRight == true {

            BallChange = false

        } else {

            BallChange = true

        }

    }
}

A: import AVFoundation

/// You **must** keep reference to this...
private var audioPlayer: AVAudioPlayer!

/**
    Tap
*/
public func tapSound() -> Void
{
    let bundle: NSBundle = NSBundle(forClass: SoundMachine.self)
    if let file_url: NSURL = bundle.URLForResource("tap_sounf", withExtension:"caf")
    {
        self.playSoundFromURL(file_url)
    }
}

/**
    Reproduce un archivo de sonido que se encuentra
    en el Bundle de nuestra app

    - parameter resource_url: La URL al archivo
*/
private func playSoundFromURL(resource_url: NSURL) -> Void
{
    self.audioPlayer = try! AVAudioPlayer(contentsOfURL:resource_url)
    self.audioPlayer.prepareToPlay()
    self.audioPlayer.play()
}


text:
Q: Application crashing when returning 1 row in tableview I have a tableview that is populated with an array called json. If the length of json is 0, I would like to return 1 row in my tableview.
 -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  TableViewCell *cell = [self->tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
  NSDictionary *info = [json objectAtIndex:indexPath.row];
  //content is the name of label in the custom cell
  if ([json count]>0) {
    cell.content.text = [info objectForKey:@"message_text"];
  }
  else
    cell.content.text = @"There are currently no messages. Please pull down to refresh";

  return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
if([json count]>0)
    return [json count];
else
    return 1;

}

The above code causes my application to crash and I am unsure why. Why does this not work and how can I resolve the issue.
I get the following error:
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArray0 objectAtIndex:]: index 0 beyond bounds for empty NSArray'

A: Change this code:
NSDictionary *info = [json objectAtIndex:indexPath.row];
//content is the name of label in the custom cell
if ([json count]>0) {
  cell.content.text = [info objectForKey:@"message_text"];
}
else
   cell.content.text = @"There are currently no messages. Please pull down to refresh";

To:
//content is the name of label in the custom cell
if ([json count]>0) {
  NSDictionary *info = [json objectAtIndex:indexPath.row];
  cell.content.text = [info objectForKey:@"message_text"];
}
else
   cell.content.text = @"There are currently no messages. Please pull down to refresh";

Hope this help!


text:
Q: Why does my UPDATE trigger "Syntax error in string in query expression" error? I can execute an Access SQL INSERT statement without error, but when I attempt an UPDATE with the code below, it throws the error:

"Syntax error in string in query expression".

Why does that happen and how can I fix it?
Here is my code..
    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
    If txtName.Text = Nothing Or dtpDateBirth.Text = Nothing Or txtPhoneNumber.Text = Nothing Or txtEmail.Text = Nothing Or txtID.Text = Nothing Or mtbNPWP.Text = Nothing Or rtbAddress.Text = Nothing Or txtVillage.Text = Nothing Or txtSubDistrict.Text = Nothing Or txtCity.Text = Nothing Or txtPostalCode.Text = Nothing Or txtEmergencyName.Text = Nothing Or txtEmergencyNumber.Text = Nothing Or txtEmergencyEmail.Text = Nothing Then
        MsgBox("No data has been update", MsgBoxStyle.Information, "No data edit")
        Exit Sub
    Else
        Call koneksi()
        cmd = New OleDb.OleDbCommand("update t_customer set name='" & txtName.Text & "', date_birth='" & dtpDateBirth.Text & "', phone_number='" & txtPhoneNumber.Text & "', email='" & txtEmail.Text & "', id='" & txtID.Text & "', npwp='" & mtbNPWP.Text & "', address='" & rtbAddress.Text & "', village='" & txtVillage.Text & "', sub_district='" & txtSubDistrict.Text & "', city='" & txtCity.Text & "', postal_code='" & txtPostalCode.Text & "', gender='" & gen & "', emergency_name='" & txtEmergencyName.Text & "', phone_emergency='" & txtPhoneNumber.Text & "', email_emergency='" & txtEmergencyEmail.Text & "' where [codeCust]='" & txtIDCust.Text, conn)
        cmd.ExecuteNonQuery()
        MsgBox("Update data success!", MsgBoxStyle.Information, "Update")
    End If
    Call disabled()
    Call showData()
End Sub

A: As HansUp has suggested with the link you should be using parameters. Also you are not disposing the command. Also AFAIK (I thought) you needed the open the connection before you can ExecuteNonQuery. As for the Data Mismatch youre experiencing, I think it's because you have a ' in the where clause that shouldnt be there, assuming that the ID is an INT.
    Using OledbConn As New OleDbConnection("Conn String")

        OledbConn.Open()
        Using t_customerCMD As New OleDbCommand("UPDATE t_customer SET [Col1]=@Col1,[Col2]=@Col2 WHERE [codeCust]=@codeCust", OledbConn)
            With t_customerCMD
                .Parameters.Add("@Col1", SqlDbType.VarChar).Value = TextBox1.Text
                .Parameters.Add("@Col2", SqlDbType.VarChar).Value = TextBox2.Text
                .Parameters.Add("@codeCust", SqlDbType.Int).Value = CInt(txtIDCust.Text) 'Assumes ID is integer
                .ExecuteNonQuery()
            End With
        End Using
        OledbConn.Close()

    End Using
End Sub

A: Thank you for everyone who helped me. I thank you very much. This problem has been resolved.
this is my completion code, which I can finally do to update the database.
   Sub updateData()
    Call gender()
    If String.IsNullOrEmpty(txtName.Text) OrElse String.IsNullOrEmpty(dtpDateBirth.Text) OrElse String.IsNullOrEmpty(txtPhoneNumber.Text) OrElse String.IsNullOrEmpty(txtEmail.Text) OrElse String.IsNullOrEmpty(txtID.Text) OrElse String.IsNullOrEmpty(mtbNPWP.Text) OrElse String.IsNullOrEmpty(rtbAddress.Text) OrElse String.IsNullOrEmpty(txtVillage.Text) OrElse String.IsNullOrEmpty(txtSubDistrict.Text) OrElse String.IsNullOrEmpty(txtCity.Text) OrElse String.IsNullOrEmpty(txtPostalCode.Text) OrElse String.IsNullOrEmpty(txtEmergencyName.Text) OrElse String.IsNullOrEmpty(txtEmergencyNumber.Text) OrElse String.IsNullOrEmpty(txtEmergencyEmail.Text) Then
        MsgBox("No data has been update", MsgBoxStyle.Information, "No data edit")
        Exit Sub
    Else
        Try
            Call koneksi()
            Using cmd = New OleDb.OleDbCommand("update t_customer set name='" & txtName.Text & "', date_birth='" & dtpDateBirth.Text & "', phone_number='" & txtPhoneNumber.Text & "', email='" & txtEmail.Text & "', id='" & txtID.Text & "', npwp='" & mtbNPWP.Text & "', address='" & rtbAddress.Text & "', village='" & txtVillage.Text & "', sub_district='" & txtSubDistrict.Text & "', city='" & txtCity.Text & "', postal_code='" & txtPostalCode.Text & "', gender='" & gen & "', emergency_name='" & txtEmergencyName.Text & "', phone_emergency='" & txtPhoneNumber.Text & "', email_emergency='" & txtEmergencyEmail.Text & "' where [codeCust]=@codeCust", conn)
                cmd.Parameters.Add("codeCust", CType(txtIDCust.Text, String))
                cmd.ExecuteNonQuery()
                conn.Close()
                MsgBox("Update data success!", MsgBoxStyle.Information, "Update")
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End If
End Sub

Because I use the radio button for gender options, I added this so that gender can be changed.
Private Sub gender()
    Call koneksi()
    Dim str As String
    str = "Insert into t_customer([gender]) Values (?)"
    Dim cmd As OleDbCommand = New OleDbCommand(str, conn)
    If rdnMale.Checked = True Then
        gen = rdnMale.Text
        cmd.Parameters.Add(New OleDbParameter("gender", CType(gen, String)))
    Else
        gen = rdnFemale.Text
    End If
End Sub


text:
Q: Array push function result Can someone help me with this?
The array always return blank.
var x = [];
geocoder.geocode('29 champs elysée paris', function(err, res) {
x.push(res)
});
console.log(x);

/* The result( res ) of the function is a Array....

A: geocoder.geocode() runs asynchronously.
Is this more what you're looking for?
var x = [];
geocoder.geocode('29 champs elysée paris', function(err, res) {
    x.push(res)
    console.log(x);
});

If you need to examine the array after several different geocoder.geocode() executions (or other asynchronous executions) you'd need some other infrastructure to handle that. Research asynchronous functions a bit to find examples on that.


text:
Q: Warning of pending edits on mobile app I just tried to suggest an edit for a post via the Android mobile app and once I finally hit the "Suggest" button I got an error saying I couldn't edit that post.
After checking on my desktop I discovered that another edit had been suggested, so I was unable to edit it until that was addressed. While i imagine I was probably just very unlucky and an edit went in just before mine, it would have been nice to have been alerted to that fact, either when it happened or just via the final error message.
Could an improvement be made to the mobile app to provide a clearer cause of the error in this case and cases like it?


text:
Q: If password less login is not recommended for commercial sites, what would be the best option to to do it without interaction? continued Not even able to login password-less.
$ ssh -v user@example.com
OpenSSH_6.0p1, OpenSSL 1.0.1c 10 May 2012
debug1: Reading configuration data /etc/ssh_config
debug1: Connecting to example.com [XX.XX.XX.X1] port 22.
debug1: Connection established.
debug1: identity file /home/admin/.ssh/id_rsa type 1
debug1: identity file /home/admin/.ssh/id_rsa-cert type -1
debug1: identity file /home/admin/.ssh/id_dsa type -1
debug1: identity file /home/admin/.ssh/id_dsa-cert type -1
debug1: identity file /home/admin/.ssh/id_ecdsa type -1
debug1: identity file /home/admin/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.8p1 Debian-7ubuntu1
debug1: match: OpenSSH_5.8p1 Debian-7ubuntu1 pat OpenSSH_5*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.0
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA 3b:81:30:2e:7a:c8:ca:51:7a:46:bb:50:cb:d3:a2:9b
debug1: Host 'example.com' is known and matches the ECDSA host key.
debug1: Found key in /home/admin/.ssh/known_hosts:2
debug1: ssh_ecdsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/admin/.ssh/id_rsa
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/admin/.ssh/id_dsa
debug1: Trying private key: /home/admin/.ssh/id_ecdsa
debug1: Next authentication method: password
user@example.com's password:

sshd_config file on the site I want to connect but not able to.
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 768

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication

#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

AllowUsers user

file permissions:

.ssh directory permission on the server example.com

drwx------ 2 user user      4096 2012-07-26 13:35 .ssh

permissions on the files of the .ssh file

-rw------- 1 user user  398 2012-07-26 13:35 authorized_keys
-rw-r--r-- 1 user user 1428 2012-07-25 18:55 known_hosts
--------------------------------------------------------------------

pemissions in the files ~/.ssh and ~/.ssh/ files workstation

drwx------+ 1 Admin  None     0 Jul  9 17:05 .ssh

-rw-------  1 admin None 1679 Jul  9 17:05 id_rsa
-rw-r--r--  1 admin None  398 Jul  9 17:05 id_rsa.pub
-rw-r--r--  1 admin None  383 Jul 26 13:35 known_hosts

A: Theoretical
I feel like I need to clarify some things that you may or may not understand about how SSH works:
In the context of SSH, Passwordless can refer to two things:

*

*Authenticating over SSH without supplying a password over the wire; i.e., using public key authentication

*Authenticating over SSH without supplying a password over the wire, and without using a password to protect the decryption of your private key

So there are three possible modes:

*

*Authenticate by directly supplying a password. No public/private keys are used.

*Authenticate by public/private keypair, but supply a password on your client machine to decrypt the private key and make it usable. This is done using ssh-agent. The private key decryption password is cached so that it is only supplied once for the duration of your login session; after that, the password will be saved in the ssh-agent.

*Authenticate by public/private keypair, but the keypair is not password-protected, so the user does not supply a password at all.

The second mode is the most secure. You can test this mode by creating a password-protected keypair, make sure ssh-agent is set up properly (as it is on modern Linux distros), and it should "just work": when you first login to an SSH server that uses your private key, you get a prompt to enter the password. Every time after that, until you logout, it "just works" with no prompt.
Practical

debug1: Authentications that can continue: publickey,password
  debug1: Next authentication method: publickey
  debug1: Offering RSA public key: /home/admin/.ssh/id_rsa
  debug1: Authentications that can continue: publickey,password
  debug1: Trying private key: /home/admin/.ssh/id_dsa
  debug1: Trying private key: /home/admin/.ssh/id_ecdsa
  debug1: Next authentication method: password

Try the following:

*

*Rename the known_hosts file to something else (like known_hosts.bak) on both the client and server

*On the server, logged in as user, try

chmod go-w ~/
  chmod 700 ~/.ssh
  chmod 600 ~/.ssh/authorized_keys

*On the client, logged in as admin, try

chmod 700 ~/
  chmod 700 ~/.ssh
  chmod 400 ~/.ssh/id_rsa
  chmod 400 ~/.ssh/id_rsa.pub
  #if the admin user doesn't have a group, create it and make it the admin user's primary group
  chown -R admin:admin ~/.ssh

*Make darn sure that the contents of the client's ~/.ssh/id_rsa.pub (note, the .pub is critical) is in the server's ~/.ssh/authorized_keys on one line (with no linebreaks -- but don't confuse text editor wrapping and linebreaks; use cat ~/.ssh/authorized_keys to ensure you're viewing the file without wrapping), and that the contents of the client's ~/.ssh/id_rsa is not anywhere on the server, or indeed, anywhere but that one place on the client. Note: If you have accidentally put ~/.ssh/id_rsa (the private key) on the server, I highly recommend that you delete your keypair and create a new one, starting over from scratch. You'll have to put the new id_rsa.pub into the authorized_keys file.

*???

*Profit!


text:
Q: The Witcher 3: On a new game, will I have to pay for the Enchanter of Runes max level, again? If I start the new game plus in Witcher 3, will I need to pay again for the enchanter of runes to reach the maximum level?

A: Yes, you have to pay again.
But the money you already have carries over to New Game Plus. I found that I had plenty of money to pay.


text:
Q: Creating a "Drop-Up" menu Anyone knows a jQuery menu plugin that allows that the render of menu is drop-up instead of drop-down?

A: A similar question was asked on Doctype, you should probably take a look: http://doctype.com/make-jquery-mega-menu-drop-up


text:
Q: Получения значения по ключу В общем стоит довольно таки тривиальная задача, получения значения по ключу из HashMap или TreeMap (до сих пор не знаю для этой задачи лучше использовать хеш или три мап).
char[] decode = {'A', 'B', 'D', 'B', 'D', 'D', 'D', 'C', 'D', 'D', 'B', 'D', 'D',
        'D', 'D', 'D', 'B', 'D', 'B', 'D', 'C', 'B', 'D', 'C', 'D', 'B', 'C', 'B', 'D', 'B'}; //это у нас массив который будем сравнивать с ключём в HashMap

HashMap<String,Object> map=new HashMap<String,Object>();
        Set<Map.Entry<String,Object>> entrySet=map.entrySet();
        map.put("A", "11");
        map.put("B", "01");
        map.put("C", "10");
        map.put("D", "00"); //тут мы заполнили наш HashMap ключем и значением
String encode = ""; //пустой стринг, куда будем записывать наши значения полученные по ключу
Object desiredObject=new Object();
desiredObject=decode; //тут мы приравниваем объекту массив, который будем сравнивать с ключем в хешмапе
for (Map.Entry<String,Object> pair : entrySet) {
if (desiredObject.equals(pair.getKey())) {
    encode=encode+pair.getValue();// нашли наше значение и возвращаем  значение
}

}
Честно признаюсь подобный код нашёл на просторах интернета и якобы правильный при таких операциях, только вот мой String остается всегда пустым. Изначально у меня была идея сделать обычное сравнение через двумерный цикл, как это делается с обычными массивами и списками, но в Java так просто это не работает.
Пример ответа в стринг должен быть примерно таким (11 01 00 01 00 ...) то есть все найденные значения по заданному ключу записаться в тот пустой стринг

A:     char[] decode = {'A', 'B', 'D', 'B', 'D', 'D', 'D', 'C', 'D', 'D', 'B', 'D', 'D',
        'D', 'D', 'D', 'B', 'D', 'B', 'D', 'C', 'B', 'D', 'C', 'D', 'B', 'C', 'B', 'D', 'B'}; //это у нас массив который будем сравнивать с ключём в HashMap

    Map<Character, String> map = new HashMap<>();
    map.put('A', "11");
    map.put('B', "01");
    map.put('C', "10");
    map.put('D', "00");
    StringBuilder encode = new StringBuilder();
    for (char ch : decode) {
        String get = map.get(ch);
        if (get!=null) encode.append(get);
    }

    System.out.println(encode.toString());


text:
Q: LINQ to SQL lambda exp. OrderBy, Case When,Dynamic Where I'm using LINQ to SQL and LINQ dynamic where and order by.
I want to convert the code below(ASP) to C#.net.
    function getTestimonialList(statusCd)
     sWhere = ""
     if statusCd <> "" then
    sWhere = " where status='" & statusCd & "'"
     end if
     sqlStr="select * from testimonial" & sWhere & " order by case when status = 'P' then 1 when status = 'A' then 2 else 3 end, dateadded desc"
     set rs=getResult(sqlStr)
     set getTestimonialList=rs
end function

Here is my query :
var TestimonialList = from p in MainModelDB.Testimonials
                                  where String.IsNullOrEmpty(statusCd)?"1=1":p.status== statusCd
                              orderby p.status == 'P' ? 1 : (p.status == 'A' ? 2 : 3)
                              orderby p.DateAdded descending
                              select p;

the above example doesn't work! , any idea if its possible? any other way to do it?
Thanks

A: Instead of trying to use a query expression, I suggest you use the Where, OrderBy and ThenByDescending methods directly. For example:
IQueryable<Testimonial> testimonials = MainModelDB.Testimonials;
if (!string.IsNullOrEmpty(statusCd))
{
    testimonials = testimonials.Where(t => t.status == statusCd);
}
var ordered = testimonials.OrderBy(t => t.status == 'P' ?
                                           1 : (t.status == 'A' ? 2 : 3))
                          .ThenByDescending(t => t.DateAdded);

Note the use of ThenByDescending instead of OrderByDescending - your original query used two "primary" orderings which is almost never what you want.
I'm not entirely sure that the OrderBy clause will work, but it's worth a try. If it doesn't work, please say what happens instead of just saying "it doesn't work".


text:
Q: Text input box like the SMS app on the iPhone I am having a terrible time trying to get an input box like the one in the SMS app.
Can anyone offer some guidance on how to build one of these and make it look good? I need an input box that is shaped nicely like the UITextfield but will stretch vertically when typing.
I assume that I need to calculate width of the text and stretch the overlay image frame vertically when the text word wraps. The closest I have come does stretch but the cursor bounces all around when nearing the boundaries.
UPDATE:
I have worked on this everyday for a week and I have about given up on the UITextView. I can get it to stretch properly but when backspacing, the Textview height shrinks too much when going up a line. As I continue backspacing it corrects itself. For example, it displays this behavior when I am on line 4 and backspace up to line 3. Then as I continue backspacing, it corrects until I get to the end of line 2. Then it corrects itself,.... etc.
I decided to try to subclass UITextField but I can't even get it to display in the Frame size that I specify. 150,150,150,150.

A: Try Chat Input Sample. It has the similar look and functionality of SMS app.

A: Three20 project has a control that should do this for you.
From the Three20 README:

TTTextEditor is a UITextView which can
  grow in height automatically as you
  type. I use this for entering messages
  in Facebook Chat, and it behaves
  similarly to the editor in Apple's SMS
  app.

A: You get to do this yourself.  Luckily, the UITextField can notify you whenever its text changes using UITextFieldTextDidChangeNotification, and luckily NSString has methods (under the UIKit Additions) that let you get the height of the string given a certain width using boundingRectWithSize:options:attributes:context:, and luckily you can resize a UITextField yourself using frame.

A: I know this is old but for the people that still look at this answer there is now a nice control from Slack that does that called  SlackTextViewController.


text:
Q: Laravel 4 wkHtmlToPdf routes, POST and GET issue right,
I have installed the service provider for wkhtmltopdf (https://github.com/ignited/laravel-pdf)
and when I add
Route::get('/', function() {
    $pdf = PDF::make();
    $pdf->addPage('Hello World');
    $pdf->send();
});

in my routes.php it generates a pdf file.
What I am trying to do is to POST a whole div to my controller and then generate a PDF from that.
My form:
<form id="convert" action="{{{ URL::to('') }}}/pdf" method="post">
<input type="hidden" name="body" id="body">
<input type="submit" class="btn btn-success pdf" value="Done? Convert to PDF!">
</form>

the jQuery:
$('form#convert').submit(function(){
                  $("input#body").val($("#preview").html());
              });

routes.php:
Route::post('pdf', 'PdfController@index');

and finally my controller (PdfController):
<?php

class PdfController extends BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {

        $data = Input::get('body');

                $pdf = PDF::make();
            $pdf->addPage($data);
            $pdf->send('test.pdf');
            if(!$pdf->send())
        return $pdf->getError();
    }

}

Somehow I think it;s a basic POST vs GET thing, or I'm not doing things right.
Right now I get the error Could not run command '/var/www/docassembly/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64'
but if I replace my variable inside my controller by straight html I get the same error.
If I use GET in the form and the route and pass straight html as a parameter, the error is different:
Could not run command '/var/www/docassembly/vendor/h4cc/wkhtmltopdf-amd64/bin/wkhtmltopdf-amd64' test /tmp/tmp_WkHtmlToPdf_Hq98EZ: Loading pages (1/6) [> ] 0% [======> ] 10% [============================================================] 100% Error: Failed loading page http://test (sometimes it will work just to ignore this error with --load-error-handling ignore)

So having it in the controller is also an issue.
 Any leads?

A: According to the documentation of the package you have provided, it says that you need to include the binaries in your composer.json file to make it work:

Note (you must also include wkhtmltopdf binaries)
32-bit systems
{
    "require": {
        "h4cc/wkhtmltopdf-i386": "*"
    }
}

64-bit systems
{
    "require": {
        "h4cc/wkhtmltopdf-amd64": "*"
    }
}

You can include both of these if you need.

Sounds like Laravel is trying to execute the 64bit binary and can't find it. Make sure that:

*

*You have it placed in the right folder.

*It has execution permission set with chmod.

A: Turns out the answer is quite simple, just needed to start the input with
 and end with
As my input for whtml2pdf was the content of a div, I just had to insert those html tags into the value of the input being sent to the controller and voila.


text:
Q: KafkaException: Couldn't close the Consumer? Today I've came across this one time exception which I just don't understand how could occur.
Cannot be replicated, happened twice in a row and never again.
Code structure:

try {
 Create Apache KafkaConsumer and consume something, do stuff, call commit.
consumer.close()
} Catch (Ex) {
 log stuff
} Finally {
  if (consumer) consumer.close()
}

Connection was OK - Kafka was alive because my script found and consumed a message from topic.
The thing which I can't understand: in what possible case after committing I wouldn't be able to close consumer? could kafka "died" in the middle of the process?
Btw this is just test automation, script to consume particular message.


text:
Q: Android logcat suddently does not show anything anymore I have been using Android Studio for years but now all of a sudden the logcat messages are not displayed anymore in the logcat window of Android Studio as you can see in the screenshot. I use the following code:
Log.e("Log_AvIn:", "CategoryToBeDisplayed: " + ingredientCategoryToBeDisplayed);

However, in the "Run" window you can still see the logcat messages

I tried (almost) everything from this old post (Android studio logcat nothing to show) like restarting Android Studio, Using another Emulator, Invalidating the Caches, Restarting Logcat, Change the log level to Debug (or anything else) and back to Verbose, running adb kill-server && adb start-server in the terminal (I get an error when trying to execute this), launch ddms on the command line (I get an error when tying to execute this).
Does anyone have any further idea what I can do? As said before, it just happened recently. Before everything had been good for years.


text:
Q: passing style as argument to jquery animate so i have a function for handling elements with a hover, however i want to be able to pass in the css styles as an argument.  i have tried different variations, but this is currently my code (just the necessary portion)...
function load_hovers(mouseOverCss){
  $('.hover').hover(function(){
    $(this).animate({
      eval(mouseOverCss)
    }, 500, function() {
    });

and i call load_hovers("backgroundColor: 'red'");
this returns an error invalid object initializer $(this).animate({.  without using eval, the error is missing : after property id {eval(mouseOverCss)}\n.
any suggestions?

A: You're probably better to stay away from the Eval option (Eval is evil and all that...) and try passing in an object to your method instead.
First create an object for your CSS argument:
var css = {};
css.Property = 'backgroundColor';
css.Value = 'Red';

Then you can pass this (or an array of them, if you need multiple properties) to your method:
function load_hovers(classes)
{
    $('.hover').hover(function(){
      $(this).animate({
        $(this).css(classes.Property, classes.Value); // or iterate over an array of these
      }, 500, function() {
      });
    });
}

A: got it.
var mouseOverCss = {};
mouseOverCss['backgroundColor'] = 'red';
mouseOverCss['paddingLeft'] = '100px';
load_hovers(mouseOverCss);

and then just
$(this).animate(mouseOverCss, duration);

thanks Phil for getting me on the path of not just sending a string pre-formatted for animate()!


text:
Q: Как найти точку координат в границах района? Есть координаты точки: 60.574855 56.832531
Есть точки границ района записанные в SQL TEXT: 60.562904 56.842296,60.56303 56.8423,60.563293 56.84232,60.563438 56.842346,60.563764 56.842367,60.563913 56.842395,60.564083 56.842456,60.564213 56.842482,60.564395 56.842495,60.564586 56.842476
Как то возможно с помощью php/mysql найти точку в границах этого района?
Заранее спасибо!


text:
Q: Thread safety with use of synchronized I am trying to write some code in my JAX-RS project. As this is iBeacon related I require the need to generate major minor numbers to store for a given user.
The code to register a user is as follows;
/**
 * Register a user to the application. Registration requires unique
 * username and unique email address.
 * @Override
 * @param username the username to register with
 * @param password the password to register with
 * @param email the email to register with
 * @param firstname the users firstname
 * @param lastname the users lastname
 * @return RegistrationStatus to determine if the method succeeded or not
 * @throws MajorMinorException
 */
public synchronized RegistrationStatus register(String username, String password,String email, String firstname, String lastname) throws MajorMinorException {

    if(StringUtilities.stringEmptyOrNull(username, password, email, firstname, lastname)){
        throw new IllegalArgumentException ("Unable to register the user as a value which is needed is null or empty");
    }

    if(!StringUtilities.validEmail(email)){
        throw new IllegalArgumentException("The email is not in a valid format to register with");
    }

    if(!StringUtilities.validPassword(password)){
        throw new IllegalArgumentException("The password " + password + " for user " + username + " was not in a valid format");
    }

    RegistrationStatus result = RegistrationStatus.FAILED;
    try {
        int major = super.getMajorMinor(true, username, source.getConnection());
        int minor = super.getMajorMinor(false, username, source.getConnection());
        if(major == -1 || minor == -1){
            throw new MajorMinorException("Major/Minor value was -1, possible bad data: " + username + " " + email);
        }
        Tuple<Integer, Integer> majorMinorPairs = IBeacon.incrementMajor(major, minor);
        result = register(username, password, email, firstname, lastname, majorMinorPairs.getFirst(), majorMinorPairs.getSecond(), source.getConnection());
        logger.info("major minor generated for user " + username + "  major: " + majorMinorPairs.getFirst() + " minor: " + majorMinorPairs.getSecond());
    } catch (SQLException e) {
        logger.error("An error occured when registering", e);
        return result;
    }
    return result;
}

Now i can foresee a potential scenario where we potentially have an issue. The reason being is that super.getMajorMinor(true, username, source.getConnection()); performs a MAX on the database table and then increments this by one. I assume therefore it would be possible for 2 max statements to occur at the same time (before a user has registered that pair) and therefore we would get a dirty read/write.
I could lock the table in order to preserve the integrity of the data however would another solution be to synchronise the register method. This would have the same effect as locking the table i believe but would the performance impact be worse?
Thanks


text:
Q: GCP REST api authentication missing I have created a job of JDBC to BigQuery using the web interface and it worked just fine.
Now I want to create the same job from the REST API of GCP so I took the rest equivalent of the request from the site and tried to send it from Postman.
I'm sending POST request for the following URL:
https://dataflow.googleapis.com/v1b3/projects/test-data-308414/templates:launch?gcsPath=gs://dataflow-templates/latest/Jdbc_to_BigQuery
which I got from the example in the GCP documentation.
I also pass the JSON that the GCP gave me in the body.
And the API key as get parameter in the next format "?key=[API_KEY]"
I'm getting 401 response from the server with the following message:

Request is missing required authentication credential. Expected OAuth
2 access token, login cookie or other valid authentication credential.
See
https://developers.google.com/identity/sign-in/web/devconsole-project.

With a status of:

UNAUTHENTICATED

I looked up at the link and found a tutorial on how to create google authentication on the front end
witch is not helpful to me.
I'm pretty sure that I'm passing the API key in the wrong format and that the reason it failed to authenticate.
But I couldn't find any documentation that says how to do it correctly.
PS> I have also tried passing it at the headers as I saw in one place
in the next format

Authorization : [API_KEY]

but it failed with the same message

A: Few days back I was trying to integrate GCP into MechCloud and struggling to figure out how to invoke a microservice ( which is acting as a proxy to GCP) with credentials for different projects which will be passed to this microservice on the fly. I was surprised that in spite of spending good amount of time I could not figure out how to achieve it because GCP documentation is focused on working with one project credentials at a time using application default credentials. Another frustrating thing is that API explorer shows both OAuth 2.0 and API Key by default for all the APIs when the fact is that API Key is hardly supported for any API. Finally I found the solution for this problem here.
Here are the steps to invoke a GCP rest api -

*

*Create a service account for your project and download the json file associated with it.

*Note down values of client_email, private_key_id and private_key attribues from service account json file.

*Define following environment variables using above values -

GCP_SERVICE_ACCOUNT_CLIENT_EMAIL=<client_email>
GCP_SERVICE_ACCOUNT_PRIVATE_KEY_ID=<private_key_id>
GCP_SERVICE_ACCOUNT_PRIVATE_KEY=<private_key>

*

*Execute following python code to generate jwt_token -

    import time, jwt, os

    iat = time.time()
    exp = iat + 3600

    client_email = os.getenv('GCP_SERVICE_ACCOUNT_CLIENT_EMAIL')
    private_key_id = os.getenv('GCP_SERVICE_ACCOUNT_PRIVATE_KEY_ID')
    private_key = os.getenv('GCP_SERVICE_ACCOUNT_PRIVATE_KEY')

    payload = {
        'iss': client_email,
        'sub': client_email,
        'aud': 'https://compute.googleapis.com/',
        'iat': iat,
        'exp': exp
    }

    private_key1 = private_key.replace('\\n', '\n')
    # print(private_key1)

    additional_headers = {'kid': private_key_id}

    signed_jwt = jwt.encode(
                    payload,
                    private_key1,
                    headers=additional_headers,
                    algorithm='RS256'
                )

    print(signed_jwt)

*

*Use generated jwt token from previous step and use it as a bearer token to invoke any GCP rest api. E.g.

curl -X GET --header 'Authorization: Bearer <jwt_token>' 'https://compute.googleapis.com/compute/v1/projects/{project}/global/networks'

A: The best practice to authenticate a request is to use your application credentials. Just make sure you installed the google cloud SDK.
curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://dataflow.googleapis.com/v1b3/projects/PROJECT_ID/templates:launch?gcsPath=gs://dataflow-templates/latest/Jdbc_to_BigQuery


text:
Q: How to do variable interpolation on domain property in Grails? I am new to Grails and have been looking into doing variable interpolation on a domain property which I am calling from a service.
My Domain looks like this:
class MonthlyResult {

FilterType type
String typeId
Integer year
Integer january = 0
Integer february = 0
Integer march = 0
Integer april = 0
Integer may = 0
Integer june = 0
Integer july = 0
Integer august = 0
Integer september = 0
Integer october = 0
Integer november = 0
Integer december = 0

And I am trying to do this on my MonthlyResult monthlyResult:
monthlyResult.${monthName}
where monthName is a String with the name of the month that I want.

A: You just need to add double quotes:
def monthName = 'january'
def monthlyResult = new MonthlyResult()
println monthlyResult."${monthName}"

output:
0

A: As simple as
String monthName = 'january'
assert 42 == new MonthlyResult( january:42 )[ monthName ]

Also, I'd rather use a map in such domain class, keyed by some enum values:
class MonthlyResult {

  Enum Month { january, february, .... }

  Map<Month,Integer> months
}


text:
Q: Async Databinding using ArcGIS Pro SDK and MVVM? How can we bind data to datagrid (In dockpane) using Async programing in ArcGIS Pro SDk and MVVM as one of my process will take lot of time.
Please let me know if you can have any ideas or samples.


text:
Q: Laravel4 old debug page How can I get the laravel 4 debugger page in laravel 5 debugger
page

here
to

A: Install the whoops package:
composer require filp/whoops

Then use it to render your exceptions by editing your app/Exceptions/Handler.php:
<?php namespace App\Exceptions;

use Exception;
use Whoops\Run as Whoops;
use Illuminate\Http\Response;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use PragmaRX\Sdk\Services\ExceptionHandler\Service\Facade as SdkExceptionHandler;

class Handler extends ExceptionHandler {

    protected $dontReport = [
        'Symfony\Component\HttpKernel\Exception\HttpException'
    ];

    public function report(Exception $e)
    {
        return parent::report($e);
    }

    public function render($request, Exception $e)
    {
        if ($this->isHttpException($e))
        {
            return $this->renderHttpException($e);
        }

        if (env('APP_DEBUG'))
        {
            return $this->whoops($e);
        }

        return parent::render($request, $e);
    }

    protected function whoops(Exception $e)
    {
        $handled = with(new Whoops)
                    ->pushHandler(new \Whoops\Handler\PrettyPageHandler())
                    ->handleException($e);

        return new Response(
            $handled,
            $e->getStatusCode(),
            $e->getHeaders()
        );
    }

}


text:
Q: UINavigationItem - no "free" backbutton for one of my buttons So in my main window i have these two buttons "settings"(leftBarButtonItem) & "i"(info button,rightBarButtonItem)"
When i press the info button i get the "free" back button, but i have to create one programmatically for the settings button? why is that?
Here is how i programmed the buttons in viewDidLoad
UIBarButtonItem *settingsBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:@"Settings" style:UIBarButtonItemStyleBordered target:self action:@selector(settings:)];
self.navigationItem.leftBarButtonItem = settingsBarButtonItem;

UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
CGRect frame = infoButton.frame;
frame.size.width = 40.0f;
infoButton.frame = frame;
[infoButton addTarget:self action:@selector(about:) forControlEvents:UIControlEventTouchUpInside];
butInfo = [[UIBarButtonItem alloc] initWithCustomView:infoButton];
self.navigationItem.rightBarButtonItem = butInfo;

A: How was the ViewController invoked?
In general the "Free" back button only happens if the view controller was pushed onto the navigation stack by a parent ViewController.
This could be via a Segue (if you are using Storyboard), or via - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated (message to UINavigationController).
from the UINavigationController documentation:
If the top-level view controller does not have a custom left bar button item, but the navigation item of the previous view controller has a valid item in its backBarButtonItem property, the navigation bar displays that item.
If a custom bar button item is not specified by either of the view controllers, a default back button is used and its title is set to the value of the title property of the previous view controller—that is, the view controller one level down on the stack. (If there is only one view controller on the navigation stack, no back button is displayed.)
This means that you must have set the Title property of the Parent View Controller to display a back button with it's name.


text:
Q: Display 3D function and its gradient in same graphic Is it possible to display e.g., $z=x^2+y^2$ with Plot3D and in the same box, in the $z=0$ plane, plot its gradient?

A: p = Plot3D[x^2 + y^2, {x, -1, 1}, {y, -1, 1}];
pv = VectorPlot3D[{{2 x, 2 y, 0}, {-2 y, 2 x, 0}}, {x, -1, 1}, {y, -1,
     1}, {z, -0.01, 0.01},
   PlotRange -> {Automatic, Automatic, {-1, 1}}];
Show[pv, p]


text:
Q: Lagrange multipliers: when is local extremum a global extremum? Consider the following Olympiad problem from the IMO shortlist:
Let the real numbers $a,b,c,d$ satisfy the relations $a+b+c+d=6$ and $a^2+b^2+c^2+d^2=12.$ Prove that:
$36 \leq 4 \left(a^3+b^3+c^3+d^3\right) - \left(a^4+b^4+c^4+d^4 \right) \leq 48.$

There is an elementary solution, but I tried to do it with Lagrange multipliers (2 constraints). I first showed that if $(a,b,c,d)$ is a critical point then there can be at most $3$ distinct values among $a,b,c,d$. Using this I then showed that the only critical points are (the permutations of) $(1,1,1,3)$, which is gives the local minimum of $36$, and $(2,2,2,0)$, which gives the local maximum of $48$.
However a local extremum is not necessarily are global extremum, so I am not done here.
Is there any way to verify that a local extremum is in fact global? I am asking in general.

A: In general, if you can show that your optimization problem has continuous and differentiable objective function and constraint functions and satisfies a special technical hypothesis called a constraint qualification (there are many constraint qualifications in the literature) then the Lagrange multiplier condition is a necessary condition for a point $x^{*}$ to be a local minimum (or maximum.)
In other words, if a feasible point $x^{*}$ is a local minimum (maximum), and a constraint qualification holds, then the Lagrange multiplier condition must hold at $x^{*}$.
In this situation, if you can identify all of the points that satisfy the Lagrange multiplier condition then you can simply pick the one with the smallest objective value as the global minimum.
Unfortunately, without a constraint qualification hypothesis, it could be possible that a point is an extreme point (and perhaps a global maximum or minimum) even though it doesn't satisfy the Lagrange multiplier condition!  Most discussions of Lagrange multipliers in calculus textbooks gloss over this important technical detail.
One commonly used constraint qualification is the linear independence constraint qualification (LICQ), "the gradients of the constraint functions at $x^{*}$ are linearly independent."  The LICQ is satisfied at nearly every feasible point in your problem.  You can easily finish this off by taking care of the exception(s).
It's a good exercise to setup a counter example optimization problem in which a point $x^{*}$ is a global minimum, the gradients of the constraints are linearly dependent, and you can't solve for the Lagrange multipliers.
You can find proofs of the Lagrange multiplier necessary condition with the LICQ hypothesis in many textbooks on optimization.  More advanced books will include proofs with other constraint qualifications and explore the implications between different constraint qualifications.


text:
Q: How change location of css tab I'm working with devtools and would like that my CSS tab is under the HTML elements.
So:

Instead, I'm getting this:

I know it may be very simple but haven't found the way to do it.

A: *

*click on the gear icon.

*under Appearance -> panel layout you cab change to horizontal or vertical.


text:
Q: How to create symbolic link to a path that contains unicode characters? I am using UNIX function symlink() to link a path that contains Unicode characters. However, when I read the link, it is returning ? instead of Unicode characters.
This is what my method looks like :
if (symlink("symlink.jpg", "/real/path/光芒.jpg") != 0)
    warn("symlink() error\n");
else //symlink creation successful

The symlink is created successfully at this point, however the link looks something like this:
 symlink.jpg -> /real/path/??.jpg

I was expecting the link to look like this:
 symlink.jpg -> /real/path/光芒.jpg

Can anyone tell me why this is happening?
Any fix or alternative library/function recommendation would be appreciated.
Additional information:

*

*I am suspecting that library unistd.h or fcntl.h might not have unicode support. Because when I use creat() or open() to create a new file called 光芒.jpg, it actually creates a file called ??.jpg.

*My development environment and compiler has unicode support. For example, fprint() can use unicode characters.


text:
Q: Requests to payment a gateway are failed from JMeter on cloud systems I have a JMeter Test Plan (JMX) which simulates users placing orders and making credit card payments at the end.
The script works well when it runs from my machine. Requests to the payment gateway failed only when the script was executed from a third-party JMeter online service (e.g Redline13, Blazemeter, and Loadium).
The first request failed with the following error.

I have tried with several header configurations

*

*Sending requests without any pre-defined headers

*Setting user agent explicitly in Header Manager

*Enabling Browser Compatible Headers in the HTTP Request

Also compared the requests generated from the third-party service provider and the requests generated from my machine. Also copied the headers and used them in the local machine.

It works well with the local machine but it continues to fail in the requests from the third-party services (Redline13, Blazemeter, and Loadium).
Any solution or direction is highly appreciated.

A: As per JMeter project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

so the message is quite expected.
The fact that the script works on your local machine and doesn't work in the cloud most probably means that the payment gateway (or its mock) is not reachable from the Internet.
You can increase JMeter logs verbosity for the HTTP protocol by adding the next line to log4j2.xml file (lives in "bin" folder of your JMeter installation)
<Logger name="org.apache.http" level="debug" />

and compare jmeter.log files from local and cloud runs, it will contain request and response details which you will be able to compare and figure out what's different.


text:
Q: ActiveAdmin Sidebar Ordering in Index When you add a sidebar in the index view, it shows up after the filter sidebar.
I'd like my own sidebar to appear before the filter sidebar.
Any ideas?

A: I wrote the following:
ActiveAdmin::Views::Pages::Base.class_eval do
        # Renders the sidebar
        def build_sidebar
          a = []
          sidebar_sections_for_action.collect do |section|
            a = [a, section].flatten.compact
          end
          div id: "sidebar" do
            a.reverse.each do |section|
              sidebar_section(section)
            end
          end
        end
end

save the above in app/admin/active_admin_extensions.rb,
good luck.


text:
Q: How to enable tap-to-click in libinput on Ubuntu 19.04 x11 Unity How to enable tap to click, double tap to right click and other such behaviours in libinput on Ubuntu 19.04 x11 Unity.
Enabing Tap to click in Mouse and Touchpad settings makes no difference.
The wanted behaviours work out of the box with xserver-xorg-input-synaptics installed.
I am using a Logitech Wireless Touchpad.

A: This is a well known issue. You should ideally use libinput. Then you need to simply create a file and enable the options after targeting the right device.
 $ sudo su # Get root
 # touch /etc/X11/xorg.conf.d/30-touchpad.conf
 # vim /etc/X11/xorg.conf.d/30-touchpad.conf

Here you can now add additional options. A basic one would be:
Section "InputClass"
Identifier "touchpad"
Driver "libinput"
  MatchIsTouchpad "on"
  Option "Tapping" "on"
  Option "NaturalScrolling" "on"
  Option "ClickMethod" "clickfinger"
EndSection

Don't forget to reboot after this. For more options you should check the man pages for libinput. A better write-up used to be here, and may now be read here.


text:
Q: Golang debugger not starting up on Goland I started to see the following error on my Goland IDE whenever I try to debug an application.
# runtime/cgo
cgo-builtin-prolog:1:10: fatal error: cannot open file '/usr/local/include/stddef.h': Permission denied
#include <stddef.h> /* for ptrdiff_t and size_t below */
         ^
1 error generated.

Here is my go env
GO111MODULE="on"
GOARCH="arm64"
GOBIN=""
GOCACHE="/Users/sukeesh/Library/Caches/go-build"
GOENV="/Users/sukeesh/Library/Application Support/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="arm64"
GOHOSTOS="darwin"
GOINSECURE=""
GOMODCACHE="/Users/sukeesh/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="darwin"
GOPATH="/Users/sukeesh/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/Users/sukeesh/go/go1.18"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/Users/sukeesh/go/go1.18/pkg/tool/darwin_arm64"
GOVCS=""
GOVERSION="go1.18"
GCCGO="gccgo"
AR="ar"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/sukeesh/go/src/github.com/epiFi/gamma/go.mod"
GOWORK=""
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -arch arm64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/jg/d8ghq_vx6mb1k3zjcv10bctc0000gp/T/go-build2149253438=/tmp/go-build -gno-record-gcc-switches -fno-common"

I am unable to run debug tool on Goland IDE. Can someone please help me solve this issue? Thanks in advance.


text:
Q: Sequential compactness in the space of distributions In a course on distributions titled Distributions: Topology and Sequential Compactness, the following theorem can be found on page 53 of the PDF:

Theorem 5.5.
Let $A \subset {\cal D}'(\Omega)$ be a set of distributions that is pointwise bounded, i.e. on any fixed test function $\phi \in {\cal D}(\Omega)$. Then $A$ is sequentially compact.

The problem is, the proof only establishes relative sequential compactness, i.e. it proves that any sequence in $A$ converges to some distribution $f \in {\cal D}'(\Omega)$, but does not prove that $f \in A$. Are there any references for the latter? Or is it actually incorrect?


text:
Q: The Hole Argument I have read explanations of this but haven't really understood. Given a spacetime $(M,g)$ I have read that if I represent the metric in some coordinates $(x,y,z,t)$ as $g(x,y,z,t)$ and then in another coordinate system as $g'(x',y',z',t'),$ that $g'(x,y,z,t)$ (now using the old coordinates) will also solve the Einstein equations. Now $g$ and $g'$ are two different metrics on the manifold and so should predict different physics, but somehow they are the same? If I measure the distance between two points on the manifold I should get different answers if the metrics are different, shouldn't I? This is the part I don't really understand. Is it something like $(M,g')$ isn't a solution, but only $(M',g')$ where $M'$ is diffeomorphic to $M$?
To give an explicit example, let's look at the Schwarzschild metric: \begin{equation}
 ds^2=-\left(1-\frac{2GM}{c^2 r}\right)c^2dt^2+\left(1-\frac{2GM}{c^2 r}\right)^{-1}dr^2+r^2\left(d \theta^2 +\sin^2 \theta d \phi^2\right) \;.
\end{equation} Apparently (according to http://faculty.luther.edu/~macdonal/HoleArgument.pdf) \begin{equation}
 ds^2=-\left(1-\frac{2GM}{c^2 f(r)}\right)c^2dt^2+\left(1-\frac{2GM}{c^2 f(r)}\right)^{-1}f'(r)^2dr^2+f(r)^2\left(d \theta^2 +\sin^2 \theta d \phi^2\right) \;
\end{equation}
is also a solution for any diffeomorphism $f$ though distances aren't the same. Of course when deriving the Schwarzschild metric it seems (according to Carroll's book) $(r,\theta,\phi,t)$ are just symbols that you only interpret after you find the metric, which is confusing. Note I didn't do a change of coordinates here, I changed the actual metric. Are they really both solutions on the same manifold?

A: Changing the coordinates of a metric does not change the underlying physics, nor the solution. A metric $g$ describing a manifold $M$, if under diffeomorphisms is transformed to a new metric $g'$ it will still describe the original $M$.

A: When you change coordinates, you just choose a different atlas for $\mathcal{M}$. This does not change the metric $g$, as it is defined independent of coordinates.
Now, your Schwarzschild example has little to do with this, since there you are talking about a diffeomorphism $t : \mathcal{M} \rightarrow \mathcal{M'}$. Yet, if $\mathcal{M'}$ is not already endowed with a metric, your natural choice for a metric $g'$ on it is
$$ g'(\mathrm{d}t(X),\mathrm{d}t(Y)) := g(X,Y) $$
which means requiring that $t$ is an isometry.
So, when you choose $t$ to be an automorphism of $\mathcal{M}$, and only act upon the coordinate $r$ as a smooth $f(r)$, the induced metric on the target manifold (which is $\mathcal{M}$ itself) is exactly the second metric you wrote down if the source manifold is endowed with the usual Schwarzschild metric. As these two are isometric, they describe the same physics. In particular, it implies that $g'$ is also a solution to the Einstein equations. Thus, both $(\mathcal{M},g)$ and $(\mathcal{M},g')$ are allowed spacetimes.
So, I just skimmed the paper, and, as it turns they really just do a coordinate change: They change the radial coordinate as $f(r') = r$. So, you've the metric given w.r.t. $(t,r,\phi,\theta)$ by your first equation, and you've the metric given w.r.t. $(t,r',\phi,\theta)$ by your second equation. They're the same, since, for any point $p$, the coordinates are related as $f(r') = r$. They are not two different metrics, just different coordinate expression.

A:
Now g and g′ are two different metrics on the manifold and so should
  predict different physics, but somehow they are the same?

The field equations require four coordinate conditions for a unique solution.
For the Schwarzschild line element, a coordinate condition is that the surface area of each sphere is $4\pi r^2$.
For the line element of the 2nd solution you provide, a different coordinate condition is used; the surface area of each sphere is $4\pi f^2(r)$ so this line element belongs to a different spacetime manifold but one that is a static solution for a vacuum spherically symmetric spacetime.
From the linked paper:

General relativity considers $G$ and $G'$ to live on different
  spacetime manifolds, say $M$ and $N$. To distinguish them, rename
  their $r$ coordinates to $r_M$ and $r_N$.
Map an event $E_N \in N$ at $r_N$ to the event $E_M \in M$ with $r_M =
 f (r_N)$, with the other coordinates unchanged. Then the
  transformation maps $G'$ to $G$.


text:
Q: PHP receives and sends data I have the following php code, it sends the data to a leads tool.
<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://mkt.university-private.internal/form/submit",                                                                                CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => array('mauticform[f_email]' => 'gbsilva@gmail.com','mauticform[f_name]' => 'Gabriel','mauticform[formId]' => '5'),
  CURLOPT_HTTPHEADER => array(
    "X-Forwarded-For: 91.92.103.192"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

The problem is that I have to enter the data manually in the php script.
I now have an CRM that does a POST and sends the following data in body form-data:
email=gbsilva@40gmail.com&name=Gabriel&IP=91.92.103.192&formId=5
what i need is that my php code accepts to receive an CRM post with these values above and make the request in my leads tool with the data that came from CRM.
on my erp, i can call a url and i will call the url of my script.php
he needs before sending convert and put the name of the fields between this nomenclature,
the leads tool only accepts fields with this nomenclature:
mauticform[f_FIELDNAME]
Can anyone help

A: Very easy just need to utilize $_POST to transfer values to variables and then use it
<?php

$P_email = $_POST['email'];
$P_name = $_POST['name'];
$P_formId = $_POST['formId'];
$P_ip = $_POST['IP'];

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://mkt.university-private.internal/form/submit",
  //..hidden
  CURLOPT_POSTFIELDS => array('mauticform[f_email]' => $P_email,'mauticform[f_name]' => $P_name,'mauticform[formId]' => $P_formId),

  //hidden

  //*update* FOR IP
  CURLOPT_HTTPHEADER => array(
    "X-Forwarded-For: $P_ip"
  ),
));

//..

UPDATE: So to address the dynamic variable names
//Create an array to hold the name=value pairs
$P_arr = [];
//Loop over $_POST and populate $P_arr
foreach($_POST as $key=>$value){
    $P_arr[$key] = $value;
   // $key will run through all those keys' values you sent //name ,email ..
   // so will $value but on the literals like "gbsilva@40gmail.com", "Gabriel"
}

/* We have now an array of key value pairs */
// adjust the KEYs to "mauticform"'s format before using
$mauticformArr = [];

foreach($P_arr as $key=>$value){
   if($key != 'IP'){
      if($key!= 'formId')
        $mauticformArr['mauticform[f_'.$key .']'] = $value;
      else
        $mauticformArr['mauticform['.$key .']'] = $value;
   }
}

// Then use inside you code as
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://mkt.university-private.internal/form/submit",
  //..hidden
CURLOPT_POSTFIELDS => $mauticformArr,
  //..hidden
  //..

A: You may find that "Guzzle" works better than actually using CURL ...


text:
Q: Руководство по сети в c/c++ Собственно ищу человеческое руководство по тому как организовать сетевое взаимодействие в c++ c ну и c# (благо они похожи). Может посоветуете книги или статьи?
A: Это ошибочное мнение, что сетевое взаимодействие на языках C++ и C# одинаковое (или похожее).
Несмотря на то, что в основе лежат TCP/UDP/HTTP, реализации в этих языках и соотвественно подходы к программиированию очень сильно отличаются.

*

*Для C# - нужно изучать WCF.

*Для C++  - Windows Socket и WinInet

A: Я вообще ориентировался на стандартный sys/socket.h.
Еще я использовал материал от глубокоуважаемого К.К. "Самоучитель игры на Winsock". Жалко, что под разными операционными системами приходится по-разному выкручиваться. Хотя есть возможность задействовать ту же прекрасную библиотеку Qt, благо средства сетевого взаимодействия она предоставляет. Да и Qt вполне соответствует духу ООП. Другой вопрос, что C++ + Qt - это уже не совсем C++.


text:
Q: Ubuntu 18.04 server - can unattended-upgrades cause MySQL to crash? Quick overview of the company product I'm working on before I ask my question:
We have a server running a pretty much stock install of Ubuntu 18.04 and a vision app.  The main purpose of the server is to run the vision app.  The vision app logs data to a MySQL database (the MySQL install is pretty much stock as well).  We also have a website that is essentially a front end for the database.  If the mysql systemd service stops running and does not automatically restart then the vision app will crash and not be able to restart until MySQL is started again manually, which is absolutely unacceptable (the vision app has to run 24 hours a day with not more than an occasional few seconds of downtime).
To protect out client's networks, our servers are on isolated local networks that do NOT have internet access.
What has been happening lately is the mysql systemd service has been crashing and not restarting.  I made this post:
mysql.service location on Ubuntu 18.04 server?
which resulted in doing the following:
cd /etc/systemd/system
sudo mkdir mysql.service.d
cd mysql.service.d
sudo nano override.conf

Then I entered the following for override.conf:
[Service]
Restart=always

This did not solve the problem, that is to say MySQL crashes and does not restart after anywhere from 5 to 20 hours of running.  I've check the RAM and hard disk usage during the MySQL crash and both are substantially below 75% usage so that does not seem to be the problem either.
Some Googling and browsing /var/log led me to /var/log/unattended-upgrades.  The most recent crash occurred at about 6:28 am on January 3rd, 2019.
cd /var/log/unattended-upgrades
cat unattended-upgrades.log

output:
(some stuff omitted)
2019-01-02 15:43:33,230 INFO Starting unattended upgrades script
2019-01-02 15:43:33,230 INFO Allowed origins are: o=Ubuntu,a=bionic, o=Ubuntu,a=bionic-security, o=UbuntuESM,a=bionic
2019-01-03 06:28:00,499 INFO Initial blacklisted packages:
2019-01-03 06:28:00,534 INFO Initial whitelisted packages:
2019-01-03 06:28:00,534 INFO Starting unattended upgrades script
2019-01-03 06:28:00,534 INFO Allowed origins are: o=Ubuntu,a=bionic, o=Ubuntu,a=bionic-security, o=UbuntuESM,a=bionic
2019-01-03 06:28:02,248 INFO Removing unused kernel packages: linux-modules-extra-4.15.0-29-generic linux-image-4.15.0-29-generic linux-headers-4.15.0-29 linux-headers-4.15.0-29-generic linux-modules-4.15.0-29-generic
2019-01-03 06:28:36,159 ERROR Auto-removing the packages failed!
2019-01-03 06:28:36,159 ERROR Error message: installArchives() failed
2019-01-03 06:28:36,159 ERROR dpkg returned an error! See /var/log/unattended-upgrades/unattended-upgrades-dpkg.log for details
2019-01-03 06:28:36,561 INFO No packages found that can be upgraded unattended and no pending auto-removals
2019-01-03 07:13:21,059 INFO Initial blacklisted packages:
2019-01-03 07:13:21,137 INFO Initial whitelisted packages:
(some stuff omitted)

next command:
cat unattended-upgrades-shutdown.log

output:
(some stuff omitted)
Log started: 2019-01-03  06:28:02
(Reading database ... 232457 files and directories currently installed.)
Removing linux-modules-extra-4.15.0-29-generic (4.15.0-29.31) ...
Setting up mysql-server-5.7 (5.7.24-0ubuntu0.18.04.1) ...
Checking if update is needed.
Checking server version.
Error occurred: The mysql.session exists but is not correctly configured. The mysql.session needs SELECT privileges in the performance_schema database and the mysql.db table and also SUPER privileges.
mysql_upgrade failed with exit status 5
dpkg: error processing package mysql-server-5.7 (--configure):
 installed mysql-server-5.7 package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 mysql-server-5.7
Log ended: 2019-01-03  06:28:35

I'm a vision person, not a server/networking expert, so I would not profess to understand these logs entirely, but it seems that unattended-upgrades is attempting to update MySQL and failing due to not having root permissions, which makes absolutely no sense since unattended-upgrades would need root permissions to do almost everything it does.  Anyhow, after more Googling I found this:
cd /etc/apt/apt.conf.d
cat 20auto-upgrades

output:
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";

So at this point here are my questions:
1) Based on the logs above, does seems likely that unattended-upgrades is causing the MySQL service to crash?  If so, why is this the case?
2) Being that our server does not have internet connectivity, would it be a good general practice to disable automatic updates anyway?
3) Is there anything else I should check that could cause the MySQL service to crash and not auto-restart?
4) Why did adding override.conf with Restart=always not make MySQL automatically restart?  When I type sudo systemctl start mysql.service MySQL does successfully restart.  Isn't that what the Restart=always line is supposed to do automatically?  Is there another way I can enter this line so it will actually work?
5) Has anybody else experienced unattended-upgrades causing MySQL to crash?  Is this a known problem?  I couldn't find anybody else mentioning this upon Googling which seems odd.
6) I'm under the impression that the next step is to disable auto-updates.  If this is the case, in 20auto-upgrades should I set Update-Package-Lists to 0, Unattended-Upgrade to 0, or both?  I don't see any reason to leave updating package lists on if unattended upgrade is turned off so my inclination is to set both to 0 unless somebody suggests otherwise.

A: After unattended upgrade of mysql server I had no option but remove and reinstall mysql-server and restore databases.
The samples of log files:
2019-01-24 06:19:16,643 INFO Initial whitelisted packages:
2019-01-24 06:19:16,644 INFO Starting unattended upgrades script
2019-01-24 06:19:16,644 INFO Allowed origins are: o=Ubuntu,a=cosmic, o=Ubuntu,a=cosmic-security, o=UbuntuESM,a=cosmic
2019-01-24 06:19:22,702 INFO Packages that will be upgraded: apt apt-utils libapt-inst2.0 libapt-pkg5.0 mysql-client-5.7 mysql-client-core-5.7 mysql-server mysql-server-5.7 mysql-server-core-5.7
2019-01-24 06:19:22,710 INFO Writing dpkg log to /var/log/unattended-upgrades/unattended-upgrades-dpkg.log
2019-01-24 06:22:03,228 ERROR Installing the upgrades failed!
2019-01-24 06:22:03,242 ERROR error message: installArchives() failed
2019-01-24 06:22:03,256 ERROR dpkg returned a error! See /var/log/unattended-upgrades/unattended-upgrades-dpkg.log for details

Log started: 2019-01-24  06:21:05
Preconfiguring packages ...
(Reading database ... 91129 files and directories currently installed.)
Preparing to unpack .../mysql-server-5.7_5.7.25-0ubuntu0.18.10.2_amd64.deb ...
Unpacking mysql-server-5.7 (5.7.25-0ubuntu0.18.10.2) over (5.7.24-0ubuntu0.18.10.1) ...
Preparing to unpack .../mysql-server-core-5.7_5.7.25-0ubuntu0.18.10.2_amd64.deb ...
Unpacking mysql-server-core-5.7 (5.7.25-0ubuntu0.18.10.2) over (5.7.24-0ubuntu0.18.10.1) ...
Setting up mysql-server-core-5.7 (5.7.25-0ubuntu0.18.10.2) ...
Processing triggers for systemd (239-7ubuntu10.6) ...
Processing triggers for man-db (2.8.4-2) ...
Setting up mysql-server-5.7 (5.7.25-0ubuntu0.18.10.2) ...
Checking if update is needed.
Checking server version.
Running queries to upgrade MySQL server.
mysql_upgrade: (non fatal) [ERROR] 1728: Cannot load from mysql.proc. The table is probably corrupted
mysql_upgrade: (non fatal) [ERROR] 1545: Failed to open mysql.event
mysql_upgrade: [ERROR] 1136: Column count doesn't match value count at row 1
mysql_upgrade failed with exit status 5
dpkg: error processing package mysql-server-5.7 (--configure):
 installed mysql-server-5.7 package post-installation script subprocess returned error exit status 1
Errors were encountered while processing:
 mysql-server-5.7
Log ended: 2019-01-24  06:22:02


text:
Q: Is SAXParserFactory susceptible to XXE attacks? We read our XML template files using javax.xml.parsers.SAXParserFactory. If there is XXE in the XML file we're reading, is there a way to turn off processing that?
thanks - dave

A: Yes, it is by default susceptible to XXE attacks.
Consult this cheat sheet for properly configuring the parser:
To summarize, you'll want to configure the relevant vulnerabilities with SAXParserFactory.setFeature(foo, bar) documentation


text:
Q: Is it possible to use wildcards in org.osgi.framework.system.packages.extra in Felix? Is it possible to use wildcards in org.osgi.framework.system.packages.extra in Felix?
For example, I want to export to the org.osgi.framework.system.packages.extra packages like my.package.* .

A: No, it does not. The specification literally states:

Packages specified in this property are added to the org.osgi.framework.system.packages property and therefore have the same syntax. This allows the configurator to only define the additional packages and leave the standard VM packages to be defined by the framework.


text:
Q: How to enable solr document cache between 2 independent entities? Am trying to index an application (which has both metadata and attachments along with it). Am using DIH to build the solr documents. In my DIH Config xml, i have defined 2 separate entities, in which first one will fetch the metadata for all my active records, and the second entity will fetch the attachments(can be 0 to many )for all those records.
Both these entities have a "SEQUENCE ID" in common, Is there a way i can cache the SEQUENCE IDs from my first entity & re use that in second entity?
Appreciate any help
Thanks!

<entity name="metadata" query="SELECT sequence_id,field1,field2 from     table1 where active_indicator='Y'">

<field column="sequence_id" name="seq_id"/>
<field column="field1" name="field_1"/>
<field column="field2" name="field_2" />
</entity>

<entity name="attachments" query="select t2.sequence_id,t2.field3 from     table1 t1,table2 t2 where t1.sequence_id=t2.sequence_id  and t1.sequence_id=(SELECT sequence_id from table1 where active_indicator='Y')">

<!--if i can get the t1.sequence_id cached, i can use them to select attachments for those seq ids alone-->

<field column="sequence_id" name="seq_id"/>
<field column="field3" name="field_3"/>
</entity>
</document>

A: You can wrap your dependent entities inside the entity it depends on, which will give you access to the column values for the rows in the parent entity. There's an example in the community wiki with multiple entities within each other.
<entity name="record" query="SELECT * FROM records">
  <entity name="attachment"
    query="SELECT field_1, field_2 FROM attachments WHERE SEQUENCE_ID='${record.SEQUENCE_ID}'">
    <field name="attachment_val" column="field_1" />
  </entity>
  <field ... />
</entity>

This is the basic DIH configuration and should work. To rewrite this to use the cache implementation (if that's what you're asking for), you'll have to configure the inner entity to select all rows and use the cache for lookups:
<entity name="attachment"
    query="SELECT field_1, field_2 FROM attachments"
    cacheKey="SEQUENCE_ID" cacheLookup="record.SEQUENCE_ID">
    ....
</entity>

The functionality should otherwise be the same.


text:
Q: How to set zero as the mean value when plotting a line graph in R of distance travelled per day I'm trying to plot a line graph in R displaying distance travelled per day by an individual, with days on the x axis and distance travelled (per day) on the y axis.
I want to set the value of zero so that it is equal to the mean distance travelled. This is so that I can assess when movements were more than 2 standard deviations from the mean distance.
Is there a simple way to do this in R?
My data format:
Day Distance
1    5.09902
2    0.00000
3    0.00000
4    5.09902
5    0.00000
6    0.00000

Each row represents distance travelled per day from one location to the following location.
Solution followed and data plotted:
ig1$stdDist <- (ig1$Distance - mean(ig1$Distance))/sd(ig1$Distance)

plot(ig1$stdDist)

plot(ig1$stdDist, type = "o",col = "red", xlab = "Days", ylab = "Stdev",
     main = "IG001")

A: Since you ultimately seem to be interested in looking at how many standard deviations a distance is from the mean, you may want to try standardizing your distance measurements.  You could try something like
data$stdDist <- (data$Dist - mean(data$Dist))/sd(data$Dist)

data$stdDist tells you how many standard deviations above or below the mean each of your original distances was. (Note--the code above assumes you have no missing values.)


text:
Q: how do I add an icon to an Android button in XML so I have been trying to do this for a while now, I seached google and all but I do not seem to get what I need.
I am writing an app and basically create 4 buttons.
What I want to do is place an Icon at the background of the button and write text like in weather apps where you have the cloud with next and also change the fontstyle of the text. I found icons here.how do I do this?
this is what I wrote:
`
<Button
        android:layout_width="162dp"
        android:layout_height="200dp"
        android:text="WEATHER STATION"
        android:textStyle="bold"
        android:textSize="26dp"
        android:gravity="bottom"
        android:typeface="monospace"
        android:drawableTop="@drawable/weathericon"
        android:background="@drawable/weather"
        android:id="@+id/weather_station" />`

unfortunately I cant put images yet.

A: Try replacing
android:background="@drawable/weather"
in your code with
android:background="@android:color/transparent"
android:drawableTop="@drawable/[your background image]"

A: Just call setBackgroundDrawable() on a Button to set the background of the button.
The text will appear on the button with background image.


text:
Q: How to get diff between two tar.gz I have two archive 1.tar.gz (containing hello.txt) and 2.tar.gz (containing hello.txt and helloworld.txt).
I would get the diff between this two tar.gz. The output should be helloworld.txt.
I've tried with tis command :
diff <(tar -tvf 1.tar.gz | sort) <(tar -tvf 2.tar.gz | sort)

but the output was wrong. I've got this result :
< drwxr-xr-x user/user         0 2016-12-09 23:29 1/
< -rw-r--r-- user/user       344 2016-12-09 23:29 1/hello.txt.gpg
---
> drwxr-xr-x user/user         0 2016-12-09 23:27 2/
> -rw-r--r-- user/user       344 2016-12-09 23:27 2/hello.txt.gpg
> -rw-r--r-- user/user       363 2016-12-09 23:27 2/helloworld.txt.gpg

A: This also works:
$ diff <(tar -tvf 1.tar.gz | rev | cut -d\/ -f1 | rev) <(tar -tvf 2.tar.gz | rev | cut -d\/ -f1 | rev)
1a2
> helloworld.txt.gpg

Further explanation:
The following: | rev | cur -d\/ -f1 | rev is a quick way of getting just the filename out of a full path.


text:
Q: How to save pairs of data into an one array I have XML file where I have name of currency and rate. I want to save those currencies and rate as pairs into an array, but it doesnt work, when I echo the array with foreach only last one appears.
Here's my code:
<?php
$xml = simplexml_load_file("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
$array=array();
foreach ($xml->children() as $cubeMain) {
    foreach ($cubeMain->children() as $cubeTime) {
        echo "Kursid seisuga: " . $cubeTime['time'];
        foreach ($cubeTime->children() as $cubeCurr) {
            $currency=$cubeCurr['currency'];
            $rate=$cubeCurr['rate'];
            $array = array((string)$currency => $rate);
            echo $currency . " " . $rate . "
";
        }
    }
}

foreach ($array as $currency => $rate){
    echo "$currency: $rate\n";
}

?>

A: try
$array[(string)$currency] = $rate;

instead of
$array = array((string)$currency => $rate);

A: If you expect to have several currency + rate couples, you'll want an array that contains sub-items, each one being made of currency + rate.
Typically, you'll first initialize your array :
$array = array();

Then, for each currency, you'll add an item into that array :
$array[] = array((string)$currency => $rate);

With that, you'll have a long list, but not indexed by currency -- which might not be that useful.
You'll probably, instead, prefer going with this second solution :
$array[(string)$currency] = $rate;

With that, your array will have the currency as key -- which make it much easier to find your data back, later.

Going with the second solution, your array is indexed by currency.
Which means you can find the rate for a specific currency this way :
echo $array['EUR'];  // if EUR is an exinsting currency

And loop over all data like this :
foreach ($array as $currency => $rate) {
    echo "$currency : $rate
";
}


text:
Q: Extracting Latitude and Longitude data from USB sensor (Python 3.4) I want to obtain Latitude and Longitude data from a USB GPS Sensor.
I can access the output of the GPS using the following code.
import time, serial
port ='COM5'
ser = serial.Serial(port)
ser.baudrate = 4800
line = ser.readline()
line2 = line.decode('latin-1')
print(line2.find("$GPGGA") != -1) #true when Lat & Long is available
print(line)

Different data is returned when I rerun the code. However, when the returned information contains the prefix "$GPGGA" Latitude and Longitude information is present (see Screenshot).
What is the best way to just extract/parse the Latitude and Longitude data from the returned data?
I feel this should be dead simple, and I am missing something basic.
New to programing .
Thanks
Steve

A: to get lat, orientation #1, long, orientation #2, when string is valid, just do:
if line2.startswith("$GPGGA"):
    lat,dir1,long,dir2 = line2.split(",")[2:6]

that will assign the 4 variables as the info youre looking for.


text:
Q: Executable doesn't run from terminal I have created a simple program (executable) with pyinstaller 3.2.
When I double-click it from nautilus, it runs perfectly,
but when I try to run it from terminal from another folder (/path/executable), the ui doesn't come up. If I run it from the same path (./executable), it will run perfectly again.
Any idea why does it happen?


text:
Q: wp_nav_menu() seems to ignore my given parameters Here's how my header code along with our fateful menu looks like
<body <?php body_class(); ?> id="top">

    <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home" class="logo"><?php bloginfo( 'name' ); ?>

        <?php bloginfo( 'description' ); ?>

        <?php wp_nav_menu(array(
'theme_location'  => '',
'menu'            => '',
'container'       => 'div',
'container_class' => 'wrtwert',
'container_id'    => 'sdfgdsfgsfg',
'menu_class'      => 'menu',
'menu_id'         => 'ffffff',
'echo'            => true,
'fallback_cb'     => 'wp_page_menu',
'before'          => '',
'after'           => '',
'link_before'     => '',
'link_after'      => '',
'items_wrap'      => '
%3$s
',
'depth'           => 0,
'walker'          => ''    )); ?>

    <?php get_search_form(); ?>

And here is the only output i ever get http://puu.sh/5cGNr.png. They only parameter that seems to work is the menu class, so if i change that i get a different output but it's not even targeting the class that it should. I saw this was asked time and again and i looked into the like 10 threads about this, tried the said solutions but to no avail. What i want to do is give my ul list a class, and i'd also like to know how the others can be changed if i need to in the future.

A: So yeah, a pretty stupid omission by my part but still, somebody might do the same. My problem was i had no registered menus. I omitted that because my themes were actually showing my pages in the navigation bar so i thought it was there. Quite strange.


text:
Q: How to acknowledge message in Rabbitmq in a different channel I have a query on RabbitMq consumer acknowledgement, I read documentation on RabbitMq stating that acknowledging the message should be on the same channel from which consumer received. But I'm in a situation where due to some reason consumer process is stopped after I received message and haven't acknowledge the Rabbitmq, when  the consumer process is restarted, consumer starts getting unacknowledged messages from RabbitMq, but here consumer cannot send the acknowledge to those messages as I get a channel exception stating the tag doesn't belongs to the channel. So, my question is how to handle this scenario and how can I acknowledge the rabbitmq to remove the message after my consumer process is completed reading the message?

A: As you said acknowledgement must be sent on the same channel

Acknowledgement must be sent on the same channel the delivery it is for was received on. Attempts to acknowledge using a different channel will result in a channel-level protocol exception

The easy way to do that is to use autoack=true, so the message acknowledged automatically once it is consumed.
boolean autoAck = true; // acknowledgment is covered below
channel.basicConsume(TASK_QUEUE_NAME, autoAck, consumer);

EDIT
if auto_ack does not work for you, you could use channel_consumer.basicCancel(consumerTag);
something like that:
   final Consumer consumer = new DefaultConsumer(channel_consumer) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
          String message = new String(body, "UTF-8");

          System.out.println(" [x] Received '" + message + "'");
          try {
            channel_consumer.basicCancel(consumerTag);
            System.out.println(" [x] stopping" + message + "'");

            try {
              Thread.sleep(10000);
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            System.out.println(" [x]  elaborated getting ack" + message + "'");
            channel_consumer.basicAck(envelope.getDeliveryTag(), false);

          } finally {
            System.out.println(" [x] Done");
          }
        }
      };
      boolean autoAck = false; // acknowledgment is covered below
      channel_consumer.basicConsume("test", autoAck, consumer);


text:
Q: Calling UITableView's method to update from ParserDidEndDocument, UITableView null? I have found a few questions regarding this topic but known seem to get my problem solved. I have an iPhone app that pulls and XML feed from a server, parses it, then displays the data in three UITableViews (sorting occurs at parsing). I currently have NSTimers to update the UITables once the data is done being parsed. I know there is a better way. I am trying to use the parser delegate method
In my Parser.m
    -(void)parserDidEndDocument:(NSXMLParser *)parser{
   NSLog(@"done Parsing, now update UITable in otherViewController");
    otherViewController *otherUpdatingtmp =[[otherViewController alloc] initWithNibName:@"otherViewController" bundle:nil];
    [otherUpdatingtmp updateTable];
    }

to trigger the updateTable method that is located on the otherViewController to reloadData in the table. My NSLog tells me my updateTable is firing in the otherViewController thread however I can not seem to get my TableView to update because its returned as NULL.
In my otherViewController.m
-(void)updateTable{

    [tabeViewUI reloadData];
    NSLog(@"update table fired. table view is %@.", tabeViewUI);

}

It's gotta be something small i've overlooked. Thanks in advance!
EDIT 7/24/12:
Thanks to @tc. for turning me onto using [NSNotificationCenter]
in my parser.m
-(void)parserDidEndDocument:(NSXMLParser *)parser{
  NSLog(@"done Parsing, now update UITable's with NSNotification");

    [[NSNotificationCenter defaultCenter] postNotificationName:@"parserDidEndDocument" object:self];}

then in each of my UITableViews I added:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateTable) name:@"parserDidEndDocument" object:nil];

    }
    return self;

}

lastly:
 -(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

I hope this helps someone else. It certainly helped me! Thanks @tc.


text:
Q: how to connect generated time dimension with datetime field, ssas I have a datetime field in my fact table, and I want to group and filter by it, so I created a time dimension and ssas generated a table for it that has a date without time primary key.
What is the right way to connect this generated table to my field, create a view and calculate there additional date with empty time? or there are any other more simple way, maybe using some hierarchies or something? Sorry for probably very simple question its just my second day with analysis servises

A: How do you fill your fact table. The usual way to this is in the ETL process.
You have a time dimension DIM_Date
With the columns Date_ID, Year, Month, Weekday
Then you should have a fact table FACT_Sales
With the columns Date_ID, Product_ID, Customer_ID, value
When filling the fact table with your ETL-Tool. Let's assume it is SSIS. You do a lookup in the date dimension and set the surrogate key in the facts (Date_ID) correspondingly.
If the tables are allready there. You can use a computed column in the SSAS Data Source View and set your foreign key relationship via drag and drop.