text:
Q: Handeling SSL Client not reading all data I am trying to accomplish, that my ssl server does not break down, when a client does not collect all data.  (fixed with one minor bug)
when the data is too long.
Basically what I'm trying to do is write in a non-blocking way. For that I found two different approaches:
First approach
using this code
int flags = fcntl(ret.fdsock, F_GETFL, 0);
fcntl(ret.fdsock, F_SETFL, flags | O_NONBLOCK);

and creating the ssl connection with it
Second approach:
Doing this directly after creating the SSL Object using SSL_new(ctx)
BIO *sock = BIO_new_socket(ret.fdsock, BIO_NOCLOSE);
BIO_set_nbio(sock, 1);
SSL_set_bio(client, sock, sock);

Both of which have their downsides, but neither of which helps solving the problem.
The first approach seems to read in a unblocking way just fine, but when I write more data, than the client reads, my server crashes.
The second approach does not seem to do anything, so my guess is, that I did something wrong or did not understand what a BIO actually does.
For more Information here is how the server writes to the client:
int SSLConnection::send(char* msg, const int size){
    int rest_size = size;
    int bytes_sent = 0;
    char* begin = msg;
    std::cout << "expected bytes to send: " << size << std::endl;
    while(rest_size > 0) {
        int tmp_bytes_sent = SSL_write(connection, begin, rest_size);
        std::cout << "any error     : " << ERR_get_error()<< std::endl;
        std::cout << "tmp_bytes_sent: " << tmp_bytes_sent << std::endl;
        if (tmp_bytes_sent < 0){
            std::cout << tmp_bytes_sent << std::endl;
            std::cout << "ssl error     : " << SSL_get_error(this->connection, tmp_bytes_sent)<< std::endl;
        } else {
            bytes_sent += tmp_bytes_sent;
            rest_size -= tmp_bytes_sent;
            begin = msg+bytes_sent;
        }
    }
    return bytes_sent;
}

Output:
expected bytes to send: 78888890
Betätigen Sie die <RETURN> Taste, um das Fenster zu schließen...
(means: hit <return> to close window)

EDIT: After people said, that I need to cache errors appropriate, here is my new code:
Setup:
connection = SSL_new(ctx);
if (connection){
    BIO * sbio = BIO_new_socket(ret.fdsock, BIO_NOCLOSE);
    if (sbio) {
        BIO_set_nbio(sbio, false);
        SSL_set_bio(connection, sbio, sbio);
        SSL_set_accept_state(connection);
    } else {
        std::cout << "Bio is null" << std::endl;
    }
} else {
    std::cout << "client is null" << std::endl;
}

Sending:
int SSLConnection::send(char* msg, const int size){
    if(connection == NULL) {
        std::cout << "ERR: Connection is NULL" << std::endl;
        return -1;
    }
    int rest_size = size;
    int bytes_sent = 0;
    char* begin = msg;
    std::cout << "expected bytes to send: " << size << std::endl;
    while(rest_size > 0) {
        int tmp_bytes_sent = SSL_write(connection, begin, rest_size);
        std::cout << "any error     : " << ERR_get_error()<< std::endl;
        std::cout << "tmp_bytes_sent: " << tmp_bytes_sent << std::endl;
        if (tmp_bytes_sent < 0){
            std::cout << tmp_bytes_sent << std::endl;
            std::cout << "ssl error     : " << SSL_get_error(this->connection, tmp_bytes_sent)<< std::endl;
            break;
        } else if (tmp_bytes_sent == 0){
            std::cout << "tmp_bytes are 0" << std::endl;
            break;
        } else {
            bytes_sent += tmp_bytes_sent;
            rest_size -= tmp_bytes_sent;
            begin = msg+bytes_sent;
        }
    }

    return bytes_sent;
}

Using a client, that fetches 60 bytes, here is the output:
Output writing 1,000,000 Bytes:
expected bytes to send: 1000000
any error     : 0
tmp_bytes_sent: 16384
any error     : 0
tmp_bytes_sent: 16384
Betätigen Sie die <RETURN> Taste, um das Fenster zu schließen...
(translates to: hit <RETURN> to close window)

Output writing 1,000 bytes:
expected bytes to send: 1000
any error     : 0
tmp_bytes_sent: 1000
connection closed  <- expected output

A: First, a warning:  non-blocking I/O over SSL is a rather baroque API, and it's difficult to use correctly.  In particular, the SSL layer sometimes needs to read internal data before it can write user data (or vice versa), and the caller's code is expected to be able to handle that based on the error-codes feedback it gets from the SSL calls it makes.  It can be made to work correctly, but it's not easy or obvious -- you are de facto required to implement a state machine in your code that echoes the state machine inside the SSL library.
Below is a simplified version of the logic that is required (it's extracted from the Write() method in this file which is part of this library, in case you want to see a complete, working implementation)
enum {
   SSL_STATE_READ_WANTS_READABLE_SOCKET   = 0x01,
   SSL_STATE_READ_WANTS_WRITEABLE_SOCKET  = 0x02,
   SSL_STATE_WRITE_WANTS_READABLE_SOCKET  = 0x04,
   SSL_STATE_WRITE_WANTS_WRITEABLE_SOCKET = 0x08
};

// a bit-chord of SSL_STATE_* bits to keep track of what
// the SSL layer needs us to do next before it can make more progress
uint32_t _sslState = 0;

// Note that this method returns the number of bytes sent, or -1
// if there was a fatal error.  So if this method returns 0 that just
// means that this function was not able to send any bytes at this time.
int32_t SSLSocketDataIO :: Write(const void *buffer, uint32 size)
{
   int32_t bytes = SSL_write(_ssl, buffer, size);
   if (bytes > 0)
   {
      // SSL was able to send some bytes, so clear the relevant SSL-state-flags
      _sslState &= ~(SSL_STATE_WRITE_WANTS_READABLE_SOCKET | SSL_STATE_WRITE_WANTS_WRITEABLE_SOCKET);
   }
   else if (bytes == 0)
   {
      return -1;  // the SSL connection was closed, so return failure
   }
   else
   {
      // The SSL layer's internal needs aren't being met, so we now have to
      // ask it what its problem is, then give it what it wants.  :P
      int err = SSL_get_error(_ssl, bytes);
      if (err == SSL_ERROR_WANT_READ)
      {
         // SSL can't write anything more until the socket becomes readable,
         // so we need to go back to our event loop, wait until the
         // socket select()'s as readable, and then call SSL_Write() again.
         _sslState |=  SSL_STATE_WRITE_WANTS_READABLE_SOCKET;
         _sslState &= ~SSL_STATE_WRITE_WANTS_WRITEABLE_SOCKET;
         bytes = 0;  // Tell the caller we weren't able to send anything yet
      }
      else if (err == SSL_ERROR_WANT_WRITE)
      {
         // SSL can't write anything more until the socket becomes writable,
         // so we need to go back to our event loop, wait until the
         // socket select()'s as writeable, and then call SSL_Write() again.
         _sslState &= ~SSL_STATE_WRITE_WANTS_READABLE_SOCKET;
         _sslState |=  SSL_STATE_WRITE_WANTS_WRITEABLE_SOCKET;
         bytes = 0;  // Tell the caller we weren't able to send anything yet
      }
      else
      {
         // SSL had some other problem I don't know how to deal with,
         // so just print some debug output and then return failure.
         fprintf(stderr,"SSL_write() ERROR!");
         ERR_print_errors_fp(stderr);
      }
   }
   return bytes;  // Returns the number of bytes we actually sent
}

A: I think your problem is
rest_size -= bytes_sent;
You should do rest_size -= tmp_bytes_sent;
Also
if (tmp_bytes_sent < 0){
            std::cout << tmp_bytes_sent << std::endl;
           //its an error condition
          return bytes_sent;
        }

I dont know whether this will fix the issue, but the code you pasted has the above mentioned issues

A:
When I write more data, than the client reads, my server crashes.

No it doesn't, unless you've violently miscoded something else that you haven't posted here. It either loops forever or it gets an error: probably ECONNRESET, which means the client has behaved as you described, and you've detected it, so you should close the connection and forget about him. Instead of which, you are just looping forever, trying to send the data to a broken connection, which can never happen.
And when you get an error, there's not much use in just printing a -1. You should print the error, with perror() or errno or strerror().
Speaking of looping forever, don't loop like this. SSL_write() can  return 0, which you aren't handling at all: this will cause an infinite loop. See also David Schwartz's comments below.
NB you should definitely use the second approach. OpenSSL needs to know that the socket is in non-blocking mode.

Both of which have their downsides

Such as?
And as noted in the other answer,
rest_size -= bytes_sent;

should be
rest_size -= tmp_bytes_sent;


text:
Q: How to display snackbar infinite duration in flutter? I created flutter project in android studio and tried to show snackbar infinite duration.This is my code
 final snackBar = SnackBar(
    content: Text('Cart:'+countProducts.toString()+" Products($countCost:sum)",style: TextStyle(color: Colors.black),),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(topLeft:Radius.circular(22),topRight:Radius.circular(22))),
    backgroundColor: Colors.white70,
    action: SnackBarAction(
      textColor: Colors.blueAccent,
      label: "Buy",
      onPressed: () {
        // Some code to undo the change.
      },
    ),
  );

  Scaffold.of(context).showSnackBar(snackBar);

There is another button that will change snackbar text. But I do not want to it dismiss back.So how to display snackbar infinite duration in flutter

A: You can use the Duration property on the snackbar
Example
final snackBar = SnackBar(
    content: Text('Cart:'+countProducts.toString()+" Products($countCost:sum)",style: TextStyle(color: Colors.black),),
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(topLeft:Radius.circular(22),topRight:Radius.circular(22))),
    backgroundColor: Colors.white70,
    action: SnackBarAction(
      textColor: Colors.blueAccent,
      label: "Buy",
      onPressed: () {
        // Some code to undo the change.
      },
    ),
   duration: Duration(seconds: double.infinity),

//Gets problem int != double
      );
using Duration(seconds: double.infinity)
Not Sure if this is the best though.
EDIT
You can try the following instead of using double.infinity
Duration(days: 365)

Reference

*

*Duration

redpajama_set_name: RedPajamaStackExchange


text:
Q: Timer.Elapsed handler abruptly stops var checkTimer = new Timer();
checkTimer.Elapsed += (s, e) =>
{
    bool? doneIndexing = serviceConnection.GetIndexStatus();
    Log.Debug(TAG, $"Indexing status: {doneIndexing}");
    if (doneIndexing.HasValue && doneIndexing == true)
    {
        Log.Debug(TAG, "Done indexing, updating UI");
        var indexStatusView = FindViewById<TextView>(Resource.Id.indexStatusView);
        var indexProgress = FindViewById<ProgressBar>(Resource.Id.indexProgress);
        indexStatusView.Text = GetString(Resource.String.done_indexing);
        indexProgress.Visibility = ViewStates.Gone;
        checkTimer.Enabled = false;
    }
};
checkTimer.Interval = 100;
checkTimer.Enabled = true;

Execution stops at indexStatusView.Text = GetString(Resource.String.done_indexing). It does get called a few times more when doneIndexing == true, but even if I move the disable line to the top, execution still stops at that same line. What could cause this?

A:
Execution stops at indexStatusView.Text .....

Perform your UI updates on the UI thread, ie:
if (doneIndexing.HasValue && doneIndexing == true)
{
    var indexStatusView = FindViewById<TextView>(Resource.Id.indexStatusView);
    var indexProgress = FindViewById<ProgressBar>(Resource.Id.indexProgress);
    Log.Debug(TAG, "Done indexing, updating UI");
    RunOnUiThread(() =>
    {
        indexStatusView.Text = GetString(Resource.String.done_indexing);
        indexProgress.Visibility = ViewStates.Gone;
    });
    checkTimer.Enabled = false;
}

A: I just looked up this timer and my best guess is that you have an Exception that is swallwoed. Apparently this Timer uses heavy Multithreading. It is even possible for multiple Elapsed Events to run in parlell on different pool threads.
Unfortuantley Multithreading is notriously good at swallowing Exceptions. And this one seems to have no abiltiy to avoid this or expose the Exceptions: https://developer.xamarin.com/api/event/System.Timers.Timer.Elapsed/
"If the Timer.SynchronizingObject property is null, the Timer.Elapsed event is raised on a ThreadPool thread. If the processing of the Timer.Elapsed event lasts longer than Timer.Interval, the event might be raised again on another ThreadPool thread. In this situation, the event handler should be reentrant."
"The Timer component catches and suppresses all exceptions thrown by event handlers for the Timer.Elapsed event. This behavior is subject to change in future releases of the .NET Framework."
Your abiltiy to debug it depends on your skills on getting Exceptions out of alterante Threads and possibly general multithreading. Considering the possibly long running nature of this work, maybe a Rate Limitation would be better? Run code like this in another Thread:
integer interval = 20;
DateTime dueTime = DateTime.Now.AddMillisconds(interval);

while(true){
  if(DateTime.Now >= dueTime){
    //insert code here

    //Update next dueTime
    dueTime = DateTime.Now.AddMillisconds(interval);
  }
  else{
    //Just yield to not tax out the CPU
    Thread.Sleep(1);
  }
}


text:
Q: Проверка входа на сайт Здравствуйте. Ниже представлен код
@WebServlet(name = "SignInServlet", urlPatterns = {"/SignInServlet"})
public class SignInServlet extends HttpServlet
{
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
{
    String login = req.getParameter("login");
    String password = req.getParameter("password");
    String role;

    resp.setContentType("text/html;charset=utf-8");
    PrintWriter pw = resp.getWriter();

    Connection conn = null;

    String url = "jdbc:postgresql://127.0.0.1:5432/crm";
    String name = "vladimir";
    String pass = "1234";
    try
    {
        Class.forName("org.postgresql.Driver");
        conn = DriverManager.getConnection(url, name, pass);
        Statement statement = null;
        statement = conn.createStatement();
        JOptionPane.showMessageDialog(null,conn.toString());
        ResultSet result1 = statement.executeQuery("SELECT * FROM users");
        while (result1.next())
        {
            if((password.equals(result1.getString("password"))) &&
                    (login.equals(result1.getString("login"))))
            {
                role = result1.getString("userrole");
                getServletContext().
                        getRequestDispatcher("/signiinsucces.jsp").
                        forward(req, resp);
            }
            /*else if((!password.equals(result1.getString("password"))) &&
                    (!login.equals(result1.getString("login"))))
            {
                getServletContext().
                        getRequestDispatcher("/signiinfail.jsp").
                        forward(req, resp);
            }*/
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        getServletContext().
                getRequestDispatcher("/error.jsp").
                forward(req, resp);
    }
    finally
    {
        if (conn != null)
        {
            try
            {
                conn.close();
            }
            catch (SQLException ex)
            {
                getServletContext().
                        getRequestDispatcher("/error.jsp").
                        forward(req, resp);
            }
        }
    }
}
}

Как можно осуществить проверку для входа, чтобы успешном входе отправляло на страничку signiinsucces.jsp, а при неудачной попытке на signiinfail.jsp?

A: Прошу строго не судить этот код с моего первого приложения по Java.
Я реализовал для своего учебного приложения проверку вошел или нет по кукам.
Вначале делаю проверку в куках стоит ли метка авторизации, если нет то проверяю логин и пароль, и если ни один из перечисленных вариантов не прошел вывожу сообщение об ошибке и перенаправляю на страницу ввода логина и пароля.
Для лишения прав на доступ достаточно очистить куки от метки авторизации.
Так же я не давно узнал что существует легковесная библиотека для авторизации Apache Shiro https://shiro.apache.org/ , на любом проекте рекомендуют не писать самостоятельно авторизацию, а использовать готовое решение.
@WebServlet("/admin")
public class Admin extends HttpServlet {
private static final String LOGIN = "admin";
private static final String PASSWORD = "admin";

private static final String cookieName = "ADMIN";
private static final String cookieValue = "ADMIN";

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    req.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html;charset=utf-8");

    String login = req.getParameter("login");
    String password = req.getParameter("password");

    int a = LOGIN.compareTo(login);
    int b = PASSWORD.compareTo(password);
    System.out.println("a = " + a);
    System.out.println("b = " + b);

    // проверяет вход по защита ли авторизация в куках
    if (Util.isLoginSuccessful(req)) {
        resp.sendRedirect("/dbservlet");

    // если не зашиты данные в куках то проверяет введенный логин и пароль
    } else if (Util.isCorrectLoginPassword(req)) {
        // здесь в куках прописываем метку авторизации
        resp.addCookie(new Cookie(cookieName, cookieValue));
        // перенаправляем на на servlet который отвечает за завешенную
        // страницу, где так же будет проверка на авторизацию через куки
        resp.sendRedirect("/dbservlet");

    } else {
        // если никакой способ авторизации не прошел выводи сообшение
        // об ошибке и через 5 секунд перенаправляет на страницу авторизации
        PrintWriter out = resp.getWriter();
        out.println("Incorrect login or password");
        resp.setHeader("Refresh", "5;URL=http://localhost:8080/admin.html");
    }
}

// метод проверяет метку в куках
public static boolean isLoginSuccessful(HttpServletRequest req) {
    Cookie[] cookies = req.getCookies();
    for (Cookie cookie : cookies) {
        if (cookie.getName().contains(cookieName) && cookie.getValue().contains(cookieValue)) return true;
    }
    return false;
}

}


text:
Q: Read an MST file with vbscript I'm trying to do a script that gets information out of some MSI and MST files and write it into a text file. I achieved reading the MSI files. However, I get the following message.

Msi API Error 80004005: OpenDatabase, DatabasePath, OpenMode
1:2219  2:  3:4:

I open the file like this

Set installer = Wscript.CreateObject("WindowsInstaller.Installer") : CheckError
Dim database : Set database = installer.OpenDatabase(FileName, msiOpenDatabaseModeReadOnly) : CheckError

It works just fine with MSI files. I believe MST files should be read in a different way.
How can a read an MST file using vbscript?

A: I haven't tried myself, but according to MSDN, to view a transform file (MST) you need to open your MSI database and then use the ApplyTransform method with the msiTransformErrorViewTransform parameter. This will give you a temporary _TransformView table, which you can query to get the desired information.
So, your code should look like this:
Const msiOpenDatabaseModeReadOnly    = 0
Const msiTransformErrorViewTransform = 256
Dim installer, database

Set installer = CreateObject("WindowsInstaller.Installer") : CheckError
Set database = installer.OpenDatabase(MSIFileName, msiOpenDatabaseModeReadOnly) : CheckError
database.ApplyTransform MSTFileName, msiTransformErrorViewTransform : CheckError


text:
Q: Save one column of specific row to a .txt file in datagrid (Error: Unable to cast object of type App.Data.Controller to type System.Data.Datarowview) I've been looking around for a tutorial on how to do this since I'm quite new at working with WPF but cant find to seem what I'm looking for.
I have a datagrid binded and filled with testdata. I also have a download button per row that is meant to only download the column "XMLCode" of the row it belongs to. I would like for this data to be downloaded in a .txt file.
I know that proper architecture is MVVM but for simplicity's sake I care about getting the function to work first. Than rebuilding it into MVVM at a later time. I think my issue sounds simple enough but I can't find any tutorial or help that only deals with one specific column in one specific row, only examples of downloading an entire datagrid to a .txt file. Could anyone help me in the right direction?
Datagrid code for clarification
    <DataGrid Grid.Row="1" Grid.RowSpan="5" Grid.ColumnSpan="5" x:Name="ConDatagrid" CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding AllDatainTable, Mode=OneWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}">
        <DataGrid.Columns>
            <DataGridTextColumn Header="{x:Static p:Resources.LabelNaam}" Binding="{Binding Name}" />
            <DataGridTextColumn Visibility="Collapsed" Header="XML" Binding="{Binding XMLCode}" />
            <DataGridTemplateColumn Header="{x:Static p:Resources.LabelDownload}" dgx:DataGridFilterColumn.IsFilterVisible="False" >
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Button Click="DLButton_Click" Content="{iconPacks:Material Kind=ContentSave, Width=16, Height=16}">
                            <!-- Click=""> -->
                        </Button >
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

EDIT : This is what I've tried so far with a different table, this wields the error "Unable to cast object of type App.Data.Controller to type System.Data.Datarowview"
    public static void DumpAsTxt(object data, string fileName)
    {
        var stream = new FileStream(fileName, FileMode.OpenOrCreate);
        using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
        {
            writer.Write(data);
            writer.Close();
        }
    }

    private void DLButton_Click(object sender, RoutedEventArgs e)
    {
            try
            {
                System.Data.DataRowView dataRowView = (System.Data.DataRowView)((Button)e.Source).DataContext;
                String ControllerID = dataRowView[1].ToString();
                String ControllerXML = dataRowView[2].ToString();
                DumpAsTxt(ControllerXML.ToString(), "ResultaatID-" + ControllerID + ".txt");
                //This is the code which will show the button click row data. Thank you.
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
    }

EDIT 2 :
    private void DLButton_Click(object sender, RoutedEventArgs e)
    {
            try
            {
                DumpAsTxt(ConDatagrid.SelectedItem.XMLCode.ToString(), "ControllerXML.txt");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
    }

And AllDataInTable :
    public ObservableCollection<Controller> AllDatainTable { get; } = new ObservableCollection<Controller>();
    public void UpdateTest()
    {
        AllDatainTable.Clear();
        foreach (var item in GetAllDatainTable()) AllDatainTable.Add(item);
    }

    public static List<Controller> GetAllDatainTable()
    {

        using (var context = new EFContext())
        {
            return context.Controllers.ToList();
        }
    }

A: Unfortunately the button does not know anything about the Row it belongs too. So to fix your method first give the DataGrid a name (ConDatagrid) then make the below changes.
private void DLButton_Click(object sender, RoutedEventArgs e)
{
    try
    {
        var selectedItem = ConDatagrid.SelectedItem as Controller;
        String ControllerID = selectedItem.Name;
        String ControllerXML = selectedItem.XMLCode;
        DumpAsTxt(ControllerXML, "ResultaatID-" + ControllerID + ".txt");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}


text:
Q: Magnetic field and magnetic domains I have a confusion regarding how magnetic field propagate in a medium (ferromagnets or air etc..). It is knows when a ferromagnet is exposed to an external magnetic field, the magnetic domain of the ferromagnet will be aligned with the external magnetic field. My question is this alignment of domain assure the propagation of the external magnetic field in the ferromagnet? The same question for the air. Do the magnetic field propagate in the air because the magnetic domains of the air are aligned?

A: No alignment of magnetic domains in a medium is needed for a magnetic field to propagate in that medium. Magnetic fields can propagate through a vacuum despite the fact that there are no magnetic moments or domains at all in a vacuum, right?
Similarly, no dielectric moments are required for electric fields to propagate in a medium, and electric fields can travel perfectly well through a vacuum.


text:
Q: Jquery ajax call with prompt not working I'm putting a "Lost password" link in my login form.
The link in the form is in a div with id pwdforget
I do not want to submit the form, just prompting for an email address, looking into the db to verify whether such address exists, sending an email or returning an error in case email doesn't exist
My jquery script is quite basic (I use impromptu for the prompt, but I have the same problem with any other routine, even with the basic javascript prompt)
$('#pwdforget').click(function() {
  $.Prompt("Insert your email address","", "", function(r) {
    $.ajax({
      url: 'pwdforget.php?email='+r,
      success: function(res){
        result = $.trim(res);
        if(result=="ok") {
          alert("Thank you");
        } else {
          alert("Bad address");
        }
      }
    });
  });
});

Looking into the console, I can verify that the address is sent to the php file, but I get no answer from the file, nor any action takes place. I created an empty php file, which just echoes "ok", but in the success part of the ajax call I noticed that the res variable is always empty, no matter what is echoed from the php file.
I also noticed that nothing happens in the php file (I tried putting some variable with firephp, and the console echoes noting)
I use $.ajax every day, but this is the first time I use it with javascript prompt.
Any clue?
Thanks
Alfa

A: You can try .done().
$.ajax({}).done(function ( data ) { alert(data); })

This is working.
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
  var  r=prompt("enter your email");
  if(r){
    $.ajax({
      url: 'pwdforget.php?email='+r,
      success: function(res){
      $('body').html(res);
      }
  });} });
</script>


text:
Q: How to get a table identity inserted by instead of insert trigger? I have a problem described as follows: I have a table with one instead of insert trigger:
create table TMessage (ID int identity(1,1), dscp varchar(50))
GO
Alter trigger tr_tmessage on tmessage
instead of insert
as

--Set NoCount On

  insert into tmessage
  select dscp from inserted
GO
Alter proc P1
As

--Set NoCount On

insert into tmessage
(dscp)
values('some data')

Select SCOPE_IDENTITY()

GO

When I execute P1 it returns Null for SCOPE_IDENTITY() instead of the identity of the table. I even tried Output clause in the insert statement in the proc. but again the output table Identity field that gets filled from inserted in the Output clause is 0 in this case.
Any help would be appreciated.

A: Well, you've got yourself quite a pickle there.
From the one hand, you need the instead of insert trigger on your table, but from the other hand, you want to get the identity that this trigger generates back to the stored procedure that activated it.
Since there is no way to send parameters to and from triggers, you will have to do one of 3 things:

*

*Find some way to eliminate the need for that instead of trigger.
This is my best recommendation.

*Break your stored procedure to 2 parts: One part will do everything until the insert into statement (including it), thus activating the instead of insert trigger, and the other part that will do all operations needed after the trigger. this way you can use the scope_identity() inside the instead of insert trigger and send it's return value to the second stored procedure as a parameter.
Note: this design means you have to insert records one by one. should you try to insert more then one record, scope_identity() will only return the identity of the last row inserted by the trigger.

*Find some way of passing data between the stored procedure and the instead of trigger. Since triggers can't except or return parameters, you will have to use either a temporary table or a regular table. This suggested solution is only suggested as a last resort, since it will complicate your code and probably cause some performance issues as well. Also, you will have to find a way to hold execution of the stored procedure until the instead of trigger will finish it's work. I can give you some pointers on how to share data between the procedure and the trigger, but I really suggest not to choose this solution.

A: SCOPE_IDENTITY() return the value from current scope and that is stored procedure outside from stored procedure it will be null.use @@identity to get last inserted identity.


text:
Q: JavaScript and CSS positioning an image for any resolution I am trying to create a simple slide show of an image that is set up in and background div. I dont have problem with creating the slideshow code but i have problem with positioning the image that should change according to the the width of others monitors resolution.
In the image bellow i described were i want to place the image. The image should be placed in the red div.

Here is the image that i want to put in the red div to be like a background. The resolution is (1900px x 500px)

Here is a model what i managed to do. I tried in java script code to declared a global variable sw which I assigned the window.innerWidth (sw=window.innerWidth), after in  CSS  using jquery selecting the red div $('#rotator') and assigned the sw ($('#rotator').css('width', sw)), but the result wasn't what I need to obtain.  I obtained the image that was cropped from the right according to the screen resolution.

If someone know how to solve this question i will be greatful!
Here is my CODES:
HTML
<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="style.css">

CSS
body{
    margin: 0px;
    margin-left: 0px;
}

.slider{
    width: 940px;
    height: 360px;
    background-color: #FFDF00;
    margin: 0 auto;
    position: absolute;
    left: 15%;
    top: 20px;
    }

#rotator {
    position: relative;
    height: 500px;
}

.puzzle {
    width: 100px;
    height: 100px;
    background-position: -100px 0px;
    float: left;
}

And JavaScript that also contain the function of slideshow effect (that is working).
$(document).ready(init)

sw=window.innerWidth;

if (sw % 100 == 0) {
    sw=window.innerWidth
}
else{
    sw=Math.floor(sw/100)*100
}

//counter of slider
current_slide=0;
image_list=new Array
(
"img/1.jpg",
"img/2.jpg",
"img/3.jpg",
"img/4.jpg",
"img/5.jpg"
);

function init ()
{
    $('#rotator').css('width', sw)
    change(image_list[current_slide]);
    //start timer
    setInterval(  "change(image_list[current_slide])"   ,2500);
}

function change(bg_image){
    // this function creats cells inside

    rot = $('#rotator'); //constructor
    rot.empty();
    for(y = 1; y<=5; y++)
     {
        for(x = 1; x<=sw/100; x++)
          {
           rot.append('

');
           //select the
 using his class and setting up the cells coordinates
           $('.p-' + x + '-' + y).css('background-position', (-(x-1)*100) + 'px ' + (- (y-1)*100) + 'px').css('background-image','url('+bg_image+')');
           $('.p-' + x + '-' + y).css('opacity', 0).delay(parseInt(Math.random()*1000)).animate({opacity: 1}, {duration: 1000})
          }
     }
     current_slide++;
     if(current_slide >= image_list.length)current_slide=0
}

Thank you  for your time and consideration!

A: You either have to put the image into a container div who's width is dynamic to the size of the page and set width of the image inside it to 100%, or use the CSS attribute background-size: cover; (which is only compatible with newer browsers).
Images set as the background image for a div will simply fill their container and be clipped by that container as it shrinks past the dimensions of the background image unless background-size: cover; is used.  To gain the same effect in older browsers, the aforementioned 100% trick is used.
Cross-browser style:
http://jsfiddle.net/2D5Vw/
New(ish)-School:
http://jsfiddle.net/HLf2Q/


text:
Q: How to return an object in jsx and use in immediately with out depending on setState as its Asynchronous I am new to react and I am trying to do DRF (Django Rest Framework) with React so I am using the fetch() with required attributes to hit the API endpoint and getting some data. Now in my case, I need to hit two API endpoints. But I wanted to reuse the fetch() by putting it in a function which will return an object and I'll save using setState.
My problem is the endpoint URL for the second API call is in the object returned by the first API call.
Example:
fetch(enpoint1, data) -> returns {name: 'something', url: 'endpoint2'}
if I do setState here the object is not updated as setState is Asynchronous and so I cannot use it immediately.
I might have a super silly mistake. Any advice on the "way I am doing it" or "on how to correct it" would be appreciated.
  componentDidMount() {
  let currentComponent = this;
  try {
    const data = {username: 'username', password: 'password'};
//gets me the token
    fetch(URL(Just example), {
      method: 'POST',
      headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
      },
      body: JSON.stringify(data)
    }).then(function(response) {
      return response.json();
    }).then(function(data){
      return data.token
    }).then(function(token){
      var project_object = currentComponent.fetchFunction(currentComponent.props.endpoint, token)
      console.log(project_object)
      //This is UNDEFINED
    })
  } catch (e) {
    console.log(e);
  }
}

fetchFunction(endPoint, token) {
    let currentComponent = this;
    var object = {}
    console.log(endPoint)
    try {
      //fetch for project object
      fetch(endPoint, {
        method: 'GET',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'authorization': 'Token ' + token
        }
      }).then(function(response) {
        return response.json();
      }).then(function(object){
        console.log(object)
        object = object
      })
    } catch (e) {
      console.log(e);
    }
    return object
}


text:
Q: Upload image to a web site automatically I'm looking for a solution to be able to upload images to a web site without the need to fill the form myself.  The site in question uses a flash button with triggers the file selection on my computer and then uploads my selected files on the web page.  Is there any way I can automate this process ?
Thanks in advance

A: You could use a proxy/web debugger such as fiddler2, see what the http transaction looks like for a single file upload and then write an app to do that same for your list of images.


text:
Q: Is it possible to use OCaml in embedded mode? Some time ago I emerged for myself that Guile and Racket can be embedded and be called right from any C++ application.
Can OCaml work like this?

A: You can have a look at the Embedded O'Caml Toplevel done by Clément Capel. It's the result of a summer internship so it wasn't updated since 2004.
Otherwise, there is ocamlmklib.

A: You can use the OCaml toplevel as a library. It is part of the official OCaml distribution and up-to-date. See toploop.mli in OCaml sources for the interface. It is officially only available in bytecode, but there is experimental support for native code.
If you plan to redistribute your application, be aware that the toplevel library (and the compiler itself) are under a more restrictive license (modified QPL) than the standard library and runtime (modified LGPL).


text:
Q: What is a good way to familiarize myself with PHP, coming from an ASP.NET background? Currently, I'm very comfortable with building tools/web apps in an ASP.NET environment. I'm not really looking to leave tbh, as I really like C#, ASP.NET, MVC 3, Visual Studio, etc.
However, right now I know almost nothing about PHP and that seems like a deficiency that I'd like to rectify.
Are there any books (or other learning methods) that would be a good resource to learn PHP? Obviously there are plenty of beginning PHP books, but I am already comfortable with much of what is involved with building a web page, and interested in focusing on PHP itself which might not be compatible with the scope of some beginning PHP books.
I went through the PHP Manual quite a bit, and it doesn't seem to flow as smoothly as might be ideal. Is there a beginning PHP book that would be appropriate? I miss the cohesiveness that most books contain when looking through those samples. There is lots of info more, but it feels more like a reference while coding than a primary learning vehicle.

A: The best resource out there to learn PHP is the PHP manual. It's extremely well written and well structured, and it's one of the biggest assets of the PHP community. If you are confident with ASP.net, the manual is enough to get you started.
Before you start reading though, you should setup a PHP stack. You can install Apache, PHP and your favorite database (SQLServer is fine) by yourself (it's extremely easy) or you could setup a ready made stack like XAMPP. XAMPP will install:

*

*Apache,

*MySQL,

*PHP,

*The PHP Extension and Application Repository (PEAR)

*PERL

*OpenSS (via mod_ssl)

*SQLite

*phpMyAdmin
all in one go (plus some other stuff). One important library it's missing is phpUnit, that obviously will help you with unit testing.
Then you should install an IDE, your obvious choices are Eclipse Classic with the PHP Development Tools (PDT) or Netbeans for PHP. There are a lot of others, but these two I recommend. I use them both, if you can't choose between them Netbeans is a little easier to get the hang of, but you should really evaluate both and decide for yourself which one is better for you - I haven't worked with Visual Studio in a long time and I really don't know which IDE may feel more familiar to you.
When you get over the basics from the manual, you should start thinking of an MVC framework. Again, I will recommend two:

*

*Zend Framework, and

*CodeIgniter
Zend Framework is the beast and CodeIgniter is the beauty, if you allow me a silly metaphor. Zend Framework has a steep learning curve, is backed by Zend (the company behind PHP), and you can do almost everything with it. CodeIgniter is a lot easier to get the hang of, has nice documentation for beginners and it's fairly popular. But most of it's codebase is outdated crap, as they used to support PHP4 not so long ago.
For a beginner the obvious choice is CodeIgniter, but don't get stuck with it. Use it as a learning tool and move to Zend Framework as soon as possible. Again there are a lot more MVC frameworks in the PHP world, but these two are the ones I recommend.
As for books, a great non beginner book is PHP Objects, Patterns and Practice. Sitepoint's PHP books are always a delight to read. If you fall in love with PHP you should really consider a subscription to PHP Architect.
Lastly, check out this great discussion on purely technical reasons for PHP as a first choice.

Update: A few more online resources, that mostly target non beginners:

*

*IBM's PHP project resources

*Oracle's PHP Developer Center

*Zend Developer Zone
and if for some weird reason you want to play around with PHP on IIS instead of Apache, a good starting place is Microsoft's PHP on Windows. PHP on IIS works and is a valid choice especially for a .Net developer, but you should really go with Apache (and MySQL or PostgreSQL instead of SQLServer) to get the full PHP experience and also ensure that your skills are portable to any other popular OS. You don't want to miss out on the joy that is mod_rewrite.

Personal note: There's a lot of hate floating around for PHP, some of it is justified. If you do decide to go for it, you must be extremely critical of the various PHP resources, scripts, libraries you will meet along the way, there's too much crap out there and it's impossible for a beginner to know the difference. PHP's vast popularity can be translated to a very big and helpful community, large marketability of your skills, millions upon millions of blogs, but it can also be translated to a few thousand terabytes of crappy code.

A: Yannis has a lot of good stuff to say there but I read, Build Your Own Database Driven Web Site, 4th Edition, and it was filled with everything I needed to know to get started on the right path to developing professional PHP web applications.
I was also working exclusively on .NET before I started doing some PHP work. PHP is a lot easier to work with but has some peculiar issues when developing large scale applications and this book gets you started on that.
One issue for me was that how PHP is not strictly an Object Oriented language. It has all sorts of functions in procedural form and Object Oriented form and it kinda takes a while to get used to, coming from a language where everything is organized into classes and namespaces.
Another one was how easily you can mix up everything in PHP making things a lot more difficult. In .NET the tools that you use, such as Visual Studio, guide you to actually practice good coding standards by doing some of the work for you. Usually a .aspx page would have it's HTML Markup and C# code separated into two files.
If you are a heavy user of .NET tools, and prefer to work with ASP.NET controls, still another is issue for you would be the lack of controls (GridView etc) in PHP. I know that there are a lot of libraries/frameworks that give you something similar but they are not exactly part of the basic PHP package.
Another issue for me was how in PHP, there is heavy use of Arrays and Hashes serving more like collections in .NET. They are everywhere and it would be a good to get used to the fact that arrays are not just an ordered list of the same type of objects/scalar units. They can server as a collection objects to house all sorts of stuff.
I can go on and on but to mention one of the major things I found very peculiar to PHP (I don't know it could be also common in other languages), is how often the "include" (and related) functions are used so commonly. I can say that the book from Sitepoint can get you up to speed with all of this.


text:
Q: Merge Mozilla Addon to Build I am working on a few addons on Mozilla since this easier than manually editing the source code.
The bigger picture is to have a customized browser that I can share with my fellow geeks and friends.
Question:Is there a simple way to add an addon to a Mozilla build so that my users don't have to manually install the addons on their computer.Something like a pre-packaged Setup.exe. The Setup.exe needs to be fully independent and not requiring to have Mozilla pre-installed.
More info(Edited):

Another reason is I do not want them to have access to the addons ,
  the addons shouuld be in the core of the browser.Hence, a user should
  not be able to turn off or even know it is an addon but barely the
  functionality of their browser X.

A: You may want to use Portable Firefox, make your customizations and share the folder with your friends.
http://portableapps.com/apps/internet/firefox_portable


text:
Q: Python http.client.Incomplete Read(0 bytes read) error I have seen this error on the forum and read through the responses yet I still don't understand what it is or how to address it. I'm scraping data from the internet from 16k links, my script scrapes similar information from each link and writes it to a .csv some of the date gets written before this error.
Traceback (most recent call last):
 File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 541, in _get_chunk_left
   chunk_left = self._read_next_chunk_size()
 File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 508, in _read_next_chunk_size
   return int(line, 16)
ValueError: invalid literal for int() with base 16: b''

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
 File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 558, in _readall_chunked
   chunk_left = self._get_chunk_left()
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 543, in _get_chunk_left
   raise IncompleteRead(b'')
http.client.IncompleteRead: IncompleteRead(0 bytes read)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "MoviesToDb.py", line 91, in <module>
html = r.read()
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 455, in read
   return self._readall_chunked()
File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/http/client.py", line 565, in _readall_chunked
   raise IncompleteRead(b''.join(value))
http.client.IncompleteRead: IncompleteRead(17891 bytes read)

I would like to know:1) What does this error mean?  2) How do I prevent it?

A: try to import :
from http.client import IncompleteRead

and add this in your script :
except IncompleteRead:
    # Oh well, reconnect and keep trucking
        continue

A:
requests.exceptions.ChunkedEncodingError: ('Connection broken: IncompleteRead(0 bytes read)', IncompleteRead(0 bytes read)).

It is because the server of http protocal is 1.0 version,while python use 1.1 version. The solution is to assign the protocal version of client, like this
Python3 Version please add:
> import http.client
> http.client.HTTPConnection._http_vsn = 10
> http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'

Python2 Version please add:
> import http.client
> http.client.HTTPConnection._http_vsn = 10
> http.client.HTTPConnection._http_vsn_str = 'HTTP/1.0'

See the reference How to deal with "http.client.IncompleteRead: IncompleteRead(0 bytes read)" problem


text:
Q: jQuery UI Position right top set's CSS to left top This code :
controls.position({
    my: "right top",
    at: "right top",
    of: parent
});

is setting the element controls CSS as

...

Why does it not set it as right: 0px; ?

A: One possibility is that the code is compatible with older browsers which don't support the right or bottom CSS properties. Older IE's don't support those.


text:
Q: cordova plugin twilio_client_phonegap in hosted webapp : cordova I am using this plugin in my cordova app to use twilio client sdk functionality. Plugin is working fine in my app.
Question
I needed this plugin in my "Hosted Cordova App", this plugin uses tcplugin.js and i cannot find help to use this plugin in my app.
*I dont think including .js file manually will work.
Any help or reference will be appreciated. Thanks for your time.

A: I have used cordova-plugin-remote-injection to inject the plugins in hosted app.
Copy and paste the tcplugin.js and load it on device ready, it will work.


text:
Q: Divide Bootstrap card class to 3 horizontal boxes of the same size and 2 vertical boxes I am using Bootstrap 4 and I have the following Bootstrap code block:

I need to create an image gallery: 3 horizontal boxes of the same size and 2 vertical boxes, so I tried the following code:

            Your text

            Your text

            Your text

            Your text

            Your text

            Your text

But this generates the gallery with some space between images. I need images without any space between. What could I do to achieve this?

A: CSS
.borders{
  border: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

HTML

Preview Screenshort

A: You could also consider doing your gallery with plain CSS. Witch makes the HTML so much nicer:

.gallery {
  width: 600px;
  display: grid;
  grid-template-columns: auto auto auto;
  grid-template-rows: auto auto;
  grid-gap: 0;
}
.gallery > * {
  width: 200px;
}

A: Try this way:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"/>


text:
Q: Is it possible to set diff/merge-tool for a specific file extension in git-extensions? I'm just getting started on developing in LabView, it's all new to me.
And i'd like to use git extensions to handle my versioning. Since the source is in a *.vi format, I can't use the normal diff tools, the source is binary.
Fortunately, LabView comes with dedicated diff and merge tools which seems to be very helpful. And I can setup TortoiseGit to use these tools on all *.vi files. It's from this how-to:
https://www.labviewhacker.com/doku.php?id=learn:software:github:getting_started
Is there a way to do the same in Git Extensions? I much prefer git extensions over TortoiseGit.. So I'd rather not be forced to use TortoiseGit.
From what I've found, you can only specify a general diff/merge tool, not different ones for different types of files.
Any help would be appreciated, do anyone know how? :)

A: If the output of the diff tool is text, you can view diffs under standard Git using a combination of .gitattributes and .git/config. I hope that Git Extensions would respect this setting.
I recommend reading the Git Attributes chapter of the Pro Git book for details on setting this up, but the idea should be something like
*.vi diff=labview

in your repository's .gitattributes file, and
[diff "labview"]
textconv = labview-diff-tool

in your .git/config.
If the diff tool does not output text, you may find the top response to this question useful, which discusses using a graphical diff tool.

A: Reference: http://zone.ni.com/reference/en-XX/help/371361H-01/lvhowto/configlvcomp_thirdparty/

*

*Right-click in any folder (that is not a git project) and select TortoiseGit –> Settings

*Click on Diff Viewer tab

*Click Advanced -> Add

*

*Extension: .vi

*External Program:
C:\Program Files (x86)\National Instruments\Shared\LabVIEW Compare\LVCompare.exe %base %mine-nobdcosm -nobdpos

*

*-nobdcosm means do not compare the appearance of block diagram objects.

*-nobdpos means do not compare the size or position of block diagram objects.

*Repeat for: .ctl and .llb extensions


text:
Q: Getting screen width on API Level 30 (Android 11): getDefaultDisplay() and getMetrics() are now deprecated. What should we use instead? I currently calculate the screen width like this :
public static int getScreenWidth(@NonNull Context context) {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics.widthPixels;
}

Since these 2 functions (getDefaultDisplay() and getMetrics()) are now deprecated, what should we use instead ?

A: Running into the same problem in 2022, there's a newish Jetpack library for handling this across the various API versions.
build.gradle
dependencies {
    implementation 'androidx.window:window:1.0.0'

}

import androidx.window.layout.WindowMetrics;
import androidx.window.layout.WindowMetricsCalculator;

WindowMetrics windowMetrics = WindowMetricsCalculator.getOrCreate().computeCurrentWindowMetrics(activity);
final int height = windowMetrics.getBounds().height();
final int width = windowMetrics.getBounds().width();

One caveat I ran into as well is that including androidx.window ended up pulling in tens of thousands of library methods that put me above the DEX 64k method limit, so I had to figure out how optimize those out using the R8/proguard settings, but that's another problem.

A: For calculating screen width minus any system bars, this should work:
public static int getScreenWidth(@NonNull Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        WindowMetrics windowMetrics = activity.getWindowManager().getCurrentWindowMetrics();
        Insets insets = windowMetrics.getWindowInsets()
                .getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
        return windowMetrics.getBounds().width() - insets.left - insets.right;
    } else {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics.widthPixels;
    }
}

Note that this isn't exactly the same: testing this with the height produces different results, and I've been unable to replicate the old API's functionality with the new API (partly due to the behavior of the old API being a bit tricky to reason about and not always what you want, hence its deprecation).  In practice, though, it should be good enough as a generic screen width for many things.

A: I guess I have successfully implement equivalent methods (improving @RyanM's) to deprecated one.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Deprecated older method for comparison.
    DisplayMetrics outMetrics = new DisplayMetrics();
    getDisplay().getMetrics(outMetrics);
    Log.d("Upto API-29", String.format(
            "(width, height) = (%d, %d)", outMetrics.widthPixels, outMetrics.heightPixels
    ));

    // Newer methods.
    Log.d("API-30+", String.format(
            "(width, height) = (%d, %d)", getScreenWidth(this), getScreenHeight(this)
    ));
}

public static int getScreenWidth(@NonNull Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        WindowMetrics windowMetrics = activity.getWindowManager().getCurrentWindowMetrics();
        Rect bounds = windowMetrics.getBounds();
        Insets insets = windowMetrics.getWindowInsets().getInsetsIgnoringVisibility(
                WindowInsets.Type.systemBars()
        );

        if (activity.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE
                && activity.getResources().getConfiguration().smallestScreenWidthDp < 600
        ) { // landscape and phone
            int navigationBarSize = insets.right + insets.left;
            return bounds.width() - navigationBarSize;
        } else { // portrait or tablet
            return bounds.width();
        }
    } else {
        DisplayMetrics outMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }
}

public static int getScreenHeight(@NonNull Activity activity) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        WindowMetrics windowMetrics = activity.getWindowManager().getCurrentWindowMetrics();
        Rect bounds = windowMetrics.getBounds();
        Insets insets = windowMetrics.getWindowInsets().getInsetsIgnoringVisibility(
                WindowInsets.Type.systemBars()
        );

        if (activity.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE
                && activity.getResources().getConfiguration().smallestScreenWidthDp < 600
        ) { // landscape and phone
            return bounds.height();
        } else { // portrait or tablet
            int navigationBarSize = insets.bottom;
            return bounds.height() - navigationBarSize;
        }
    } else {
        DisplayMetrics outMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }
}

The points are

*

*SystemBar's height is not included in Window bound's height. We should exclude NavigationBar's height only (unless it is in landscape mode on phone device).

*In landscape mode on phone device, we should exclude NavigationBar's size from Window bound's width.

TESTS
1. On my real phone (API-30)
portrait:
2021-12-14 22:17:28.231 31660-31660/com.stackoverflow.windowmetrics D/Upto API-29: (width, height) = (1080, 2016)
2021-12-14 22:17:28.237 31660-31660/com.stackoverflow.windowmetrics D/API-30+: (width, height) = (1080, 2016)

landscape:
2021-12-14 22:17:35.858 31660-31660/com.stackoverflow.windowmetrics D/Upto API-29: (width, height) = (2016, 1080)
2021-12-14 22:17:35.887 31660-31660/com.stackoverflow.windowmetrics D/API-30+: (width, height) = (2016, 1080)

2. On emulated Nexus10 (API-31)
portrait:
2021-12-14 22:19:33.379 1416-1416/com.stackoverflow.windowmetrics D/Upto API-29: (width, height) = (1600, 2464)
2021-12-14 22:19:33.382 1416-1416/com.stackoverflow.windowmetrics D/API-30+: (width, height) = (1600, 2464)

lanscape:
2021-12-14 22:18:44.809 1416-1416/com.stackoverflow.windowmetrics D/Upto API-29: (width, height) = (2560, 1504)
2021-12-14 22:18:44.814 1416-1416/com.stackoverflow.windowmetrics D/API-30+: (width, height) = (2560, 1504)

2. On emulated Nexus7 (API-31)
portrait:
2021-12-14 22:21:21.606 3108-3108/com.stackoverflow.windowmetrics D/Upto API-29: (width, height) = (800, 1216)
2021-12-14 22:21:21.610 3108-3108/com.stackoverflow.windowmetrics D/API-30+: (width, height) = (800, 1216)

landscape:
2021-12-14 22:22:23.283 3108-3108/com.stackoverflow.windowmetrics D/Upto API-29: (width, height) = (1280, 736)
2021-12-14 22:22:23.289 3108-3108/com.stackoverflow.windowmetrics D/API-30+: (width, height) = (1280, 736)

A: val windowMetrics = requireActivity().windowManager.currentWindowMetrics
val displayMetrics = resources.displayMetrics

val pxHeight = windowMetrics.bounds.height()
val pxWidth  = windowMetrics.bounds.width()

val density  = displayMetrics.density

val dpHeight = pxHeight/density
val dpWidth  = pxWidth/density

A: @RequiresApi(20)
inline val Fragment.windowHeight: Int
    get() {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val metrics = requireActivity().windowManager.currentWindowMetrics
            val insets = metrics.windowInsets.getInsets(WindowInsets.Type.systemBars())
            metrics.bounds.height() - insets.bottom - insets.top
        } else {
            val view = requireActivity().window.decorView
            val insets = WindowInsetsCompat.toWindowInsetsCompat(view.rootWindowInsets, view).getInsets(WindowInsetsCompat.Type.systemBars())
            resources.displayMetrics.heightPixels - insets.bottom - insets.top
        }
    }

@RequiresApi(20)
inline val Fragment.windowWidth: Int
    get() {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val metrics = requireActivity().windowManager.currentWindowMetrics
            val insets = metrics.windowInsets.getInsets(WindowInsets.Type.systemBars())
            metrics.bounds.width() - insets.left - insets.right
        } else {
            val view = requireActivity().window.decorView
            val insets = WindowInsetsCompat.toWindowInsetsCompat(view.rootWindowInsets, view).getInsets(WindowInsetsCompat.Type.systemBars())
            resources.displayMetrics.widthPixels - insets.left - insets.right
        }
    }

This requires androidx.core version 1.5.x

A: Most of the answers here using windowManager.getCurrentWindowMetrics() method to get the screen size. But this won't give the actual(physical device) screen size. If the screen is in split mode the application will occupy only some portion of the screen and it will give that size instead of full-screen size.
So to get the full-screen size it is recommended to use windowManager.getMaximumWindowMetrics() method.
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
WindowMetrics metrics = windowManager.getMaximumWindowMetrics();
Rect bounds = metrics.getBounds();
int width = bounds.width();
int height = bounds.height();

A: You can use
Context.getDisplay() instead of getDefaultDisplay()
display.getRealMatrix(displayMetrics) instead of display.getMetrics(displayMetrics)


text:
Q: Can you describe every number as a handful of small recurring operations and some input? Let's say that I would like to describe every number from 1 to googleplex with a limited number of operations, but including recursion.
So for a random example, I want to describe:
340282366920938463463374607431768211146
I can describe that as the following:
input = 2

while_loops = 7

while (while_loops > 0):
    input = input * input
    while_loops = while_loops - 1

input = input - 310

print(input)

Is it possible to represent all integers between 1 and googleplex with similarly simple steps?
Is there a way to measure how complex the algorithms would need to get to be able to describe every number between those two?
Is there a way to quickly determine what those algorithms are?
What field of mathematics would study this question? Are there any big name papers?


text:
Q: Cannot convert byte array back to Protobuf String     @Test
    public void test() throws InvalidProtocolBufferException {
        byte[] testString = StringValue.newBuilder()
                                       .setValue("testString")
                                       .build()
                                       .getValueBytes()
                                       .toByteArray();

        StringValue stringValue = StringValue.parseFrom(testString);
        System.out.println(stringValue);
    }

Created a byte array from the Protobuf StringValue, but when converted it back, I got:

com.google.protobuf.InvalidProtocolBufferException: Protocol message end-group tag did not match expected tag.

Any idea why would this happen?


text:
Q: Sampling and Filtering In my system I measure signals with interesting bandwith from DC to 2 kHz. I have an analog low-pass filter with 200 kHz cutoff frequency in order to filter noise. The ADC samples the signal with 500 kHz. The signals are then used for a feedback controller that runs in a task with 20 kHz. So my questions are the following:
Can I expect alias on the signals used in the control task of 20 kHz?
Should in this case a digital filter at the sampling rate of 500 kHz applied that has a maximal cutoff frequency of 10 kHz (Half of control task rate)?
Would it be possible to apply a further low pass filter with 10 kHz cutoff frequency in the 20 kHz program task?

A:
Can I expect alias on the signals used in the control task of 20 kHz?

Yes. The 500kHz signal could have have signals up to 200kHz in it. It would get aliased when re-sampled for feeding into 20kHz.

Should in this case a digital filter at the sampling rate of 500 kHz applied that has a maximal cutoff frequency of 10 kHz (Half of control task rate)?

Yes. You can have a digital anti-aliasing filter running at 500kHz sitting upstream of the 20kHz control task.

Would it be possible to apply a further low pass filter with 10 kHz cutoff frequency in the 20 kHz program task?

(Emphasis mine). By the time you are inside the 20kHz, task, the aliasing would have already occured. (Unless you passed multiple, consecutive samples of the 500kHz signal inside the task, in which case the information loss hasn't occured yet). So, the digital anti-aliasing filter should be sitting upstream of the task.


text:
Q: read elements file txt bash I have a file text titled test.txt containing
1 2 3 4
2 3 4
1 12 2 4 5 66

I would like to read it line by line and for each line I would like to extract the elements.
I tried with
while read lines;
do

  echo $lines

done < test.txt

It prints correctly the lines of the matrix saved in the txt file but now I don't know how extract the single elements from the variable lines...
I would like to do something like this
while read lines;
do

 ((for i = 0; i<=numberofelementline; i++))
 do
   element = ....
   echo $element

 done

done < test.txt

A:     read -a line <<< $a
    for i in ${!line[@]}; do echo ${rline[i]}; done

We read a file / line and store as an array. Next for each element of the array we run a for loop. This way you know the element and it's position.

A: You could replace all spaces to new lines and read them again with another while loop:
while read LINE; do
        echo "$LINE"  | tr -s ' ' '\n' | while read NUM; do
                echo $NUM
        done
done < test.txt

A: If you just want to echo them:
cat test.txt | tr ' ' '\n'

If you want to use the numbers:
while read num; do
    echo $num
    ...
done < <( cat test.txt | tr ' ' '\n' )


text:
Q: Prevent entire field in Access form from being highlighted When I scroll to the next record in an Access form, whatever field I am in gets highlighted once scrolled to the next record. How do I prevent the highlight of the entire field?
Users are having issues where they are accidentally deleting with one click because the entire field is highlighted.

A: You will find the behaviour set under Options, Behaviour Entering Field.
See also: http://msdn.microsoft.com/en-us/library/aa172326(v=office.11).aspx


text:
Q: Unable to drop default constraint in Oracle SQL> ALTER TABLE CUSTOMERS MODIFY AGE INT DEFAULT 10;

Table altered.
SQL > ALTER TABLE CUSTOMERS ALTER COLUMN AGE DROP DEFAULT;

ERROR at line 2:
ORA - 01735 : invalid ALTER TABLE OPTION.

A: Your ALTER statement is wrong and you cannot use two ALTER commands in one statement. And we never drop default value instead we set it to NULL.

If a column has a default value, then you can use the DEFAULT clause to change the default to NULL, but you cannot remove the default value completely. If a column has ever had a default value assigned to it, then the DATA_DEFAULT column of the USER_TAB_COLUMNS data dictionary view will always display either a default value or NULL.

ALTER TABLE
Use the following SQL command to drop the default.
ALTER TABLE constomers MODIFY age DEFAULT NULL;

A: Use MODIFY [COL_NAME] DEFAULT NULL instead of ALTER COLUMN [COL_NAME] DROP DEFAULT so far oracle does not accept the latter version.


text:
Q: Windows 8 laptop booting straight to BIOS. No logo One month old Windows 8 laptop (Asus K55N-DB81) has suddenly stopped booting. When turning on the laptop, it goes straight to BIoS without showing any of the ASUS logos or anything.
I've tried the following:

*

*Reset bios

*Pull RAM one at a time

*Boot without hard drive

*Try to use F12 boot options

*Make sure HDD and RAM are seated properly

All have no impact and have the same outcome as above. The BIOS seems to recognize that there is a hard drive and the proper amount of RAM.
I've exhausted all of my troubleshooting options. Anything else I can try before going through warranty support?
I should also note that the laptop came with no physical recovery media.

A: If you have the Windows installation disc or have the means to make one, you should try reinstalling Windows or repairing it from that disc.

A: Found this on the ASUS website.  Just check that I have your correct model.
BIOS 217
1.Update agesa code
2.Fix bug it will display ASUS logo when "Launch CSM" item disable
3.Fix the bug that System will show black screen
4. Fix winflash verify fail

Asus


text:
Q: jquery how to check if string contains specific numeric value How can I check with a jQuery if string value contains the specified numeric value?
For e.g;
a= 13
c = 12

b = 'we have 13 monkeys in the Zoo"

how to check if ( a in b = True)  and (c in b = False)?

A: You can use a regex to achieve that :

var a = 13,
    c = 12,
    b = 'we have 13 monkeys in the Zoo';

if (b.match('\\b' + a + '\\b')) {
  console.log('b includes a');
}

if (b.match('\\b' + c + '\\b')) {
  console.log('b includes c');
}

Using \b limit search to match the whole word, here "13", addressing the issue pointed out by George.

A: You can use the following code:
var s = $.grep(b.split(' '), function(v) {
  return v == a
});

if (s.length) {
  console.log('b includes a');
}

Demo

var a = 13,
  c = 12,
  b = 'we have 13 monkeys in the Zoo';
d = 'we have 134 monkeys in the Zoo';

var s = $.grep(b.split(' '), function(v) {
  return v == a
});

var t = $.grep(d.split(' '), function(v) {
  return v == a
});

if (s.length) {
  console.log('b includes a');
}
if (t.length) {
  console.log('d includes a');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: Create Dynamic Search Query Using StringBuilder I have a search form which has data in controls like checkboxlist (Multi Select), text box
I need to search SharePoint list for the values and display the list records in grid view.
Please suggest me how to write the search query which is dynamic..
Ex: If there are no values selected in one text box.. I need not include it in the query.

A: You can either run SPMetal to generate static objects to query your lists using LINQ

*

*http://msdn.microsoft.com/en-us/library/ee538255%28v=office.14%29.aspx

*http://zimmergren.net/technical/sp-2010-getting-started-with-linq-to-sharepoint-in-sharepoint-2010
Or just use an old and yet effective CAML Query
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Where><Eq><FieldRef Name='YourField'/>" +
    "<Value Type='Text'>Insert value to search here</Value></Eq></Where>";
SPListItemCollection collListItems = oList.GetItems(oQuery);

In a straight forward linq query
var results = MySPList.Items.Cast<SPListItem>()
              .Where(SPItem => SPItem["YourField"] == "Your query");

However, running spmetal is the way to go if you plan to use linq queries frequently, because using straight linq queries on splists can result on serious performance issues.

A: Using StringBuilder to form the query dynamically.
if (!(String.IsNullOrEmpty(implanter)))
{
      query[querycount] = "<In><FieldRef Name='Implanter' /><Values>" + implanter + "</Value></In>";
                            querycount++;
}


text:
Q: jQuery Duplicate detection for list I'm trying to detect duplicate so that i can identify them and add in additional information for the user to be able to differentiate them.
But whats happening bellow is everything gets triggered as a dupe.
It's been a long day and hoping for a second pair of eyes to help out with this.

jQuery(document).ready(function($) {
  "use strict";

  $.each(["bingo a", "bingo b", "bingo c", "bingo c", "bingo d", "bingo e", "bingo e", "bingo f", "bingo g"], function(index, element) {
    var $sameValue = $(this).text(),
      $abaadd = "";

    if ($(this).next().text() === $sameValue || $(this).prev().text() === $sameValue) {
      $abaadd = ' (dupe)';
    }
    $('ul').append($('
' + element + $abaadd + '
'));

  });

});

A: I propose this:
let arr = ["bingo a", "bingo b", "bingo c", "bingo c", "bingo d", "bingo e", "bingo e", "bingo f", "bingo g"]

for(i = 0; i < arr.length; i++){
  let item = arr[i];
  let optionalValue = "";

  if (item === arr[i + 1] || item === arr[i - 1]) {
    optionalValue = "(dupe)"
  }
   $('ul').append($('
' + item + optionalValue + '
'));
}

Here is Jsfiddle : https://jsfiddle.net/mr_oza/5qmnewjg/2/

A: You have some mistakes using Jquery without needing it. This should solve your problem

jQuery(document).ready(function($) {
  "use strict";

  var arr = ["bingo a", "bingo b", "bingo c", "bingo c", "bingo d", "bingo e", "bingo e", "bingo f", "bingo g"]
  arr.forEach(function(element, index){
    var $abaadd = "";

    if (arr[index + 1] === element || arr[index-1] === element) {
      $abaadd = ' (dupe)';
    }

    $('ul').append($('
' + element + $abaadd + '
'));

  });

});

Basically, $(this) has no property $(text), being just a string, not an html element.
Also, Taking a quick look at jQuery documentation I didn't find any .next() or .previous() on $.each, so I replaced it with a native forEach so I can access previous and next indexes to compare


text:
Q: jquery event handlers stacking i have something like this: http://jsfiddle.net/PTcw8/4/

     show me

    <input type="button" value="click to change the links onclick event" onclick="javascript:changeOnClick(); return false;" />

function changeOnClick() {
    $("#container a").unbind('click');
    $("#container a").on('click', function() {
        alert("changed on the fly");
    })
}

the link has an inline onclick event, i cant unbind it and bind a new handler, they just stack for some reason.
isn't it possible to unbind inline handlers?

A: You can only .unbind() an event handler if you have previously attached it with .bind():

Event handlers attached with .bind() can be removed with .unbind().

For inline event handlers, either use:
$("#container a").removeAttr("onclick");

or
$("#container a")[0].onclick = null;

DEMO.

A: I would do this:
$(document).ready(
    function(){
       $("#container a").removeAttr("onclick");
       $("#container a").on('click', function() {
          alert("changed on the fly");
       })
    }
);


text:
Q: Conversion python to Java I need to convert this Python code in Java but the '\x00' hexcode is a real problem.
How can I do the export data to bytes[] ?
message__FirstPart = '\x45\x55\x43\x45\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00'
# event_par = key number (5+ 0..9
message__event_par   = chr(key+5)
message__filler   = '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
# mit link state = 1
message__link_status = chr(int(GroupID))
# mit link state = 1
#message__link_status = '\x01'
# the sender's mac-address
message__mac = '\x00\x00\x00\x00\x00\x00'

data = message__FirstPart + message__event_par + message__filler + message__link_status + message__mac

Thanks !

A: Strings in Java are made up of char, not byte.  Though a char is really just two bytes, it is interpreted as UTF-16 and this can cause all sorts of trouble when you really want to talk about a series of bytes as it appears in your example.
You can express literal bytes as hexadecimal in Java as 0x00, 0x01, ..., 0xFF though these usually get interpreted as int and must be cast to byte:
byte[] arr = new byte[] { (byte) 0x01, (byte) 0x02 };

You can also look into the ByteBuffer class for assembling streams of bytes.


text:
Q: Optional arguments in S4 generics dbGetQuery is an S4 generic in RMongo. It is declared as
dbGetQuery(rmongo.object, collection, query, skip=0, limit=1000)

With a function like this in R, skip and limit are optional arguments. However, when I call it in this way
dbGetQuery(mongo, 'changesPerTypeEpoch', '{}', limit=10000)

I get an error:

Error in (function (classes, fdef, mtable)  :
    unable to find an inherited method for function 'dbGetQuery' for signature '"RMongo", "character", "character", "missing", "numeric"'

Looking at the source code, I found there are two signatures defined for the generic:
signature(rmongo.object="RMongo", collection="character", query="character", skip='numeric', limit='numeric')
signature(rmongo.object="RMongo", collection="character", query="character", skip='missing', limit='missing')

So in order to make it work without passing skip, it needs to have another signature:
signature(rmongo.object="RMongo", collection="character", query="character", skip='missing', limit='numeric')

However, that makes me feel uncomfortable, because in order to make n optional arguments in a S4 generic, one has to define 2^n signatures. Is there any better way to define optional arguments in S4 generic?

A: A generic can limit the number of arguments on which dispatch actually occurs (using the 'signature' argument to setGeneric) (e.g., 'skip' and 'limit' will never be anything other than a numeric, so should not be included in dispatch. It's not unusual for optional arguments to appear after '...' (they need to be spelled in full, instead of being matched by position, but being explicit seems like a good idea here; '...' are needed to allow methods to expose their own additional arguments)
setGeneric("fancy",
    function(x, y, ..., z=1, verbose=TRUE) standardGeneric("fancy"),
    signature=c("x", "y"))

One can also write methods for class 'ANY', although that's a pretty confident promise. Probably it would be better for RMongo to use the generics from the DBI package.


text:
Q: What is the fastest hash + salt for IP adresses? (Node.JS) There are quite many requirements right now about tracking of user information like unique user visits, returning users, etc..
The problem is that in some countries the IP address is considered as sensitive personal information.
So - to keep still unique users on the website, I would like to store hashed IP address in the DB. Of course it should be

*

*Fast (because this transaction is made on each page request)

*Salted (So that government can not compain that it is reversible)

Thanks for your advices
Bukso

A: There is no perfect hash encryption method. It all depends on your system configurations and settings. For the best result that suits your need, you can run a benchmark test against all hash methods and can evaluate yourself.
The code to run the benchmark is as follows
const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;
const hash = require('crypto').createHash;
const data = 'Delightful remarkably mr on announcing themselves entreaties favourable. About to in so terms voice at. Equal an would is found seems of. The particular friendship one sufficient terminated frequently themselves. It more shed went up is roof if loud case. Delay music in lived noise an. Beyond genius really enough passed is up.';
const scenarios = [
  { alg: 'md5', digest: 'hex' },
  { alg: 'md5', digest: 'base64' },
  { alg: 'sha1', digest: 'hex' },
  { alg: 'sha1', digest: 'base64' },
  { alg: 'sha256', digest: 'hex' },
  { alg: 'sha256', digest: 'base64' }
];
for (const { alg, digest } of scenarios) {
  suite.add(`${alg}-${digest}`, () =>
    hash(alg).update(data).digest(digest)
  );
}
suite.on('cycle', function (event) {
  console.log(String(event.target));
})
  .on('complete', function () {
    console.log('Fastest is ' + this.filter('fastest').map('name'));
  })
  .run();

For more related details you can follow the following blog article
https://medium.com/@chris_72272/what-is-the-fastest-node-js-hashing-algorithm-c15c1a0e164e