text:
Q: Changing a date format using regex in Python I'm trying to convert a date that is in the format of YYYYMMDD to MM/DD/YYYY as it is being read from a database and written to an Excel file. Using Perl I would do the following:
var=~s/([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])/$5$6\/$7$8\/$1$2$3$4/;

Keeping in mind that this is all happening in a "for row in rows" loop structure that is reading in the database info.
Any help would be very much appreciated.

A: instead of using a regular expression you can use pythons datetime module.
or you could combine the two, however it is you want, but this would be a more clear way to modify date formatting. python is a language where clarity and easy reading are as important as efficiency. looking at the code below one can see that i am modifying a datestamp, whereas using a regular expression it is quite unclear sometimes.
read the datetime element and then write it as you want:
>>> from datetime import datetime
>>> datestring = '20121212' # 2012 / 12 /12
>>> datetime.strptime(datestring, '%Y%m%d').strftime('%m/%d/%Y')
'12/12/2012'

A: I would go for simple string operations - certainly no less clear...
>>> s = '20121213'
>>> '/'.join( (s[4:6], s[6:], s[:4]) )
'12/13/2012'

as opposed to:
>>> re.sub(r'(\d{4})(\d{2})(\d{2})', r'\2/\3/\1', s)
'12/13/2012'

If you're going to insist using an re like you've posted below though

dateFormatted = row["TRADE_DATE"] dateFormatted =
  re.sub(r'(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)', r'\5\6/\7\8/\1\2\3\4',
  dateFormatted) – user1901341 5 mins ago

Then you could (ab)use string formatting as such
>>> '{4}{5}/{6}{7}/{0}{1}{2}{3}'.format(*s)
'12/13/2012'

A: You don't need to use a regex -- Python doesn't encourage them in the same way Perl does -- but you can certainly use one:
import re
re.sub(r'(\d{4})(\d{2})(\d{2})', r'\2/\3/\1', datestring)

A: I think you can get to it simply here, without regex:
>>> s = '20121225'
>>> conv = '/'.join((s[6:8], s[4:6], s[0:4]))
>>> conv
'25/12/2012'


text:
Q: Java primitive comparison performance I'm comparing int a and int b. Is there any performance difference between if(a>=b){...}  vs
if(a==b || a>b){...}? Thanks

A: You can always look at the byte code to see what's a happening at a lower level. This doesn't mean all compilers / options will do it the same, but I suppose the important one is the one you are using. Also, while it's a lower level, it's not the lowest level. As mentioned elsewhere on this site "Optimization in Java is mostly done by the JIT compiler at runtime". So  in the end you can't avoid some leap of faith that Java will do the smart thing for you in cases like this.
int foo(int a, int b) {
    if (a == b || a > b) return 1;
    return 0;
}

int bar(int a, int b) {
    if (a >= b) return 1;
    return 0;
}

Using javap -c on the class file you can see:
int foo(int, int);
Code:
   0: iload_1
   1: iload_2
   2: if_icmpeq     10
   5: iload_1
   6: iload_2
   7: if_icmple     12
  10: iconst_1
  11: ireturn
  12: iconst_0
  13: ireturn

int bar(int, int);
Code:
   0: iload_1
   1: iload_2
   2: if_icmplt     7
   5: iconst_1
   6: ireturn
   7: iconst_0
   8: ireturn

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как в laravel изменить путь на авторизацию и при этом передать параметр? Только начал изучать фреймворк Laravel и столкнулся с задачей, ответ на которую пока нигде не нашёл. Самостоятельно не смог решить. Прошу помочь разобраться.
Версия
Laravel Framework 6.10.1
Задача
Изменить путь на страницы авторизации и добавить в адрес параметр.
Описание
После выполнения команд

*

*composer require laravel/ui

*php artisan ui vue

*php artisan ui:auth

... получаем шаблоны, которые расположены в resources/views/auth и в resources/views/layouts
Теперь, чтобы попасть на страницу входа в адресной строке вводим адрес
localhost/login
Это адрес по умолчанию. Как его изменить таким образом, чтобы обеспечить мультиязычность сайта?
Адрес должен быть такого вида:

*

*localhost/ru/login

*localhost/en/login

*... и т. д.

В файле routes\web.php после выполнения команд выше, изначально прописано:
Auth::routes();

Для переопределения маршрутов нашёл в интернете вариант, как в листинге ниже. Если сейчас изменить адрес для входа в систему, то получится перейти на страницу.
// Login
Route::group(['middleware' => ['web']], function() {
    Route::get('/en/login', ['as' => 'login', 'uses' => 'Auth\LoginController@showLoginForm']);
    Route::post('/en/login', ['as' => 'login.post', 'uses' => 'Auth\LoginController@login']);
    Route::post('/en/logout', ['as' => 'logout', 'uses' => 'Auth\LoginController@logout']);
});
// Registration Routes...
    Route::get('register', ['as' => 'register', 'uses' => 'Auth\RegisterController@showRegistrationForm']);
    Route::post('register', ['as' => 'register.post', 'uses' => 'Auth\RegisterController@register']);

// Password Reset Routes...
    Route::get('password/reset', ['as' => 'password.reset', 'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm']);
    Route::post('password/email', ['as' => 'password.email', 'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail']);
    Route::get('password/reset/{token}', ['as' => 'password.reset.token', 'uses' => 'Auth\ResetPasswordController@showResetForm']);
    Route::post('password/reset', ['as' => 'password.reset.post', 'uses' => 'Auth\ResetPasswordController@reset']);

Но, так как нужно передавать разные значения, то первая часть адреса должна передавать параметром:
'/{lang}/login'

Но при таком варианте получаю ошибку:
LOG.error: Missing required parameters for [Route: login] [URI: {url_lang}/login]. (View: C:\xampp\htdocs\laravel\poligon.local\resources\views\layouts\app.blade.php) {"exception":{}}

Какие изменения нужно внести, чтобы решить эту задачу?

A: Добавить префикс
Route::group([
    'prefix' => '{lang?}',
], function () {
    Auth::routes();
});

И добавить смену языка в RouteServiceProvider::boot()
Route::pattern('lang', 'en|ru|lv');

Route::matched(function (RouteMatched $event) {
    app()->setLocale($event->route->parameter('lang'));
});

Вот похожие темы:
https://laracasts.com/discuss/channels/laravel/optional-language-for-all-routes
https://laraveldaily.com/multi-language-routes-and-locales-with-auth/

A: Для описанной задачи меня полностью устроило решение показанное в этом видео: https://youtu.be/_BsHyHc9NqE


text:
Q: Cut-off frequency of a LED I'm trying to solve this problem:

A GaAs LED is at \$ 300 K \$ when the current density is 1000 \$A/cm^2\$
. The width of the active region is \$ 1 µm \$. Assume that, for that current, we are in the strong injection regime, and
that the bimolecular coefficient is \$10^{-10} cm^3
/s \$.
Calculate the cut-off frequency for that current density.

I know the answer is 12.5 MHz.
I know that the cut-off frequency relates do the carrier's lifetime.
$$f_c=\frac{1}{2 \pi \tau}$$
Right, so now I need to calculate the carrier's lifetime. I know that since this is strong injection we would have:
$$\tau=\frac{1}{B \Delta n_0}$$
where B is the bimolecular coefficient. So now I need to calculate \$ \Delta n_0 \$.
My question now is how can I use the temperature, the current density and the width of the active region to calculate \$ \Delta n_0 \$? I feel that I might need some parameters of GaAs at 300 K, but I'm having trouble understanding what parameters.

A: After a bit of digging, I found this:
Equation 9.17 in this chapter
You can manipulate that equation as -
$$n=\sqrt{\frac{J}{edB}}$$
Given:
\$J=1000A/cm^2\$
\$B=10^{-10}cm^3/s\$
\$d=10^{-4}cm\$
\$e=1.6\times10^{-19}C\$
Therefore -
$$n=\sqrt{\frac{10^{36}}{1.6}}\approx\mathbf{0.791\times10^{18}/cm^3}$$
Calculate carrier lifetime -
$$\tau=\frac{1}{B \Delta n}\approx\mathbf{12.64 \text{ ns}}$$
Calculate cut-off frequency -
$$f_c=\frac{1}{2 \pi \tau}\approx\mathbf{12.6\text{ MHz}}$$


text:
Q: Getting an error when doing INSERT in Spring Data JPA I get an
org.h2.jdbc.JdbcSQLSyntaxErrorException: Column "PRICEAFTERDISCOUNT" not found; SQL statement:

This is my Item class
package com.example.demo.model.persistence;

import java.math.BigDecimal;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Entity
@Data
@Table(name = "item")
public class Item {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @JsonProperty
    private Long id;

    @Column(nullable = false)
    @JsonProperty
    private String name;

    @Column(nullable = false)
    @JsonProperty
    private BigDecimal price;

    @Column(nullable = false)
    @JsonProperty
    private BigDecimal priceAfterDiscount;

    @Column(nullable = false)
    @JsonProperty
    private String description;

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Item other = (Item) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }
}

And this is my data.sql file
insert into item (name, price, priceAfterDiscount, description) values ('Travel Card Holder', 9.25, 0, 'A holder for your travel card');

insert into item (name, price, priceAfterDiscount, description) values ('Personalised cufflinks', 45.00, 0, 'Cufflings with your initials');

insert into item (name, price, priceAfterDiscount, description) values ('Kids T-shirt', 19.95, 0, 'A T-shirt with dinosaurs')

As far as I can tell, I have added the priceAfterDiscount into my insert statement so I do not
understand where the error comes from, or why it occurs in the first place. Please help!
I have added the priceAfterDiscount field in the Item class. And annotated the same way as the rest of the fields. Also, the syntax looks correct to me

A: The exception means your database table item does not contain a column named PRICEAFTERDISCOUNT. Check database column name and add it over field annotation argument this way @Column(name="database_column_name", nullable = false).
data.sql statements have to contain the right column names also.


text:
Q: Java/JavaFX slider decimal points I'm a new JavaFX programmer and my question is I'm getting multiple decimal points in the slider and I only want one.
I'm getting like 99.99999999999 for each value within but I would love to get only one like 99.9
The thing is printf is not applicable here I guess and I only know that way >.<
private void createView() {

        final GridPane radioGridPane = new GridPane();
        final Label frequencyLabel = new Label("something");
        final Slider sliderFrequency = new Slider(87.9, 107.9, 90);

        frequencyLabel.textProperty().bind(sliderFrequency.valueProperty().asString());
        radioGridPane.add(frequencyLabel, 2, 1);
        radioGridPane.add(sliderFrequency, 3, 1);

        this.setCenter(radioGridPane);
        radioGridPane.setGridLinesVisible(true);
    }

A: You were actually quite close. You can use asString method with the following signature:
javafx.beans.binding.NumberExpressionBase#asString(java.lang.String)
that accepts a format parameter.
Example usage:
public class FormatBindingSSCCE extends Application {

    @Override
    public void start(Stage stage) {
        final Label frequencyLabel = new Label();
        final Slider sliderFrequency = new Slider(87.9, 107.9, 90);
        frequencyLabel.textProperty().bind(sliderFrequency.valueProperty().asString("%.1f"));

        final GridPane radioGridPane = new GridPane();
        radioGridPane.add(frequencyLabel, 2, 1);
        radioGridPane.add(sliderFrequency, 3, 1);

        final Scene scene = new Scene(radioGridPane);
        stage.setScene(scene);
        stage.show();
    }

}


text:
Q: Using log4net in Xamarin Android I figured, that there is a modified log4net version that supports iOS and I somewhat see how that was accomplished (it's open source), but unfortunately I don't have enough experience to do that on my own for Android.
I tried my best and got the ConsoleAppender to work on Android, but the FileAppender seems to need mutexes and they are not supported on Android as far as I understand.
So is there any way I can get log4net to work on Android?


text:
Q: Multiple @RabbitListeners sending reply to same queue when using sendAndReceive() in producer I am using SpringBoot with Spring AMQP and I want to use RPC pattern using synchronous sendAndReceive method in producer. My configuration assumes 1 exchange with 2 distinct bindings (1 for each operation on the same resource). I want to send 2 messages with 2 different routingKeys and receive response on distinct reply-to queues
Problem is, as far as I know, sendAndReceive will wait for reply on a queue with name ".replies" so both replies will be sent to products.replies queue (at least that is my understanding).
My publisher config:
    @Bean
    public DirectExchange productsExchange() {
        return new DirectExchange("products");
    }

    @Bean
    public OrderService orderService() {
        return new MqOrderService();
    }

    @Bean
    public RabbitTemplate rabbitTemplate(final ConnectionFactory connectionFactory) {
        final RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(producerJackson2MessageConverter());
        return rabbitTemplate;
    }

    @Bean
    public Jackson2JsonMessageConverter producerJackson2MessageConverter() {
        return new Jackson2JsonMessageConverter();
    }

and the 2 senders:
...
final Message response = template.sendAndReceive(productsExchange.getName(), "products.get", message);
...

final Message response = template.sendAndReceive(productsExchange.getName(), "products.stock.update", message);

...

consumer config:

    @Bean
    public Queue getProductQueue() {
        return new Queue("getProductBySku");
    }

    @Bean
    public Queue updateStockQueue() {
        return new Queue("updateProductStock");
    }

    @Bean
    public DirectExchange exchange() {
        return new DirectExchange("products");
    }

    @Bean
    public Binding getProductBinding(DirectExchange exchange) {
        return BindingBuilder.bind(getProductQueue())
                .to(exchange)
                .with("products.get");
    }

    @Bean
    public Binding modifyStockBinding(DirectExchange exchange) {
        return BindingBuilder.bind(updateStockQueue())
                .to(exchange)
                .with("products.stock.update");
    }

and @RabbitListeners with following sigratures:
 @RabbitListener(queues = "getProductBySku")
    public Message getProduct(GetProductResource getProductResource) {...}

 @RabbitListener(queues = "updateProductStock")
    public Message updateStock(UpdateStockResource updateStockResource) {...}

I noticed that the second sender receives 2 responses, one of which is of invalid type (from first receiver). Is there any way in which I can make these connections distinct? Or is using separate exchange for each operation the only reasonable solution?

A:
as far as I know, sendAndReceive will wait for reply on a queue with name ".replies"

Where did you get that idea?
Depending on which version you are using, either a temporary reply queue will be created for each request or RabbitMQ's "direct reply-to" mechanism is used, which again means each request is replied to on a dedicated pseudo queue called amq.rabbitmq.reply-to.
I don't see any way for one producer to get another's reply; even if you use an explicit reply container (which is generally not necessary any more), the template will correlate the replies to the requests.
Try enabling DEBUG logging to see if provides any hints.


text:
Q: How to find the highest number in a 2-dimensional array? Hi all and thanks in advance for your help.
So I would like to find the highest number in a 2-dimensional array.
Below is the code:

const matrix = [
  [2, 56, 10],
  [20, 34, 10],
  [23, 144, 26]
];
let maximum = matrix[0][0];
for (var row = 0; row < matrix.length; row++) {
  for (var col = 0; col < matrix.length; col++) {
    if (matrix[row][col] > maximum) {
      maximum = matrix[row][col];
    };
  };
};
document.write(' -- ', maximum);

Here is my problem -  Could you please help me to understand why when I have more numbers in the array I cannot see the highest number - Find below an example ):

const matrix = [
  [2, 56, 10, 14, 422, 3242],
  [20, 34, 55, 100, 33, 422],
  [23, 12, 14, 26, 203, 233]
];
let maximum = matrix[0][0];
for (var row = 0; row < matrix.length; row++) {
  for (var col = 0; col < matrix.length; col++) {
    if (matrix[row][col] > maximum) {
      maximum = matrix[row][col];
    };
  };
};
document.write(' -- ', maximum);

A: row < matrix.length tests the correct thing. col < matrix.length does not: you should replace it with col < matrix[row].length.
However, there is an easier way, using some of the newer JavaScript features:

const matrix = [[2,56,10,14,422,3242],[20,34,55,100,33,422],[23,12,14,26,203,233]];
const maximum = Math.max(...matrix.flat())
console.log(maximum);

matrix.flat() will flatten the two-dimensional array into one dimension, ... syntax will put each value from the one-dimensional array as its own argument to Math.max, which then finds the biggest one.

A: There is one small mistake. When you iterate the column make sure you iterate the number of columns.
matrix.length gives you the number of rows and matrix[i].length gives you the number of columns.

const matrix = [[2,56,10,14,422,3242],[20,34,55,100,33,422],[23,12,14,26,203,233]];
let maximum = matrix[0][0];
for(var row = 0; row < matrix.length; row++){
  for(var col = 0; col < matrix[row].length; col++){
    if(matrix[row][col] > maximum){
      maximum = matrix[row][col];
    };
  };
};
document.write(' -- ', maximum);

A: You are taking matrix.length for no. of column as well, but it gives you no. of rows i.e. 3  but in your case but no. of column is 6 . that's why it only check for 3 numbers

const matrix = [[2,56,10,14,422,3242],[20,34,55,100,33,422],[23,12,14,26,203,233]];
let maximum = matrix[0][0];
for(var row = 0; row < matrix.length; row++){
  for(var col = 0; col < matrix[0].length; col++){          <--- Correction
    if(matrix[row][col] > maximum){
      maximum = matrix[row][col];
    };
  };
};
document.write(' -- ', maximum);

A: Also can use Array.prototype.reduce() combined with Math.max():

const matrix = [[2,56,10,14,422,3242],[20,34,55,100,33,422],[23,12,14,26,203,233]]

const maximum = matrix.reduce((a, c) => Math.max(a, ...c), 0)
console.log(maximum)


text:
Q: Import VS Connect live for SQL Server analysis Services After setting up my ETL, now I'm preparing the reporting phase. I want to know the diffrence between Import and Connect live a SQL Server analysis Services database methods knowing that I'll be working with measures.
In my example : I need to create a measure which count the emails with failed status by department.
I have (after importing the cube) :

*

*Fact Mailing Count

*Mail Status Dimension

*Message Template Dimension (having the application name which is the
same name of the department)

A: Live connect: This will connect power bi to analysis services data model directly.so you will be building your model completely on analysis services project and deploying it frequently. So the power bi will have a live connection to the model and make updates when necessary. when new data processed or new measures or tables created. Here the limitation is you cannot combine multiple sources of data and you have to rely on the SASS Model you have already connected with.
Import: This will import tables to the Power bi and you will be allowed to create and manipulate your facts and dimensions as per your wish inside the power bi(in live connect mode you have to do it in analysis services model itself).
The main obstacle of import mode is When you import large tables will a large number of data, power bi has limitations(1GB) on that.
Creating measures and calculated tables are allowed in both modes.the difference is on which side you create them.
A detailed comparison of both Live connect and Import
https://community.powerbi.com/t5/Community-Blog/Power-BI-Live-connection-vs-Import-comparison-and-limitations/ba-p/84377


text:
Q: Extract amplitude array from a wav File using JAVA I am trying to extract amplitude array from an audio file(WAV file). I will be using this amplitude array to plot amplitude vs time graph for the given wav file. I am able to plot the graph myself but does not know how to extract the amplitude from given audio(wav) file in java?

A: Here is a helper class that you can use. The getSampleInt() method is what you need to get the amplitude:
File file = ...;
WavFile wav = new WavFile(file);

int amplitudeExample = wav.getSampleInt(140); // 140th amplitude value.

for (int i = 0; i < wav.getFramesCount(); i++) {
    int amplitude = wav.getSampleInt(i);
    // Plot.
}

It also can play files so that you can test it, but only 8bit, or 16bit files. For other cases you can only read them.
Also, please look at these diagrams to see what WAV files consist of and better understand what this class does.
public class WaveFile {
    public final int NOT_SPECIFIED = AudioSystem.NOT_SPECIFIED; // -1
    public final int INT_SIZE = 4;

    private int sampleSize = NOT_SPECIFIED;
    private long framesCount = NOT_SPECIFIED;
    private int sampleRate = NOT_SPECIFIED;
    private int channelsNum;
    private byte[] data;      // wav bytes
    private AudioInputStream ais;
    private AudioFormat af;

    private Clip clip;
    private boolean canPlay;

    public WaveFile(File file) throws UnsupportedAudioFileException, IOException {
        if (!file.exists()) {
            throw new FileNotFoundException(file.getAbsolutePath());
        }

        ais = AudioSystem.getAudioInputStream(file);

        af = ais.getFormat();

        framesCount = ais.getFrameLength();

        sampleRate = (int) af.getSampleRate();

        sampleSize = af.getSampleSizeInBits() / 8;

        channelsNum = af.getChannels();

        long dataLength = framesCount * af.getSampleSizeInBits() * af.getChannels() / 8;

        data = new byte[(int) dataLength];
        ais.read(data);

        AudioInputStream aisForPlay = AudioSystem.getAudioInputStream(file);
        try {
            clip = AudioSystem.getClip();
            clip.open(aisForPlay);
            clip.setFramePosition(0);
            canPlay = true;
        } catch (LineUnavailableException e) {
            canPlay = false;
            System.out.println("I can play only 8bit and 16bit music.");
        }
    }

    public boolean isCanPlay() {
        return canPlay;
    }

    public void play() {
        clip.start();
    }

    public void stop() {
        clip.stop();
    }

    public AudioFormat getAudioFormat() {
        return af;
    }

    public int getSampleSize() {
        return sampleSize;
    }

    public double getDurationTime() {
        return getFramesCount() / getAudioFormat().getFrameRate();
    }

    public long getFramesCount() {
        return framesCount;
    }

    /**
     * Returns sample (amplitude value). Note that in case of stereo samples
     * go one after another. I.e. 0 - first sample of left channel, 1 - first
     * sample of the right channel, 2 - second sample of the left channel, 3 -
     * second sample of the rigth channel, etc.
     */
    public int getSampleInt(int sampleNumber) {

        if (sampleNumber < 0 || sampleNumber >= data.length / sampleSize) {
            throw new IllegalArgumentException(
                    "sample number can't be < 0 or >= data.length/"
                            + sampleSize);
        }

        byte[] sampleBytes = new byte[4]; //4byte = int

        for (int i = 0; i < sampleSize; i++) {
            sampleBytes[i] = data[sampleNumber * sampleSize * channelsNum + i];
        }

        int sample = ByteBuffer.wrap(sampleBytes)
                .order(ByteOrder.LITTLE_ENDIAN).getInt();
        return sample;
    }

    public int getSampleRate() {
        return sampleRate;
    }

    public Clip getClip() {
        return clip;
    }
}

A: I tried your code and with a few minor changes it created a result. Whats wrong with the data the code puts out?
I Changed the following lines:
// create file input stream
      DataInputStream fis = new DataInputStream(new FileInputStream(wavFile));
      // create byte array from file
      arrFile = new byte[(int) wavFile.length()];
      fis.readFully(arrFile); // make sure you always read the full file, you did not check its return value, so you might be missing some data

The second thing I changed was:
System.out.println(Arrays.toString(s.extractAmplitudeFromFile(f)));

In your Main method, since you were only printing out the adress of the arary. After those changes the code put out an array that had values, that seemed to correlate with the desired data.
what excatly are you missing, or what do you expect of the data? Could you please clarify the question a bit more?


text:
Q: Retrieve the output of a python script with Java I would like to run a python script that is based on speech recognition using Java and retrieve the script outputs with Java.
I managed without much trouble to call the script and run it. It works perfectly. However I do not understand why I can not recover the outputs print with java.
here is the script python :
import aiml
import os
import time, sys
import pyttsx
import warnings

# Initialisation of the different mode
# If no specification, Jarvis will run as a text Personnal
mode = "text"
if len(sys.argv) > 1:
    if sys.argv[1] == "--voice" or sys.argv[1] == "voice":
        import speech_recognition as sr
        mode = "voice"

# Jarvis speaking part
def offline_speak(jarvis_speech):
    engine = pyttsx.init()
    engine.say(jarvis_speech)
    engine.runAndWait()

# Jarvis listenning part
def listen():
    # Jarvis listen the environnemnt to capture the voice
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Talk to JARVIS: ")
        # Jarvis is listenning
        audio = r.listen(source)
    try:
        # Print and return what Jarvis heard
        print ("test")
        print r.recognize_google(audio, language='fr-FR')
        return r.recognize_google(audio, language='fr-FR')
    except sr.UnknownValueError:
        # If Jarvis doesn't know the sentence or the word you said
        offline_speak("Je n'ai pas compris ce que vous avez dit, pouvez vous repeter s'il vous plait ?")
        print ("test")
        # Return what he heard
        return(listen())
    except sr.RequestError as e:
        # Jarvis didn't understand what you said
        print("Could not request results from Speech Recognition service; {0}".format(e))

# Jarvis running part
while True:
    if mode == "voice":
        response = listen()
        print ("test")
    else:
        response = raw_input("Talk to JARVIS : ")

    offline_speak(response)
    print ("test")

And here is my class java :
import java.io.File;
import java.util.LinkedList;
import java.util.List;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PythonCaller {

    private final String pythonPrjPath;
    private final String scriptName;
    private final String args;

    public PythonCaller(String scriptName, String args) {
        this.scriptName = scriptName;
        this.pythonPrjPath = argTreatment();
        this.args = args;
    }

    public void call() throws Exception {
        try {

            List<String> commands = new LinkedList<>();
            commands.add("python");
            commands.add(pythonPrjPath);
            commands.add(args);

            ProcessBuilder pb = new ProcessBuilder(commands);
            Process p = pb.start();

            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

            // read the output from the command
            String s;
            while ((s = stdInput.readLine()) != null) {
                System.out.println(s);
            }

        } catch (Exception e) {
            throw e;
        }
    }

    private String argTreatment() {
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource(scriptName).getFile());
        StringBuilder resPpythonPrjPath = new StringBuilder(file.getAbsolutePath());
        StringBuilder sb = new StringBuilder(resPpythonPrjPath.subSequence(0,90));
        return sb.toString();
    }

    public static void main(String[] args) {

        String tabArgs = "voice";
        PythonCaller pc = new PythonCaller("listener.py", tabArgs);
        try {
            pc.call();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Thanks for your help

A: I wasn't able to solve my problem so I decided to avoid it. Instead of reading the print, I write the data I want to retrieve in a textfile and I read the textfile from java


text:
Q: Working setup for MySQL HA & LB I have to setup High Availability and Load balancing for web(apache-tomcat+mod_jk) and MySQL(where all clients info is stored) server which are running on the same machine(ubuntu server). First I am trying to setup for the MySQL databases with minimal setup of servers(2 or 3).
I heard about master-slave setup which is not suitable for HA as there is some down time while making the slave a master when master is down.
I also heard about the master-master setup and is said to have some disadvantages like conflicting problems.
Anybody know any reliable and best setup which could be implemented for production?
EDIT 1:
I have checked setting up master-master and master-slave and didn't see any problem or trouble giving in syncing over LAN and I'm not sure these works flawless on production systems. I heard load balancing of mysql databases are possible and may not be possible and I'm not sure of this.
I heard about mysql cluster 7 and seems to be powerful of all the available options but I could not find any proper documentation setup.

A: There is a plethora of information on HA & LB for MySQL available on the web, and in print.  What research have you done so far?  I suggest starting here.

A: You should check out Tungsten Enterprise or Schooner Active Cluster.
The strictly open source (read free) solutions can't really solve your problem. MMM tries but it has come under scrutiny lately and is not recommended by one of the experts in the field.
You are going to have to shell out some dollars to solve your problem which kinda lends some weight to Flimzy's point that it may be prudent to consider other solutions on the DB tier.
Cheers


text:
Q: Difference of MONGODB C++ DRIVER mongocxx and legacy On MongoDB's official manual, there are two drivers:
 mongocxx 3.0.x and legacy 1.1.x
I am puzzling which version to choose and what is their difference.
Thanks in advance for anyone could help me!

A: If you can use C++11, you should absolutely use mongocxx. The legacy driver is just that, legacy. In fact, if you can't use C++11 for some reason, you might be better off just using the plain C driver. The legacy C++ driver does not implement the modern driver specifications, and is not receiving feature updates, only maintenance bugfixes.


text:
Q: Rails: Jquery Ajax issue with slidetoggle I have a comment section that is apart of a micropost and I am trying to click a button within the micropost so that the comment section which is displayed as none in the CSS slides and shows. The problem is that all 10 micropost's comment button opens the most recent micropost when it should be opening it's own comment section of the micropost. I am unsure how to change the javascript around along with the HTML to make the comment button dynamic to it's own micropost. Here is what I am working with, any help is much appreciated. Thank you.
JS
$(".CommentTitle").click(function(){
    $("#CommentContainer").slideToggle("slow", function(){
        $(".CommentTitle").html($(this).is(":hidden") ? "Comments" : "Comments");
    });
});

HTML

5
Comments

<div id='CommentContainer' class='<%= micropost.id%>'>

<%=render "comments/form" %>

<%=render @micropost.comments %>

A: $(".CommentTitle").click(function(){
    $("#CommentContainer", this.parent()).slideToggle("slow", function(){
        $(".CommentTitle", this).html($(this).is(":hidden") ? "Comments" : "Comments");
    });
});

You can add a context to a jQuery selector, so that it will only match below that element. In this instance, I've added this.parent() to the container selector so it will only match #CommentContainer inside the clicked container, and this to the title selector so it will match the title within the current container.
This assumes your micropost HTML looks something like this:

  Some clickable title

data here

The element types don't matter, just that CommentTitle is a direct child of CommentContainer.

A: Change your HTML so that you don't have duplicate IDs on your CommentContainer elements. That is why jQuery is only finding the first one - you are creating invalid HTML.
Assuming you have one Comment button per micropost, you should add the micropost id as a data attribute to the Title, and retrieve that to find the correct CommentContainer. Each comment container should include the ID of the micropost it belongs to in it's ID.
HTML:

        5
        <span class='CommentTitle' data-micropost='<%= micropost.id %>'>Comments

<div id='CommentContainer-<%= micropost.id%>' class='CommentContainer'>

        <%=render "comments/form" %>

        <%=render @micropost.comments %>

Javscript:
$(".CommentTitle").click(function(){
    var title = this;
    var postID = $(this).data('micropost');
    $("#CommentContainer-" + postID).slideToggle("slow", function(){
        $(".CommentTitle", title).html($(this).is(":hidden") ? "Comments" : "Comments");
    });
});

Change your CSS to hide .CommentContainer instead of #CommentContainer


text:
Q: Android YouTube Data API search.execute() doesn't work I'm not new to Java but I am new to developing on Android Studio and their platform along with the YouTube Data API and I'm having a problem with the app crashing due to the line SearchListResponse searchResponse = search.execute();
this is causing me a little frustration and I would like some help as it will help me learn and proceed with my project rather than giving up.
try {
         youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
              public void initialize(HttpRequest request) throws IOException {}
         }).build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        search.setKey(youtubeKey);
        search.setQ(s);
        search.setType("video");

        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute(); // line that crashes app
        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {

            Iterator<SearchResult> iteratorSearchResults = searchResultList.iterator();

            while (iteratorSearchResults.hasNext()) {
                SearchResult singleVideo = iteratorSearchResults.next();
                ResourceId rId = singleVideo.getId();

                if (rId.getKind().equals("youtube#video")) {
                    name.add(singleVideo.getSnippet().getTitle());
                    desc.add(singleVideo.getSnippet().getDescription());
                    image.add(singleVideo.getSnippet().getThumbnails().getDefault().getUrl());
                }

            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

Logcat where everything goes red (error)

01-18 00:01:24.266 11928-11928/dylanhedger.yttest E/InputEventSender:
  Exception dispatching finished signal. 01-18 00:01:24.267
  11928-11928/dylanhedger.yttest E/MessageQueue-JNI: Exception in
  MessageQueue callback: handleReceiveCallback 01-18 00:01:24.373
  11928-11928/dylanhedger.yttest E/MessageQueue-JNI:
  android.os.NetworkOnMainThreadException
                                                                                at
  android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
                                                                                at
  java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
                                                                                at
  java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
                                                                                at java.net.InetAddress.getAllByName(InetAddress.java:787)
                                                                                at com.android.okhttp.Dns$1.lookup(Dns.java:39)
                                                                                at
  com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
                                                                                at
  com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
                                                                                at
  com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
                                                                                at
  com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
                                                                                at
  com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
                                                                                at
  com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
                                                                                at
  com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
                                                                                at
  com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
                                                                                at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
                                                                                at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
                                                                                at
  com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
                                                                                at
  com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(Unknown
  Source:0)
                                                                                at
  com.android.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.connect(TrackedHttpURLConnection.java:128)
                                                                                at
  com.android.tools.profiler.support.network.httpurl.HttpsURLConnection$.connect(HttpsURLConnection$.java:366)
                                                                                at
  com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:104)
                                                                                at
  com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
                                                                                at
  com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
                                                                                at
  com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
                                                                                at
  com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
                                                                                at
  dylanhedger.yttest.MainActivity$1.onQueryTextSubmit(MainActivity.java:79)
                                                                                at android.widget.SearchView.onSubmitQuery(SearchView.java:1259)
                                                                                at android.widget.SearchView.-wrap8(Unknown Source:0)
                                                                                at android.widget.SearchView$5.onEditorAction(SearchView.java:1236)
                                                                                at android.widget.TextView.doKeyDown(TextView.java:7226)
                                                                                at android.widget.TextView.onKeyDown(TextView.java:7095)
                                                                                at
  android.widget.AutoCompleteTextView.onKeyDown(AutoCompleteTextView.java:831)
                                                                                at android.view.KeyEvent.dispatch(KeyEvent.java:2691)
                                                                                at android.view.View.dispatchKeyEvent(View.java:11713)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at
  com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:440)
                                                                                at
  com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1819)
                                                                                at android.app.Activity.dispatchKeyEvent(Activity.java:3267)
                                                                                at
  android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:534)
                                                                                at
  android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:58)
                                                                                at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindow
  01-18 00:01:24.373 11928-11928/dylanhedger.yttest D/AndroidRuntime:
  Shutting down VM 01-18 00:01:24.417 11928-11928/dylanhedger.yttest
  E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: dylanhedger.yttest, PID: 11928
                                                                                android.os.NetworkOnMainThreadException
                                                                                at
  android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
                                                                                at
  java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
                                                                                at
  java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
                                                                                at java.net.InetAddress.getAllByName(InetAddress.java:787)
                                                                                at com.android.okhttp.Dns$1.lookup(Dns.java:39)
                                                                                at
  com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
                                                                                at
  com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
                                                                                at
  com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
                                                                                at
  com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
                                                                                at
  com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
                                                                                at
  com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
                                                                                at
  com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
                                                                                at
  com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
                                                                                at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
                                                                                at
  com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
                                                                                at
  com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
                                                                                at
  com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(Unknown
  Source:0)
                                                                                at
  com.android.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.connect(TrackedHttpURLConnection.java:128)
                                                                                at
  com.android.tools.profiler.support.network.httpurl.HttpsURLConnection$.connect(HttpsURLConnection$.java:366)
                                                                                at
  com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:104)
                                                                                at
  com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
                                                                                at
  com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
                                                                                at
  com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
                                                                                at
  com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
                                                                                at
  dylanhedger.yttest.MainActivity$1.onQueryTextSubmit(MainActivity.java:79)
                                                                                at android.widget.SearchView.onSubmitQuery(SearchView.java:1259)
                                                                                at android.widget.SearchView.-wrap8(Unknown Source:0)
                                                                                at android.widget.SearchView$5.onEditorAction(SearchView.java:1236)
                                                                                at android.widget.TextView.doKeyDown(TextView.java:7226)
                                                                                at android.widget.TextView.onKeyDown(TextView.java:7095)
                                                                                at
  android.widget.AutoCompleteTextView.onKeyDown(AutoCompleteTextView.java:831)
                                                                                at android.view.KeyEvent.dispatch(KeyEvent.java:2691)
                                                                                at android.view.View.dispatchKeyEvent(View.java:11713)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1834)
                                                                                at
  com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:440)
                                                                                at
  com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1819)
                                                                                at android.app.Activity.dispatchKeyEvent(Activity.java:3267)
                                                                                at
  android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:534)
  01-18 00:01:24.447 11928-11928/dylanhedger.yttest E/AndroidRuntime:
  at
  android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:58)
                                                                                at
  android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.dispatchKeyEvent(AppCompatDelegateImplBase.java:316)
                                                                                at
  com.android.tools.profiler.support.event.WindowProfilerCallback.dispatchKeyEvent(WindowProfilerCallback.java:52)
                                                                                at
  com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:354)
                                                                                at
  android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4733)
                                                                                at
  android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4605)
                                                                                at
  android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
                                                                                at
  android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
                                                                                at
  android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
                                                                                at
  android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4293)
                                                                                at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
                                                                                at
  android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4350)
                                                                                at
  android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
                                                                                at
  android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
                                                                                at
  android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
                                                                                at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4174)
                                                                                at
  android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4147)
                                                                                at
  android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4200)
                                                                                at
  android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4166)
                                                                                at
  android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4326)
                                                                                at
  android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4487)
                                                                                at
  android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2435)
                                                                                at
  android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1998)
                                                                                at
  android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1989)
                                                                                at
  android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2412)
                                                                                at
  android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
                                                                                at android.os.MessageQueue.nativePollOnce(Native Method)
                                                                                at android.os.MessageQueue.next(MessageQueue.java:325)
                                                                                at android.os.Looper.loop(Looper.java:142)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

A: I found out everything from a blog and it helped a lot so if anyone else has this problem just read the blog
https://ravinishad.blogspot.com.au/2014/10/video-search-in-android-using-youtube.html?showComment=1516382560722#c4197926916525561564
At the bottom, he shows the source code but in case you don't see it here's the GitHub link
https://github.com/Keshava11/LatentLoader


text:
Q: Table storage key as a message into the Azure queue I'm able to insert the rowkey and partition key into Azure table storage:

TableOperation insertOperation = TableOperation.Insert(customer1);
  table.Execute(insertOperation);
  StoreKeyInQ(insertOperation);

// Create a new customer entity.
        CustomerEntity customer1 = new CustomerEntity("URL", "Name"+Guid.NewGuid());
        customer1.path = fullpath;

The "CustomerEntity" is as below:
public class CustomerEntity : TableEntity
    {
        public CustomerEntity(string ID, string Name)
        {
            this.PartitionKey = ID;
            this.RowKey = Name;
        }

        public CustomerEntity() { }

        public string path { get; set; }

    }

I have written code to create a queue as below:
 public void StoreKeyInQ(TableOperation insertOperation)
    {
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
        //craete a queue client
        CloudQueueClient cloudQueueClient = storageAccount.CreateCloudQueueClient();
        //retrive a reference to a container
        CloudQueue cloudQueue = cloudQueueClient.GetQueueReference("myqueue");
        //create the queue if does not exists
        cloudQueue.CreateIfNotExists();

       // Create a message and add it to the queue.
       CloudQueueMessage message = new CloudQueueMessage(insertOperation); //Here is the error as "CloudQueueMessage" can't take a argument type "TableOperation"
       queue.AddMessage(message);
    }

How to resolve this error? How to pass both "rowkey" and "partition" key of table storage into a Queue?
  EDIT:

I have added these two lines for serialization is this OK?
 System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(customerEntity.GetType());
        CloudQueueMessage message = new CloudQueueMessage(x.ToString());

My queue is showing like this; however, not sure if this is correct or not? Can anyone please clarify- Is this correct?

A:
How to resolve this error?

If we want to insert the message in to the queue. We could get the operation queue
code demo from Get started with Azure Queue storage using .NET
// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
    CloudConfigurationManager.GetSetting("StorageConnectionString"));

// Create the queue client.
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();

// Retrieve a reference to a queue.
CloudQueue queue = queueClient.GetQueueReference("myqueue");

// Create the queue if it doesn't already exist.
queue.CreateIfNotExists();

// Create a message and add it to the queue.
CloudQueueMessage message = new CloudQueueMessage("RowKey, PartitionKey ");
queue.AddMessage(message);

How to pass both "rowkey" and "partition" key of table storage into a Queue?

You could serialise your model as string and then save that as a message or you could use your customize format to save the message such as message format: RowKey, PartitionKey

Basically idea is to store both RowKey+PartitionKey in the queue and create a worker role to retrieve the key (RowKey+PartitionKey ) from the Queue.

If you just want to retrieve queue message, there are many  cheap ways we could use, such as Webjob queue trigger or azure function queue trigger.
Update:
Please have a try to use the following code.
using Newtonsoft.Json;
CloudQueueMessage message = new CloudQueueMessage(JsonConvert.SerializeObject(customer1));
cloudQueue.AddMessage(message);

For more demo code please refer to SerializeObject or Deserialize an Object.


text:
Q: protractor, loop of elements I'm new in Protractor. I'm doing automated tests and in my feature file I have this to check:
When('there are at least two ports loaded', function (next) { }

In my html I have this:

      <picture> (...) </picture>

I'm trying to doing a loop to check this, but maybe I really don't understand how:
let port_element = element.all(by.css('port-element '));
      port_element.each(function (item) {
        console.log('Port element count: ', item);
      });
      next();

but I don't understand how.
Under advice I used this on my stepdefinition:
let count = await element.all(by.css('.port-element')).count();
for(let i=1;i<=count;i++)
{
  let selector = 'div.port-element div.image-loader:nth-child('+i+')');
  //selector is the element within each div to now check
}

and
expect(element.all(by.css('div.port-item div.image-loader')).count()).to.be.above(2)
but I have this error now:
AssertionError: expected ManagedPromise::4833 {[[PromiseStatus]]: "pending"} to be a number or a date

Now I tried to do like this:
let img_loader_count = element.all(by.css('div.port-element div.image-loader'));
    console.log('img loader count: ', img_loader_count.count());

but I have this on console:
img loader count: 0
There are 12 img loader count, so this is impossible. Why on console it prints 0?
Can someone help me?
Thank you.

A: You can use count() to check how many classes are loaded in the current page.
I have done some minor changes to your code, Hope it'll help you.
    let port_element = element.all(by.css('.port-element'));
        expect(port_element.count()).toBe(2);

A: The only way I have seen to do this is using the element.count() to be the index for a loop such as:
let count = await element.all(by.css('.port-element')).count();
for(let i=1;i<=count;i++)
{
  let selector = 'div.port-element div.image-loader:nth-child('+i+')');
  //selector is the element within each div to now check
}

However, if you are only trying to check that there are a certain number of images that are within the port element, then you can do
expect(element.all(by.css('div.port-element div.image-loader').count()).toBe(2);

Per question edit:
You should be using expect() instead of console.log(). The asynchronous nature of js can cause weird things to happen when you are trying to log variables like that since it isn't wrapped in a promise. Using expect(img_loader_count.count()).toBe(12); should give you the your expected result. If you need to use console.log() for whatever reason, you have to properly queue it like:
element.all(by.css('div.port-element div.image-loader').count().then(function(value){
  console.log('The count is: '+value);
});

Here is the documentation for some of the promise stuff.


text:
Q: Expand an array to columns in spark with structured streaming I have this problem:
I'm reading the data from Kafka using structured streaming, data are CSV rows. When I get the data from Kafka, I have a streaming dataframe where the CSV row is inside "value" and it's a byte sequence.
 sDF2 = sDF.selectExpr("CAST(value as string)").select( split("value",","))

using this I have a new dataframe where "value" is a string and it is the CSV row.
How can I get a new dataframe where I have parsed and split the CSV fields into dataframe columns?
Example:
    csv row is "abcd,123,frgh,1321"
sDF schema, which contains the data downloaded from Kafka, is
key, value, topic, timestamp etc... and here value is a byte sequence with no type

sDF2.schema has only a column ( named value of type string )

I like that the new dataframe is
sDF3.col1 = abcd
sDF3.col2 = 123
sDF3.col3 = frgh ...etc

where all the columns are String.
I still can do this:
 sDF3 = sDF2.select( sDF2.csv[0].alias("EventId").cast("string"),
 sDF2.csv[1].alias("DOEntitlementId").cast("string"),
 sDF2.csv[3].alias("AmazonSubscriptionId").cast("string"),
 sDF2.csv[4].alias("AmazonPlanId").cast("string"),
 ... etc ...

but it looks ugly.

A: I have not tried it, but something like this should work.
sDF2 =
      sDF.selectExpr("CAST(value as string)")
       .alias("csv").select("csv.*")
       .select("split(value,',')[0] as DOEntitlementId",
               "split(value,',')[1] as AmazonSubscriptionId",
               "split(value,',')[2] as AmazonPlanId")


text:
Q: React Native : clean Useeffect I ma facing this issue
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
  useEffect(() => {

    firebase.auth().onAuthStateChanged((user) => {
      if (user !== null) {
        return firebase
          .firestore()
          .collection("users")
          .doc(user.uid)
          .get()
          .then((documentSnapshot) => {
            if (documentSnapshot.exists) {
              setUserData(documentSnapshot.data());
              setisloadingComplet(true);
            }
          });
      }
    });

  }, []);

when ever the user update his info . It does not update immediately until I refresh the app . and it throws me the warning above

A: thank you guys . I solved this .
the problem is that I get the data from both profile and homescreen.
what I did is removed getting the data from profile screen.
instead I got the user Data only from homescreen then pass it to profile screen via navigation.


text:
Q: Relations between monoids and modules? What is the relation between monoids and modules? Are they completely different algebraic structures, or is there a kind of inclusion relation like "elements of a module are also elements of a monoid"?

A: A module is an abelian group.  (It's more useful to think of a module as the analog of a vector space, but with the set of scalars coming from a ring instead of a field.  Usually, one arrives at this notion of a module in terms of "the action of a ring on a set" where the set is a module.)
A monoid is a relaxation of the definition of a group.  A monoid has an associative operation and a neutral element, but makes no promises about inverses.
I don't see how to express any more of a relation than "all modules are monoids" but only for the dull reason that all (abelian) groups are (abelian) monoids with the added constraint that every element has an inverse.

A: There is a chain  of forgetful functors which progressively forgets the various operations in the structure: $$\mathrm{Mod_R}\to\mathrm{Ab}\to\mathrm{AbMon}\to\mathrm{Set}$$
The interesting thing is that you can go in the opposite direction too with free functors $$\mathrm{Set}\to\mathrm{AbMon}\to\mathrm{Ab}\to\mathrm{Mod_R}$$
Each forgetful functor $U$ is adjoint to the respective free functor $F$


text:
Q: Electron forge installation and uninstallation with msi package Thanks in advance.
I have created one electron application with msi Support using electron forge maker.
{
    "name": "@electron-forge/maker-wix",
    "config": {
        "name": "XYZ",
        "manufacturer": "XYZ",
        "appIconPath": "x.ico",
        "features":{
            "autoLaunch": true
        },
        "ui": {
            "chooseDirectory": true
        }
    }
}

Here is my wix configuration
Installation and desktop shortcut everything working fine. I am able to use the product.
I have 2 question with this regarding installation and uninstallation:

*

*After installation app I not launched automatically. I have manually launch via desktop shortcut or via window search.

*While installing the application i am getting below window[enter image description here]

(https://i.stack.imgur.com/A4kbl.png)
Is that default in electron forge maker or we can able to customize it. I want to launch the application after installation without user interaction and also I want to uninstall the application without restart or reboot machine?
Could anyone pls help on this?
I want to launch the application after installation without user interaction and also I want to uninstall the application without restart or reboot machine?


text:
Q: Creating a file within a folder then writing to that file with SSH I am trying to use write a script that uses SSH to create a new directory and write to a text file in it. I've got 1 master on a network, and then 3 nodes that I want to create the directory on. These 4 machines are hosted on VMware.
#node1
ssh node1@192.168.1.102 'sudo touch /temp_dirname/host.txt'
ssh node1@192.168.1.102 'echo "node1" | sudo tee /temp_dirname/host.txt'

#node2
ssh node1@192.168.1.103 'sudo touch /temp_dirname/host.txt'
ssh node1@192.168.1.103 'echo "node1" | sudo tee /temp_dirname/host.txt'

#node3
ssh node3@192.168.1.104 'sudo touch /temp_dirname/host.txt'
ssh node3@192.168.1.104 'echo "node1" | sudo tee /temp_dirname/host.txt'

When I run this I get different errors for each node... for nodes 1 and 2 I get
touch: cannot touch '/temp_dirname/host.txt': no such file or directory

and
tee: temp_dirname/host.txt: no such file or directory

and node 3 I get:
touch: setting times of '/temp_dirname/ no such file or directory

and
tee: temp_dirname/host.txt: no such file or directory

I am absolutely confused with this as I thought touch created files - so why is it no such file or directory.

A: If /temp_dirname doesn't exist, you can create it with mkdir -p /temp_dirname.
-p works with any arbitrary depth, creating directories as required.


text:
Q: Golang template.ParseFiles "not a directory" error I'm trying to render just one template:
root_path, err := osext.Executable()
if err != nil {
    return err
}
template_path := root_path + "/app/views/mailtemplates/" + "feedback.html"

fmt.Println(exist(template_path))

tmpl, err := template.ParseFiles(template_path)
if err != nil {
    return err
}

but I have the error not a directory.
My exist function:
func exist(file_path string) bool {
    if _, err := os.Stat(file_path); os.IsNotExist(err) {
        return false
    }

    return true
}

it returns true. What's the problem with template.ParseFiles? I see documentation and where written that arguments are filenames and There must be at least one file. What I doing wrong?
EDITED:
My variables:
root_path: /home/cnaize/Dropbox/develop/gocode/bin/advorts
template_path: /home/cnaize/Dropbox/develop/gocode/bin/advorts/app/views/mailtemplates/feedback.html

My file's content:
<html>
    <head>
    </head>
    <body>
        Hello, World!
    </body>
</html>

EDITED 2: I've moved all my projects, libs and etc to /home/cnaize/gocode and now I have error:
open /home/cnaize/gocode/bin/advorts/app/views/mailtemplates/feedback.txt: not a directory

Is it Revel's problem? What I supposed to do? I've tried to remove this bin file, didn't helped.

A: The actual issue was a path within the Dropbox/ folder: consider it is synchronized/managed by an external process (dropbox), the ability to access the file isn't always reliable.
Putting the file outside of that Dropbox path would solve the issue.


text: Q: Is mv faster with --no-clobber? I am about to move a lot of data from one place to another for a second time, because the first time I had no access to some subdirectories and files. I am not sure wheter the -n/--no-clobber argument will do what I want and if it wouldn't be better to just use -f/--force instead. Is mv faster with -n?


text:
Q: Can we use MongoDB with ORMs we used to use with relational databases, such as linq2sql, entity framework, subsonic,...? I want to know if its possible based on your experience to use our previous experiences using .net ORMs with nosql db such as MongoDB.
And also if you know samples doing this please refer in your answer.

A: You can reuse your LINQ skills because the two providers between .net and MongoDB support LINQ. Both the norm driver and the mongodb-csharp-driver support LINQ queries.
See http://www.mongodb.org/display/DOCS/C+Sharp+Language+Center
Mapping an object to a document is most of the time easier than mapping an object to a set of tables. But you can't reuse all your previous experiences because a document db and a relational db are very different. But isn't it fun to explore a new "world"?


text:
Q: ContrainstLayout not filling the Screensize in Android App I'm having some trouble adding Textview to my ContraintLayout. When i use 3 or 4 EditText with this configuration there is no problem and the elements fit well in the screen, but when i add more EditText the UI collapse and all the elements keep close from each other.

But with less elements look like this:

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.auth.RegisterFragment"
android:background="#fff">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:padding="16dp">

        <TextView
            android:id="@+id/register_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/input_nombre_layout"
            android:textSize="25sp"
            android:textColor="#000"
            android:text="@string/register"
            android:layout_marginTop="30dp"/>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_nombre_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/register_text"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/input_apellidos_layout"
            android:layout_marginTop="30dp"
            >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/input_nombre"
                android:textColor="#000"
                android:hint="@string/nombre"
                android:inputType="textEmailAddress"
                />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_apellidos_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/input_nombre_layout"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/input_email_layout"
            >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/input_apellidos"
                android:textColor="#000"
                android:hint="@string/apellidos"
                android:inputType="text"
                />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_email_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/input_apellidos_layout"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/input_password_layout"
            >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/input_email"
                android:textColor="#000"
                android:hint="@string/email"
                android:inputType="text"
                />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_password_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/email_input_layout"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/input_password_confirm_layout"
            >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/input_password"
                android:textColor="#000"
                android:hint="@string/field_password"
                android:inputType="textPassword"
                />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/input_password_layout"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/btn_register_register"
            android:id="@+id/input_password_confirm_layout"
            >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/input_password_confirm"
                android:textColor="#000"
                android:hint="@string/field_confirm_password"
                android:inputType="textPassword"
                />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_numero_doc_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/input_password_confirm_layout"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/input_telefono_layout"
            >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/input_numero_doc"
                android:textColor="#000"
                android:hint="@string/numero_doc"
                android:inputType="text"
                />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_telefono_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toBottomOf="@+id/input_numero_doc_layout"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/btn_register_register"
            >

            <EditText
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/input_telefono"
                android:textColor="#000"
                android:hint="@string/telefono"
                android:inputType="text"
                />

        </com.google.android.material.textfield.TextInputLayout>

        <Button
            android:id="@+id/btn_register_register"
            android:layout_width="0dp"
            android:layout_height="55dp"
            app:layout_constraintTop_toBottomOf="@+id/input_numero_doc_layout"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            android:background="@android:color/black"
            android:text="@string/terminar"
            android:textAllCaps="false"
            android:textColor="#fff"
            android:textSize="16sp"
            android:layout_marginTop="50dp"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>

I suppose the error it has something to do with the ScrollView not filling all the screen, but im not sure how to fix it.

A: it looks like you have not referenced the id properly
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/input_email_layout" // this one
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    .....

while the password field references difference id
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/input_password_layout"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toBottomOf="@+id/email_input_layout" // this one
    .....

and I think it'd be nicer if you delete this constraint and make margin bottom instead
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/input_apellidos_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintBottom_toTopOf="@+id/email_input_layout"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/input_nombre_layout"> // delete this line and replace with margin bottom

and do the same for the others

A: If you want to arrange layout like linear layout with ConstrainLayout, don't
constrain both top and bottom. Choose one enough.
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp">

        <TextView
            android:id="@+id/register_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            android:text="register"
            android:textColor="#000"
            android:textSize="25sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_nombre_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="30dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/register_text">

            <EditText
                android:id="@+id/input_nombre"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="nombre"
                android:inputType="textEmailAddress"
                android:textColor="#000" />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_apellidos_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/input_nombre_layout">

            <EditText
                android:id="@+id/input_apellidos"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="apellidos"
                android:inputType="text"
                android:textColor="#000" />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_email_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/input_apellidos_layout">

            <EditText
                android:id="@+id/input_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="email"
                android:inputType="text"
                android:textColor="#000" />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_password_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/input_email_layout">

            <EditText
                android:id="@+id/input_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="field_password"
                android:inputType="textPassword"
                android:textColor="#000" />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_password_confirm_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/input_password_layout">

            <EditText
                android:id="@+id/input_password_confirm"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="field_confirm_password"
                android:inputType="textPassword"
                android:textColor="#000" />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_numero_doc_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/input_password_confirm_layout">

            <EditText
                android:id="@+id/input_numero_doc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="numero_doc"
                android:inputType="text"
                android:textColor="#000" />

        </com.google.android.material.textfield.TextInputLayout>

        <com.google.android.material.textfield.TextInputLayout
            android:id="@+id/input_telefono_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/input_numero_doc_layout">

            <EditText
                android:id="@+id/input_telefono"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="telefono"
                android:inputType="text"
                android:textColor="#000" />

        </com.google.android.material.textfield.TextInputLayout>

        <Button
            android:id="@+id/btn_register_register"
            android:layout_width="0dp"
            android:layout_height="55dp"
            android:layout_marginTop="50dp"
            android:background="@android:color/black"
            android:text="terminar"
            android:textAllCaps="false"
            android:textColor="#fff"
            android:textSize="16sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/input_telefono_layout" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>


text:
Q: When to stop the chain of priors in Bayesian hierarchical models? From Wkipedia's article on hyperprior:

In Bayesian statistics, a hyperprior is a prior distribution on a hyperparameter, that is, on a parameter of a prior distribution.

There will be some parameters for the hyperprior and there is nothing stopping us from defining prior distribution on these parameters too. Practical considerations stop us from doing this inductive step too many times.
Q1. Is there any theoretical result showing that the effect of these hyperpriors diminishes as we keep on defining them?
Q2. Is there a more principled way (than computational and practical considerations) to decide when to stop this chain of priors?


text:
Q: Generalizations of Poisson's Equation I'm currently reading a book in Multivariable Calculus, and there is a section on Applications of Calculus to Physics - Poisson's Equation. It states the following:
We have the 3D version: Let $$u(x) = \iiint_{\Bbb{R}^3}\frac{p(x+y)}{|y|}d^3y$$, where $p$ is a $C^2$ function on $\mathbb{R}^3$, that vanished outside a bounded set. Then $u$ is of class $C^2$ and $\nabla^2u = -4\pi p$.
The 2D analog: Let $u(x) = \int p(x+y)\log{|y|}d^2y$, where $p$ is a $C^2$ function on $\mathbb{R}^2$, that vanished outside a bounded set. Then $u$ is of class $C^2$ and $\nabla^2u = 2\pi p$.
I was wondering how we could generalize this to 4 dimensions - or even n dimensions (if its possible).
My conjecture for the 4D version is: Let $$u(x) = \iiiint_{\Bbb{R}^4}\frac{p(x+y)}{|y|^2}d^4y$$, where $p$ is a $C^2$ function on $\mathbb{R}^4$, that vanished outside a bounded set. Then $u$ is of class $C^2$ and $\nabla^2u = -4\pi^2 p$.
Is this conjecture correct? If not, what would the correct analog be, and if so, how could we prove it?

A: In THIS ANSWER, I developed the Green (or Green's if you prefer) function, $G(\vec x|\vec y)$ for the $n$-dimensional Inhomogeneous Helmholtz equation,
$$\nabla^2 G_k(\vec x|\vec y)+k^2 G_k(\vec x|\vec y)=-\delta (\vec x-\vec y)\tag1$$
where $\delta(\vec x)$ is the Dirac Delta.  Solution to $(1)$ can be written
$$G_k(\vec x|\vec y)=\frac i4 \left(\frac{k}{2\pi |\vec x-\vec y|}\right)^{n/2-1}H_{n/2-1}^{(1)}(k|\vec x-\vec y|)\tag2$$
where $H^{(1)}_{\alpha}(z)$ is the Hankel function of the first kind and order $\alpha$.
Using the same approach for the case $k=0$, we find the Green function for Poisson's equation, $\nabla^2 G_0(\vec x|\vec y)=-\delta(\vec x-\vec y)$ is given by
$$G_0(\vec x|\vec y)=\frac{\Gamma(n/2-1)}{4\pi^{n/2}|\vec x-\vec y|^{n-2}}\tag3$$

ASIDE DISCUSSION:
We could have arrived at $(2)$ by taking the limit as $k\to 0$ of $(2)$.  To do so, we use the small argument (i.e., small $k|\vec r-\vec r'|$) approximation for the Hankel function of the first kind and order $n/2-1$, $n>2$, which is given by
$$H_{n/2-1}^{(1)}(k|\vec r-\vec r'|) = -i\frac{\Gamma(n/2-1)}{\pi} \left(\frac2{k|\vec r-\vec r'|}\right)^{n/2-1}+O(k^{n/2-1})\tag{A1}$$
Using $(A1)$ in $(2)$, we find that the small argument approximation for $G_k(\vec x|\vec y)$ for $n>2$ is given by
$$G_k(\vec x|\vec y)=\frac{\Gamma(n/2-1)}{4\pi^{n/2}|\vec x-\vec y|^{n-2}}+O(k^{n-2})\tag {A2}$$
If we let $k\to 0$ in $(A2)$, we see that solution to the $n$-dimensional Poisson Equation $\Delta G_0(\vec x|\vec y)=-\delta(\vec x-\vec y)$ is
$$G_0(\vec x|\vec y)=\frac{\Gamma(n/2-1)}{4\pi^{n/2}|\vec x-\vec y|^{n-2}}$$

Using $(3)$, we find the solution to Poisson's equation $\nabla^2 u(\vec x)=p(\vec x)$ can be written as
$$\begin{align}
u(\vec x)&=\int_{\mathbb{R}^n}p(\vec y)G(\vec x|\vec y)\,d^n\vec y\\\\
&=\int_{\mathbb{R}^n}p(\vec y)\frac{\Gamma(n/2-1)}{4\pi^{n/2}|\vec x-\vec y|^{n-2}} \,d^n\vec y\\\\
&=\int_{\mathbb{R}^n}p(\vec x+\vec y)\frac{\Gamma(n/2-1)}{4\pi^{n/2}|\vec y|^{n-2}} \,d^n\vec y
\end{align}$$

EXAMPLES:
Example $1$ ($n=3$):
For $n=3$, $\Gamma(n/2-1)=\pi^{1/2}$ and $G_0(\vec x|\vec y)=\frac{1}{4\pi |\vec x-\vec y|}$ is the familiar Green function and we have
$$\begin{align}
u(\vec x)&=\int_{\mathbb{R}^3}\frac{p(\vec y)}{4\pi |\vec x-\vec y|}\,d^3\vec y\\\\
&=\int_{\mathbb{R}^3}\frac{p(\vec x+\vec y)}{4\pi |\vec y|}\,d^3\vec y
\end{align}$$

Example $2$ ($n=4$):
For $n=4$, $\Gamma(n/2-1)=1$ and $G_0(\vec x|\vec y)=\frac{1}{4\pi^2 |\vec x-\vec y|^2}$ we have
$$\begin{align}
u(\vec x)&=\int_{\mathbb{R}^4}\frac{p(\vec y)}{4\pi^2 |\vec x-\vec y|^2}\,d^4\vec y\\\\
&=\int_{\mathbb{R}^4}\frac{p(\vec x+\vec y)}{4\pi^2 |\vec y|^2}\,d^4\vec y
\end{align}$$

Example $3$ ($n=5$):
For $n=5$, $\Gamma(n/2-1)=\sqrt\pi/2$ and $G_0(\vec x|\vec y)=\frac{1}{4\pi^2 |\vec x-\vec y|^2}$ we have
$$\begin{align}
u(\vec x)&=\int_{\mathbb{R}^4}\frac{p(\vec y)}{8\pi^2 |\vec x-\vec y|^3}\,d^5\vec y\\\\
&=\int_{\mathbb{R}^4}\frac{p(\vec x+\vec y)}{8\pi^2 |\vec y|^3}\,d^5\vec y
\end{align}$$

A: The $n$-dimensional version (for $n \ge 2$) is that
$$
u(x)=\int_{\mathbb{R}^n} p(x+y) \, R(|y|) \, dy
$$
satisfies $\nabla^2 u = p$ if the function $R(r)$ is such that $1/R'(r)$ equals the $(n-1)$-dimensional surface area of the sphere with radius $r$ in $\mathbb{R}^n$. That is,
$$
R'(r) = \frac{1}{A_n r^{n-1}}
,
$$
where $A_n = 2 \pi^{n/2} \, / \, \Gamma(n/2)$ is the area of the unit sphere in $\mathbb{R}^n$ (see this question, for example).
(I won't prove this here, but the phrase to search for if you want to learn more is the fundamental solution for the Laplace operator.)
For the exceptional case $n=2$, this gives $R'(r)=\frac{1}{2\pi r}$ so that $R(r)=\frac{1}{2\pi} \ln r$ (plus a constant, which is conventionally taken to be zero).
For $n \ge 3$, we get instead
$$
R(r) = \frac{-1}{(n-2) A_n r^{n-2}}
$$
(plus a constant, which is conventionally taken to be zero).
So your conjecture for $n=4$ is correct, since we indeed have $(n-2)A_n = 2 A_4 = 2 \cdot 2 \pi^2 = 4 \pi^2$.