text:
Q: Mudar a cor de uma jProgressBar Como posso mudar a cor a minha ProgressBar, ela fica sempre um alaranjado meio esquisito, tentei usar esse código mas não funcionou:
UIManager.put("ProgressBar.background", Color.orange);
UIManager.put("ProgressBar.foreground", Color.blue);
UIManager.put("ProgressBar.selectionBackground", Color.red);
UIManager.put("ProgressBar.selectionForeground", Color.green);

A: Essas propriedades precisam estar definidas antes de criar o JProgressBar. Por exemplo:
UIManager.put("ProgressBar.background", Color.orange);
UIManager.put("ProgressBar.foreground", Color.blue);
UIManager.put("ProgressBar.selectionBackground", Color.red);
UIManager.put("ProgressBar.selectionForeground", Color.green);

JProgressBar progress = new JProgressBar();
getContentPane().add(progress);

Se for o caso de precisar alterar a cor após o componente ter sido criado ou fazer essa mudança de cores baseando-se na porcentagem de progresso, as soluções dessa pergunta (en) podem resolver.
Segue um exemplo, utilizando as propriedades que postou junto a pergunta. Eis o resultado:

Coloquei em uma thread só para mostrar a porcentagem da barra aumentando.
import java.awt.*;
import javax.swing.*;

public class Window extends JFrame implements Runnable {

    private final JProgressBar progress;

    public Window(String title) throws HeadlessException {
        super(title);
        setSize(300, 80);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        UIManager.put("ProgressBar.background", Color.orange);
        UIManager.put("ProgressBar.foreground", Color.blue);
        UIManager.put("ProgressBar.selectionBackground", Color.red);
        UIManager.put("ProgressBar.selectionForeground", Color.green);

        progress = new JProgressBar();
        progress.setStringPainted(true); // para mostrar a porcentagem como texto na barra
        getContentPane().add(progress);
        new Thread(this).start();
    }

    @Override
    public void run() {
        for(int i = 0; i < 100; i++){
            progress.setValue(i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {}
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new Window("stackoverflow pt").setVisible(true);
        });
    }
}


text:
Q: uninitialized constant Users ruby on rails I have an app that I am working on, and there appear to be two key problems: due to a problem undetectable by me, the webapp I am working on returns the error "uninitialized constant Users" and the error "uninitiallized constant SubmitController." The code for the webapp is here. I have tried renaming multiple, possibly violating variables, and attempted to rid the app of the errors. However, I have not been sucessful. The code where the errors most likely originate are from app/views/users/show.html.erb, app/views/users/show.html.erb, app/controllers/user/submit.html.erb, app.controllers/user/submit_controller.rb, app/models/Submit.rb, app/models/user.rb, app/controllers/users_controller.rb, config/routes.rb.
Thanks in advance.

A: You have error because you don't have SubmitsContoller. Also you need to move app/controller/users/submit.erb to views folder. And one more rename file Submit.rb to submit.rb.
And to make it works create submit_controller.rb in controller folder.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the best feature detector and descriptor extractor to use for disease diagnosis? My Android application, as part of my final project, utilizes OpenCV for digital image processing (disease detection and classification, to be exact). Specifically, I used SIFT algorithm to match features from two different images, but I found out that the disease detection is inaccurate and inconsistent.
I would like to ask: what do you think is the best algorithm to use for this purpose? Specifically, what algorithm ensures both consistency and accuracy regardless of illumination, orientation, rotation, and scaling?
Edit: I wish to compare, for example:
this image of a durian trunk showing severe image and this image showing a similar feature. What would be the best algorithm to use for comparing two different images with SIMILAR features?


text:
Q: Form elements array extract id With JavaScript i retrieve an array of form elements.
[
    input#NOM.form-control.input-md,
    input#SURNAME.form-control.input-md,
    input#AGE.form-control.input-md, input#ADDRESS.form-control.input-md,
    input#GENDER.form-control.input-md, input#COUNTRY.form-control.input-md
]

I'm trying to extract the id from it. I tried to use forEach without success.
My code to get this data is the following :
const getAllFormElements = element =>
    Array.from(element.elements)
        .filter(tag => ["select", "textarea", "input"]
            .includes(tag.tagName.toLowerCase()));
const pageFormElements = getAllFormElements(document.getElementById("requestForm"));
console.log(pageFormElements);

Here is my form (very classical) :
<form class="form-horizontal" id="requestForm">

                NOM

                    <input id="NOM" name="NOM" type="text" class="form-control input-md">

        ...

                GENDER

                    <input id="GENDER" name="GENDER" type="text" class="form-control input-md">

                    <button id="btnOk" name="btnOk" class="btn btn-primary">Button</button>

</form>

const getAllFormElements = element =>
  Array.from(element.elements)
  .filter(tag => ["select", "textarea", "input"]
    .includes(tag.tagName.toLowerCase()));
const pageFormElements = getAllFormElements(document.getElementById("requestForm"));
console.log(pageFormElements);
<form class="form-horizontal" id="requestForm">

        NOM

          <input id="NOM" name="NOM" type="text" class="form-control input-md">

    ...

        GENDER

          <input id="GENDER" name="GENDER" type="text" class="form-control input-md">

          <button id="btnOk" name="btnOk" class="btn btn-primary">Button</button>

</form>


text:
Q: select dates that are between current date and 3 month from the current date in mysql I want to select all dates that are between the current date and 3 months before.
I tried using this query but it isn't working right.
$sql = mysql_query("
    SELECT *
    FROM date
    WHERE d_date BETWEEN NOW() AND NOW() - INTERVAL 3 MONTH
");

Please if you could help me write the right syntax.

A: You need to swap your bounaries, and it will work:
SELECT * FROM date
WHERE d_date BETWEEN now() - INTERVAL 3 MONTH AND now()

For example, this query returns true (SQLFiddle):
SELECT (now() - interval 1 month)
    BETWEEN now() - interval 3 month AND now()

A: SELECT * FROM Table
WHERE anydate_col BETWEEN NOW() AND DATE_ADD( NOW() , INTERVAL +3 MONTH)


text:
Q: How to pipe from Command to File? Let's say I have:
fn pipe(cmd: &mut std::process::Command, file: &mut File) {
}

I want to somehow pipe from cmd.stdout to file without storing everything into an intermediary buffer. I'm trying stuff out with BufReader but I feel like I'm missing something.


text:
Q: Why iosnoop (IO snooping files on disk) returns paths with question marks? If I'm running
sudo iosnoop | grep "gem"

and then in another terminal run
gem env

in the iosnoop terminal I see:
dtrace: error on enabled probe ID 4 (ID 1106: io:mach_kernel:buf_strategy:start): illegal operation in action #3 at DIF offset 0
dtrace: error on enabled probe ID 4 (ID 1106: io:mach_kernel:buf_strategy:start): illegal operation in action #3 at DIF offset 0
dtrace: error on enabled probe ID 4 (ID 1106: io:mach_kernel:buf_strategy:start): illegal operation in action #3 at DIF offset 0
dtrace: error on enabled probe ID 4 (ID 1106: io:mach_kernel:buf_strategy:start): illegal operation in action #3 at DIF offset 0
dtrace: error on enabled probe ID 4 (ID 1106: io:mach_kernel:buf_strategy:start): illegal operation in action #3 at DIF offset 0
...
dtrace: error on enabled probe ID 4 (ID 1106: io:mach_kernel:buf_strategy:start): illegal operation in action #3 at DIF offset 0
  501 54406 R 21523616    512       bash ??/bin/gem
  501 94092 R 141320288   4096       bash ??/bin/gem
  501 94092 R 141320168   4096       ruby ??/1.8/rubygems.rb
  501 94092 R 141320208   4096       ruby ??/1.8/rubygems.rb
  501 94092 R 141319208   4096       ruby ??/rubygems/errors.rb
  501 94092 R 141319856   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319864   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319872   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319888   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319896   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319904   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319928   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319936   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141319944   4096       ruby ??/rubygems/specification.rb
  501 94092 R 141320176   4096       ruby ??/1.8/rubygems.rb
  501 94092 R 141320184   4096       ruby ??/1.8/rubygems.rb
  ...

What are the question marks near ruby in the path to the files are treated:
ruby ??/1.8/rubygems.rb

? And how can I find the absolute path to all these files?
Additional question - why are the errors here:
dtrace: error on enabled probe ID 4 (ID 1106: io:mach_kernel:buf_strategy:start): illegal operation in action #3 at DIF offset 0

?

A: While the answer above gives a good technical background, if you just want to get the full pathname of opened files I'm able to do this using raw DTrace on OS X via:
sudo dtrace -n 'syscall::open*:entry { printf("%s %s",execname,copyinstr(arg0)); }'

This will show file opens, but not reads or writes. I got this from Brendan Gregg's handy DTrace one liners page:
http://www.brendangregg.com/DTrace/dtrace_oneliners.txt
Sadly, I still don't understand why iosnoop isn't giving the full path, when it appears that it is theoretically possible.

A: The short answers are:

*

*The ?? signify that the remaining pathname is unknown,

*you can't extract the absolute path and

*this is a feature, not a bug, of DTrace on OS X.

An explanation of these points requires some familiarity with DTrace;
if appropriate then start with the introduction to the Solaris version.
iosnoop is a script that exploits the DTrace observability
framework.  In particular, it uses the io provider's start
and done probes;  the start probe exposes a request's bufinfo_t,
the target device's devinfo_t and the corresponding file's
fileinfo_t.  The fileinfo_t is not a native Darwin type:
it is a structure provided by dtrace(1) that provides a
convenient abstraction of a file for the benefit of users.
For example, amongst its members is fi_pathname, which
should give the full pathname of a file.
Having an abstracted description shields users, and their
scripts, from knowledge of and changes to the underlying
implementation of the operating system.  In theory, it also allows for a
single script to run on different operating systems
altogether.
A fileinfo_t is constructed and populated dynamically
using a DTrace translator described in /usr/lib/dtrace/io.d.
This shows the transformation from the OS-specific types
to the abstraction.  In the case of Snow Leopard I see that
fi_pathname is constructed from the string "??/" followed by
some derivates of the IO buffer.  I'm no Darwin expert but
I infer that it simply doesn't record full pathnames in its
vnodes.  This, hence, is the origin of the "??" in the output
of your script and also the reason why I assume that the absolute
pathnames are unavailable.
Finally, your DTrace errors.  For whatever reasons, Apple's
port of DTrace is subtly crippled in that it precludes tracing
of various processes, and the error message that you see is
a characteristic symptom.  Specifically, the complaint is about
the line
start_uid[this->dev, this->blk] = (int)uid;

and it turns out that (again, on Snow Leopard), trying to evaluate
uid on any of the launchd, diskimages-help and kernel_task
processes results in exactly this error.  I presume that these
processes are "out of bounds" and the errors that you see are
the consequences of Apple's modifications.


text:
Q: Is it possible to trace the last updated password in the embedded LDAP for Weblogic? For security reason we want to see the last password change for each user within the embedded LDAP server on Weblogic.
Is that possible?


text:
Q: Git - Find files whose commit messages contain a particular string I've been able to print the all the logs that contain a particular string in their commit messages using:
git log --grep=<string>

Is it possible to get a list of all the files affected in a similar way. viz. all the files that were affected by the commits that the previous command shows.

Based on Amber's post, a clearer output I was envisaging was something like this:
> git log -p --name-only --grep=<string>
a/b/c/d/e/f/a.java
a/b/c/d/e/f/b.java
a/b/c/d/e/c.java
a/b/c/f.java
a/b/c/d/e/f/s/t.java

As an aside, if there is a good place to start on learning git commands, please point me to it. Thanks.
Explanation on why this question is not a duplicate of other questions already asked: I don't want the commit content, just he files that were changed without duplicating the names of the files (if they were used in multiple commits).

A: Try adding -p --name-status to your git log command.

*

*-p tells git log to include a patch (diff) for each commit listed.

*--name-status tells the diff generation to only include the name and status (new, changed, renamed, removed, etc) for each file in the diff, rather than the full diff of changes for each file.

So that'd be, in your case...
git log -p --name-status --grep=<string>

If you don't care about how each file was affected, but just want the list of files touched, you could use --name-only instead of --name-status.
Interested in knowing more options for git log? Take a look at the git-log manpage, which should also be available via git help log in your terminal.
Nothing but a list of files
We can add a few more options to elide all of the commit information and then remove duplicate entries:
git log -p --name-only --format="" --grep=<string> | sort | uniq

This should result in output that is nothing but a unique list of files that were touched by at least one commit matching the grep string.


text:
Q: Tooltip glitchy/repeating I'm new to javascript, so I have a feeling I may of set this up wrong—I'm trying to make an opening page that features a short looping mp4 video; at the same time setting up the entire page to be a link; all the while having the cursor set to pointer with a constant tooltip displayed. It all seems to be working, except the tooltip is stuttering, freezing, repeating across the page occasionally. I'd greatly appreciate any insight or ways to set this up better, alternative ways to approach it?
Many,
many thanks.
Sample code here: https://github.com/rrrhhhhhhhhh/opener
Page here: https://rrrhhhhhhhhh.github.io/opener/

A: In the tooltip.js file use mouseEnter event instead of mouseOver (which is slower) and create a variable that tells if the mouse is 'In' or 'Out', here's the js code:

function initTooltip() {
    const tooltips = Array.from(document.querySelectorAll('[data-tooltip-container]'));
    let mouseIn = true;

    tooltips.map(tooltip => {
        tooltip.addEventListener('mouseenter', handleMouseEnter);
    })

    function handleMouseEnter() {
        mouseIn = true;
        const tooltipbox = createTooltipBox(this);

        handleMouseMove.tooltipbox = tooltipbox;
        this.addEventListener('mousemove', handleMouseMove);

        handleMouseLeave.tooltipbox = tooltipbox;
        handleMouseLeave.element = this;
        this.addEventListener('mouseleave', handleMouseLeave);
    }

    const handleMouseLeave = {
        handleEvent() {
            mouseIn = false;
            this.tooltipbox.remove();
            this.element.removeEventListener('mousemove', handleMouseMove);
            this.element.removeEventListener('mouseleave', handleMouseLeave);
        }
    }

    const handleMouseMove = {
        handleEvent(e) {
            if(!mouseIn){
                return;
            }
            this.tooltipbox.style.top = e.clientY + 25 + 'px';
            this.tooltipbox.style.left = e.clientX + 13 +'px';
        }
    }

    function createTooltipBox(el) {
        let tooltip = document.createElement('div');
        tooltip.innerText = el.getAttribute('data-tooltip-label');
        tooltip.classList.add('tooltip');

        document.body.appendChild(tooltip);

        return tooltip;
    }
}

initTooltip();


text:
Q: Cannot set UltraGrid Checkbox value to True after saving the initial data My project contains a form which allows the entering of orders, using an UltraGrid.
One column is a checkbox style column, to represent whether or not the order has been delivered.
When the order reaches 'Stage 4 - Awaiting Goods Delivery', the user can set the column value to True, which in turn prompts a new window, to allow the user to enter the volume and value of the delivery.
If the order hasn't been fully delivered, the checkbox is set back to False, and the order line turns yellow (Eg; 5 gates have been ordered, but only 3 delivered = False, but a yellow order line).
After saving the order, closing it and going back into it, I'm trying to set the Checkbox to True, to update the order to add on the rest of the delivery (the final 2 gates have been delivered), but as soon as I set it to True, it instantly becomes False again (When stepping through the following code in the CellChange method, it says the cell value is False too).
So, why can I only change the value once? After it's been saved, why can the value then not be changed again? Is it do with the fact that it's saved as False in the database?
Try
  If e.Cell.Column.ToString = "Goods_Delivered" Then
     e.Cell.Row.Update()

       If e.Cell.Value = True Then
           If IsDBNull(e.Cell.Row.Cells("Final_Delivery").Value) Then
              MsgBox("Please enter a delivery date", MsgBoxStyle.OkOnly, "Invalid Date")
                    e.Cell.Row.Cells("Goods_Delivered").Value = False
           Else
            Dim f As New dlgDelivery(e.Cell.Row, Me, e.Cell.Row.Cells("Final_Delivery").Value, con, orderNumber, e.Cell.Row.Cells("Product_Code").Value, exTotal)
                f.ShowDialog()
           End If

           e.Cell.Row.Update()

        cmdCheck_Click(sender, New EventArgs)
        cmdTotals_Click(sender, New EventArgs)

  ElseIf e.Cell.Value = False Then
      ugProducts.ActiveRow.Cells("Final_Delivery").Value = DBNull.Value
       productCode = ugProducts.ActiveRow.Cells("Product_Code").Value
       database.NotDelivered(orderNumber, productCode, con)
     Exit Sub
  Else
  End If

A: The error within this was with e.Row.Update().
I was committing the value of the cell and then you are SETTING the value of the cell, which was causing CellChange to fire again recursively, and after that I'm not sure what happens, but there was more effective ways of writing this code.
Try
  If e.Cell.Column.Key = "Goods_Delivered" Then
   Dim goodsDelivered As Boolean = Boolean.Parse(e.Cell.Text)
     If goodsDelivered = True Then
      If IsDBNull(e.Cell.Row.Cells("Final_Delivery").Value) Then
       MsgBox("Please enter a delivery date", MsgBoxStyle.OkOnly, "Invalid Date")
       Dim checkEditor As CheckEditor = e.Cell.EditorResolved
       checkEditor.Value = False
      Else
       Dim f As New dlgDelivery(e.Cell.Row, Me, e.Cell.Row.Cells("Final_Delivery").Value, con, orderNumber, e.Cell.Row.Cells("Product_Code").Value, exTotal)
       f.ShowDialog()
      End If
     ElseIf goodsDelivered = False Then
       ugProducts.ActiveRow.Cells("Final_Delivery").Value = DBNull.Value
                productCode = ugProducts.ActiveRow.Cells("Product_Code").Value
                database.NotDelivered(orderNumber, productCode, con)
             Exit Sub
         End If
      End If

Catch ex As Exception
   errorLog(ex)

 End Try


text:
Q: Is it possible to avoid locking overhead when sharing dicts between threads in Python? I have a multi-threaded application in Python where threads are reading very large (so I cannot copy them to thread-local storage) dicts (read from disk and never modified). Then they process huge amounts of data using the dicts as read-only data:
# single threaded
d1,d2,d3 = read_dictionaries()
while line in stdin:
    stdout.write(compute(line,d1,d2,d3)+line)

I am trying to speed this up by using threads, which would then each read its own input and write its own output, but since the dicts are huge, I want the threads to share the storage.
IIUC, every time a thread reads from the dict, it has to lock it, and that imposes a performance cost on the application. This data locking is not necessary because the dicts are read-only.
Does CPython actually lock the data individually or does it just use the GIL?
If, indeed, there is per-dict locking, is there a way to avoid it?

A: Multithreading processing in python is useless. It's better to use multiprocessing module. Because multithreading can give positive effort only in lower number of cases.

Python implementation detail: In CPython, due to the Global
  Interpreter Lock, only one thread can execute Python code at once
  (even though certain performance-oriented libraries might overcome
  this limitation). If you want your application to make better use of
  the computational resources of multi-core machines, you are advised to
  use multiprocessing. However, threading is still an appropriate model
  if you want to run multiple I/O-bound tasks simultaneously.
  Official documentation.

Without any code examples from your side I can only recommend to split your big dictionary on several parts and process every part using Pool.map. And merge results in main process.
Unfortunately, it's impossible to share a lot of memory between different python processes effective (we are not talking about shared memory pattern based on mmap). But you can read different parts of your dictionary in different processes. Or just read entire dictionary in main process and give a small chunks to child processes.
Also, I should warn you that you should be very carefully with multiprocessing algorithms. Because every extra megabytes will be multiplied on number of process.
So, based on your pseudocode example I can assume two possible algorithm based on compute function:
# "Stateless"
for line in stdin:
    res = compute_1(line) + compute_2(line) + compute_3(line)
    print res, line

# "Shared" state
for line in stdin:
    res = compute_1(line)
    res = compute_2(line, res)
    res = compute_3(line, res)
    print res, line

In first case, you can create a several workers, read each dictionary in separate worker based on Process class (it's good idea to decrease memory usage for each process), and compute it like a production line.
In second case, you have a shared state. For each next worker you need a result of previous one. It's worst case for multithreading/multiprocessing programming. But you can write algorithm there several workers are using same Queue and pushing result to it without waiting finish of all cycle. And you just share a Queue instance between your processes.


text:
Q: Не записываются данные в SQlite Введенные данные не записываются в БД. Где ошибка?
Проект на гитхаб.
Сам класс:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

public static final String TAG = "Log_d";

dbHelper mDatabaseHelper;
SQLiteDatabase mSqLiteDatabase;

Button btnAdd;
Button btnClear;
Button btnRead;
EditText Email;
EditText Name;
TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Email = (EditText) findViewById(R.id.editEmail);
    Name = (EditText) findViewById(R.id.editName);

    btnAdd = (Button) findViewById(R.id.btnAdd);
    btnRead = (Button) findViewById(R.id.btnRead);
    btnClear = (Button) findViewById(R.id.btnClear);

    textView = (TextView) findViewById(R.id.textView);

    btnAdd.setOnClickListener(this);
    btnRead.setOnClickListener(this);
    btnClear.setOnClickListener(this);

    Log.d(TAG, "Кнопки определены");

    //так как в классе dbHelp описаны два (три ?) конструктора мы можем воспользоваться одним из них
    //mDatabaseHelper = new dbHelper(this, "mydatabase.db", null, 1);
    mDatabaseHelper = new dbHelper(this);
    mSqLiteDatabase = mDatabaseHelper.getWritableDatabase();
    Toast.makeText(getApplicationContext(), "База данных создано только что", Toast.LENGTH_SHORT).show();

}

@Override
public void onClick(View v) {
    Log.d(TAG, "Зашли в онклик");

    switch (v.getId()) {
        case R.id.btnAdd:
            Log.d(TAG, "Нажата кнопка ADD");
            /*if (mSqLiteDatabase.equals(null)){
                mDatabaseHelper = new dbHelper(this);
                mSqLiteDatabase = mDatabaseHelper.getWritableDatabase();
            }*/

            ContentValues values = new ContentValues();
            // Задайте значения для каждого столбца
            values.put(dbHelper.DB_TEBLE_NAME_COLUMN_NAME, Name.getText().toString());
            values.put(dbHelper.DB_TEBLE_NAME_COLUMN_EMAIL, Email.getText().toString());
            // Вставляем данные в таблицу
            mSqLiteDatabase.insert(dbHelper.DB_TEBLE_NAME, null, values);

            Toast.makeText(this, "Данные записаны в таблицу!" + Name.getText().toString() + Email.getText().toString(), Toast.LENGTH_LONG).show();
            //Log.d(TAG, "Имя: " + dbHelper.DB_TEBLE_NAME_COLUMN_NAME + " Почта: " + dbHelper.DB_TEBLE_NAME_COLUMN_EMAIL);
            Log.d(TAG, "Имя: " + Name.getText().toString() + " Почта: " + Email.getText().toString());
            Name.setText("");
            Email.setText("");
            break;
        case R.id.btnRead:
            Log.d(TAG, "Зашли в Read");
            //Cursor cursor = mSqLiteDatabase.query(dbHelper.DB_TEBLE_NAME, new String[]{dbHelper.DB_TEBLE_NAME_COLUMN_NAME,
                    //dbHelper.DB_TEBLE_NAME_COLUMN_EMAIL}, null, null, null, null, null, null);

            Cursor cursor =mSqLiteDatabase.query(dbHelper.DB_TEBLE_NAME, null,null,null,null,null,null);

            if (cursor.moveToFirst()) {
                boolean bool = cursor.moveToFirst();
                Log.d(TAG," "+bool);
                do {
                    Log.d(TAG,
                            "ID " + cursor.getInt(cursor.getColumnIndex(dbHelper._ID)) +
                                    ", NAME " + cursor.getString(cursor.getColumnIndex(dbHelper.DB_TEBLE_NAME_COLUMN_NAME)) +
                                    ", EMAIl " + cursor.getString(cursor.getColumnIndex(dbHelper.DB_TEBLE_NAME_COLUMN_EMAIL)));
                } while (cursor.moveToNext());
            } else {
                Log.d(TAG, "В базе нет данных!");
            }

            cursor.close();
            break;

        case R.id.btnClear:
            mSqLiteDatabase.delete(dbHelper.DB_TEBLE_NAME,null,null);
            Log.d(TAG,"Таблица " + dbHelper.DB_TEBLE_NAME +" удалена!");
            break;
        }
    }
}

Обертка
public class dbHelper extends SQLiteOpenHelper implements BaseColumns {
    public static final String DB_NAME = "MyDB.db";
    public static final int DB_VERSION = 1;
    public static final String DB_TEBLE_NAME = "Tebel_Name";
    public static final String DB_TEBLE_NAME_COLUMN_NAME = "Name";
    public static final String DB_TEBLE_NAME_COLUMN_EMAIL = "Mail";
    //public static final String DB_TEBLE_NAME_COLUMN_Age = "Age";

    private static final String DATABASE_CREATE_SCRIPT = "create table "
        + DB_TEBLE_NAME + " (" + BaseColumns._ID
        + " integer primary key autoincrement, " + DB_TEBLE_NAME_COLUMN_NAME
        + " text not null, " + DB_TEBLE_NAME_COLUMN_EMAIL + " text);";

    dbHelper(Context context){
        super(context, DB_NAME,null,DB_VERSION);

    }

    public dbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
    }

    public dbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DATABASE_CREATE_SCRIPT);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Запишем в журнал
        Log.w("SQL", "Обновляемся с версии " + oldVersion + " на версию " + newVersion);

        // Удаляем старую таблицу и создаём новую
        db.execSQL("DROP TABLE IF IT EXISTS " + DB_TEBLE_NAME);
        // Создаём новую таблицу
        onCreate(db);
    }
}

<?xml version="1.0" encoding="utf-8"?>

<EditText
    android:id="@+id/editName"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:ems="10"
    android:hint="Введите имя"
    android:inputType="textPersonName" />

<EditText
    android:id="@+id/editEmail"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignEnd="@+id/editName"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignRight="@+id/editName"
    android:layout_below="@+id/editName"
    android:ems="10"
    android:hint="Введите Ваш Email"
    android:inputType="textEmailAddress" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Add"
    android:id="@+id/btnAdd"
    android:layout_below="@+id/editEmail"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Read"
    android:id="@+id/btnRead"
    android:layout_alignBottom="@+id/btnAdd"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Clear"
    android:id="@+id/btnClear"
    android:layout_below="@+id/editEmail"
    android:layout_alignRight="@+id/editEmail"
    android:layout_alignEnd="@+id/editEmail" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:id="@+id/textView"
    android:layout_below="@+id/btnAdd"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignRight="@+id/btnClear"
    android:layout_alignEnd="@+id/btnClear" />

A: Код с гитхаба, и пишет и читает. Удалите приложение с устройства и установите заново. Если делали изменения в базе и не выполняли upgrade версии или не удаляли приложения для пересоздания базы, такие ошибки возникают.


text:
Q: How can I delay the changing of a watched variable that is tied to an  field I set up a watch expression that watches some data that is entered into an input field that is backed up by the $scope.pid
  $scope.$watch("pid", function (pid) {
        if (pid == null || pid === "") {
            $scope.pidLower = null;
            $scope.pidUpper = null;
        }
        else if (pid.indexOf("-") > 0) {
            pid = pid.split("-");
            $scope.pidLower = parseInt(pid[0]);
            $scope.pidUpper = parseInt(pid[1]);
        }
        else {
            $scope.pidLower = parseInt(pid);
        }
    });

It works good but once the pidLower or pidUpper change then there are more functions that are called and some heavy processing. The result is that I have to wait a short time in between entering numbers into the input field.
Is there a way I can add some kind of timeout to this so that the watch function code does not change anything until the information entered into the input field has not changed for three seconds?

A: You can use the $timeout service for this. After you've injected this service into your controller you can do the following:
var parsePid = function() {...};

$scope.$watch("pid", function (pid) {
   if($scope.timeoutPromise) {
      $timeout.cancel($scope.timeoutPromise);
   }
   $scope.timeoutPromise = $timeout(function() {
      parsePid();
   }, 3000);
});

A: I think you want to validate your input before further processing. Instead of watching pid you can add filter. In filter you can change $scope.pidLower and $scope.pidUpper based on some condition , which will trigger your further heavy processing. Refer $filter for details.


text:
Q: makeTouchBar() not being called Mac Catalyst touchbar hoping you can help, I'm going a bit mad with this. I have an Objective-c iOS project I am porting over top MacOS using Catalyst. All has been going well until I have got to adding Touchbar support.
I have a swift extension of my main viewController, in which I am implementing the required delegate methods for NSTouchBarDelegate
Problem is, makeTouchBaris never called, either in the Swift extension :
@objc override open func makeTouchBar() -> NSTouchBar? {
     let touchBar = NSTouchBar()
      touchBar.delegate = self
      touchBar.defaultItemIdentifiers = [...identifiers...]
      return touchBar
    }

or just in the original Obj-C viewController :
- (NSTouchBar *)makeTouchBar {
    return ...;
}

I've followed multiple tutorials which all basically say 'override makeTouchBar and it will all magically work'. I am successfully adding Toolbars and Menu's to the app, so I'm a bit stumped what's going on and why this method is never getting called by the system.
Any help would be much appreciated
Cheers
Emile

A: I had a similar problem, which caused by my SceneDelegate implementing NSTouchBarDelegate. Instead, I should have had my AppDelegate implementing NSTouchBarDelegate.
Here is a working example to add a Touchbar to a SwiftUI Catalyst 13.0 app:
//
//  TouchbarDelegate.swift
//  TenderHub
//
//  Created by Peter Chapman on 5/08/20.
//  Copyright © 2020 Conglomo Limited. All rights reserved.
//

import UIKit

#if targetEnvironment(macCatalyst)
extension NSTouchBarItem.Identifier {
    static let play = NSTouchBarItem.Identifier("play")
    static let trash = NSTouchBarItem.Identifier("trash")
}

extension AppDelegate: NSTouchBarDelegate {

    override func makeTouchBar() -> NSTouchBar? {
        let touchBar = NSTouchBar()
        touchBar.delegate = self

        touchBar.defaultItemIdentifiers = [
            .flexibleSpace,
            .play,
            .trash,
            .flexibleSpace
        ]

        return touchBar
    }

    func touchBar(_ touchBar: NSTouchBar, makeItemForIdentifier identifier: NSTouchBarItem.Identifier) -> NSTouchBarItem? {
        let touchBarItem: NSTouchBarItem?

        switch identifier {
        case .play:
            guard let image = UIImage(systemName: "play") else { return nil }
            touchBarItem = NSButtonTouchBarItem(identifier: identifier,
                                                image: image,
                                                target: UIApplication.shared.openSessions.first?.scene?.delegate,
                                                action: #selector(SceneDelegate.play(_:)))

        case .trash:
            guard let image = UIImage(systemName: "trash") else { return nil }
            touchBarItem = NSButtonTouchBarItem(identifier: identifier,
                                                image: image,
                                                target: UIApplication.shared.openSessions.first?.scene?.delegate,
                                                action: #selector(SceneDelegate.trash(_:)))
        default:
            touchBarItem = nil
        }

        return touchBarItem
    }
}
#endif


text:
Q: Based on construct create or delete some methods Based on constructor of the class. create or destroy new methods.
I often  requires based on construct to disable or destroy methods within the class.
Can any one help me out?
class Test
{
  function __construct(userID)
  {
     if(!isValidUser($userID))
     { destroy(methods); }
  }
  function addPost()
  {

  }
}

Once destroy is called. The methods or selected methods should be destroyed
Hope you understand this time.

A: You can use the factory pattern to create an instance of a subclass of the class. Each subclass has the methods it needs. The superclass only has the methods every subclass needs.
class User
{
    function foo(){}
    function foo1(){}
    static function constructUser()
    {
        if(self::isValidUser())
        {
            return new ValidUser();
        }
        else
        {
            return new User();
        }
    }

    static function isValidUser()
    {
        //...
    }
}

 class ValidUser extends User
 {
    function addItem(){}
 }

 $user = User::constructUser();

A: I have the feeling that you are in need of the Factory pattern: an object (or function) that creates objects of different types, depending upon it's arguments.
Because what you really do when defining a different set of methods, depending on the user, is  creating objects of another type:  an AuthenticatedUser object vs. a NonAuthenticatedUser.
Using a constructor of ClassX for that is really not a good approach.
class User {  // with common methods
}

class ValidUser extends User {
     function onlyForValid() {}
}

class InvalidUser extends User {
     function onlyForInvalid() {}
}

function createObject( $id ){
    if( isValidUser( $id ) ) return new ValidUser( $id );
    else return new InvalidUser( $id );
}

A: There is no way to disable or destroy functions in PHP. You can approach this from the opposite end, however. That is, only create the functions if appropriate (i.e. using create_function()) within the constructor. Alternately, you can use a superclass and extend it using a subclass that only extends the functions that subclass needs. If you would like further illustration I can post an example for you.


text:
Q: How to get data from Infobox in Wikipedia? I want to know how to get data from infobox of Wikipedia in the right side, and how to put it in table in my website. I found this code that can get data and parse HTML, but I don't know how to put it in my own design.
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=Niger&rvsection=0&rvparse";
$data = json_decode(file_get_contents($url), true);
$data = current($data['query']['pages']);
$regex = '#<\s*?table\b[^>]*>(.*)</table\b[^>]*>#s';
$code = preg_match($regex, $data["revisions"][0]['*'], $matches);
echo($matches[0]);

A: You can do it with a url call to the Wikipedia API like this:-
http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=xmlfm&titles=Scary%20Monsters%20and%20Nice%20Sprites&rvsection=0

Replace the titles= section with your page title, and format=xmlfm to format=json if you want the article in json format.


text:
Q: Conditional Expectation, is this true? I'd like to know if this statement is true:
$$
\mathbb{E}[f(X)|X\in A] = \int f(X) \mathbb{I}_{(X\in A)} dP
$$
for any $f(X)$ and $X$ random variables and $A\subset\mathbb{R}$.

A: It's not true; just take $A$ to be an event with probability zero.
For example consider $X \sim U[0, 1]$, $f = \text{id}_\mathbb{R}$ and $A = \{\frac{1}{2}\}$. Then the left-hand side is $\frac{1}{2}$ and the right-hand side is zero.


text:
Q: Using Table of Contents/Legend Widget of ArcGIS API for JavaScript I was hoping someone might be able to take a look at my code and point out why this might not be working. I'm trying to use the Table of Contents (TOC)/Legend Widget for JavaScript API.
I thought at first that I wasn't linking properly to the stylesheet, so I ended up using their online hosted version. I also thought it might be an issue with not calling dijits/functions in the right order.
<!DOCTYPE html>

<title>Map</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<link rel="stylesheet" href="http://js.arcgis.com/3.8/js/dojo/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.8/js/esri/css/esri.css">
<link rel="stylesheet" type="text/css" href="http://gmaps-utility-gis.googlecode.com/svn/tags/agsjs/latest/build/agsjs" />

A: It looks like you just had some JavaScript errors.
You were missing commas in your layerInfos:
layerInfos:
    [{layer: BOE30,
      title: "BOE30",
      slider: true},
     {layer: APESections,
      title: "Sections",
      slider: true},
     {layer: NDMTWellBores,
      title: "ND, MT Well Bores"},
     {layer: EOXDSUs,
      title: "EOX DSUs"},
     {layer: Rigs,
      title: "Rig Locations"},
     {layer: EOXWellBores,
      title: "EOX Well Bores"},
     {layer: Activity,
      title: "Activity (Recent Completed/Permitted/Spud)",
      slider: true}
    ]

And you were missing "esri/layers/ArcGISDynamicMapServiceLayer" in the require section:
require(["dojo/_base/connect",
     "dojo/parser",
     "dojo/on",
     "esri/map",
     "agsjs/dijit/TOC",
     "esri/layers/ArcGISDynamicMapServiceLayer",
     "dojo/fx",
     "dijit/layout/AccordionContainer",
     "dijit/layout/BorderContainer",
     "dijit/layout/ContentPane",
     "dojo/domReady!"],
     function(connect, parser, on, Map, TOC, ArcGISDynamicMapServiceLayer)


text:
Q: Improve Linux kernel compile time by disabling specific modules I have to compile the Linux kernel quite frequently for a device with a limited use-case. Naturally, I don't need most of the modules of the Linux kernel. Is there a good way to determine which modules I can disable to improve the compile speed as much as possible.
I've already disabled a bunch of modules which I know I don't need. But I'd like to know which specific modules would give me the most gain in compilation speed.

A: You can build a .config appropriate for your system (more precisely, enabling only modules which are currently loaded) by running
make localmodconfig

if you want modules or
make localyesconfig

if you want a static build.
This will avoid building any modules which your system doesn't need, thus achieving your goal: "to improve the compile speed as much as possible".


text:
Q: Lispworks 7.0 load zeromq fail in Windows 10 I use the LispWorks7.0 to load the zeromq on my PC with windows 10, and got the error message as below:
    CL-USER 13 > (ql:quickload :zeromq)
To load "zeromq":
  Load 1 ASDF system:
    zeromq
; Loading "zeromq"
; gcc -o C:\Users\chaoqi\AppData\Local\common-lisp\cache\lw-7.0.0-win-x64\g\third_codes\quicklisp\dists\quicklisp\software\cl-zmq-20160318-git\src\grovel__grovel-tmpXOBV8AQ3.obj -c -m64 -Ig:\third_codes\quicklisp\dists\quicklisp\software\cffi_0.19.0\ C:\Users\chaoqi\AppData\Local\common-lisp\cache\lw-7.0.0-win-x64\g\third_codes\quicklisp\dists\quicklisp\software\cl-zmq-20160318-git\src\grovel__grovel.c

Error: Subprocess run with command ("gcc" "-o" "C:\\Users\\chaoqi\\AppData\\Local\\common-lisp\\cache\\lw-7.0.0-win-x64\\g\\third_codes\\quicklisp\\dists\\quicklisp\\software\\cl-zmq-20160318-git\\src\\grovel__grovel-tmpXOBV8AQ3.obj" "-c" "-m64" "-Ig:\\third_codes\\quicklisp\\dists\\quicklisp\\software\\cffi_0.19.0\\" "C:\\Users\\chaoqi\\AppData\\Local\\common-lisp\\cache\\lw-7.0.0-win-x64\\g\\third_codes\\quicklisp\\dists\\quicklisp\\software\\cl-zmq-20160318-git\\src\\grovel__grovel.c") exited with error code 1
  1 (continue) Retry PROCESS-OP on #<CFFI-GROVEL:GROVEL-FILE "zeromq" "src" "grovel">.
  2 Continue, treating PROCESS-OP on #<CFFI-GROVEL:GROVEL-FILE "zeromq" "src" "grovel"> as having been successful.
  3 Retry ASDF operation.
  4 Retry ASDF operation after resetting the configuration.
  5 (abort) Give up on "zeromq"
  6 Return to level 0.
  7 Return to top loop level 0.

Type :b for backtrace or :c <option number> to proceed.
Type :bug-form "<subject>" for a bug report template or :? for other options.

CL-USER 14 : 1 >

I'm sure that, I use my Vistual Studio 2015 and compiled the x64 version libzmq.dll and set the cffi path ok.
Because I use the ccl with lispbox install the zeromq and work fine, the output message as below:
CL-USER> (ql:quickload :zeromq)
To load "zeromq":
  Load 1 ASDF system:
    zeromq
; Loading "zeromq"

(:ZEROMQ)
CL-USER>

I want to known, why error message with gcc stuff and how to fix this.
As I know, it just loads the dll where the cffi:foreign-library-directories pointed.
Any help will be appreciated.


text:
Q: how to write shell script to get JRE version Hi I want to write a shell scripting which will return the installed JRE version. How to write shell script file to achieve the above.
If I write java -version then the application returns "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Server VM (build 14.0-b16, mixed mode)".
But I donot want any string. I want only jre version.
thanks
Sunil Kumar Sahoo

A: Following the idea behind monojohnny's answer, but using cut instead of awk:
java -version 2>&1 | head -n 1 | cut -d\" -f 2

A: If you want just the version (rather than the whole string), you can do something like:
-- Save this as (say) javaversion.sh
#!/bin/sh
# Changed code to remove the 'head -1' as per the suggestion in comment.
JAVA_VERSION=`java -version 2>&1 |awk 'NR==1{ gsub(/"/,""); print $3 }'`
# export JAVA_VERSION
echo $JAVA_VERSION

This gives:
$ 1.6.0_15

On my system (damn it, even more out of date !! :-) )
I found '2>&1' necessary on my system, since the output seems to go to 'stderr' rather than 'stdout'. (2>&1 = send the output of standard error to the standard out stream; in this case so we can go ahead and process with the head etc...).
The 'gsub' bit in the awk is necessary to remove the double-quotes in the string. (Global SUBstitue), $3 is the third field (awk defaults its field separator to white-space).
The "backticks" ( ` ) are used so we can capture the output - and then we store it on a variable.
[ Using 'cut' rather than 'awk' might be more elegant here - see GrzegorzOledzki's post.]

A: just use the shell
$ a=$(java -version 2>&1 >/dev/null)
$ set -- $a
$ echo $3
"1.6.0_0"

A: #!/bin/sh

java -version

A: Alternatively:
Write a Java class that accesses System Property "java.version": which will strip out some of the other formatting crap out of there and allow you to output to standard out rather than standard error.
Just have your shell script call it with a
java -cp <classpath> GetJavaVersion.class

A: Take a look at the output of
java -version

A: You can get the version of the installed JRE using the java command, with the -version switch :
$ java -version
java version "1.6.0_14"
Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
Java HotSpot(TM) Server VM (build 14.0-b16, mixed mode)


text:
Q: PyGears How to make counter I want to make a counter which can start counting at posedge of a specific signal (enable signal). And once it counts to 256, stop counting, set the counter to 0 and output something.

A: When designing with PyGears, you should try to think more in terms of functions (although asynchronous) that are being invoked by receiving commands via input interfaces. Instead of thinking of the enable signal that triggers the counter, try to think of a counter you described as a function that receives a number to count to as an input command and outputs something once it's done counting. There are two ways we could go about implementing this:

*

*An async gear, in which we write procedural code to describe the logic
 from pygears import gear, sim
 from pygears.typing import Uint
 from pygears.sim import log
 from pygears.lib import once, qrange

 @gear
 async def counter(cmd: Uint, *, something) -> b'type(something)':
     async with cmd as c:
         async for i in qrange(c):
             pass

         yield something

 @gear
 async def collect(data):
     async with data as d:
         log.info(f'Got something: {d}')

 once(val=256) \
     | counter(something=Uint[8](2)) \
     | collect

 sim()

Here, the counter has an interface called cmd, where a number of cycles to count is received, and a compile time parameter called something, which will be sent through the output interface once the counting is done. In the body of the function, we first wait for the input command to arrive: async with cmd as c:, next we wait for the counter to finish and finally we output something. qrange is a builtin gear and you are welcome to inspect its implementation here: rng.py
Then there's the collect gear which simply prints out whatever it receives. Finally, we generate the command for the counter using once, and feed the output of the counter to the collect module. When sim() is invoked, we get the following output showing that collect got something in the cycle 255:
 0                      [INFO]: -------------- Simulation start --------------
 255             /collect [INFO]: Got something: u8(2)
 256                      [INFO]: ----------- Simulation done ---------------
 256                      [INFO]: Elapsed: 0.03

*We could use a hierarchical gear to connect existing builtin modules to achieve the same thing:
 from pygears import gear, sim
 from pygears.typing import Uint
 from pygears.sim import log
 from pygears.lib import once, qrange, when

 @gear
 def counter(cmd: Uint, *, something):
     last = qrange(cmd)['eot']

     return when(last, something)

 @gear
 async def collect(data):
     async with data as d:
         log.info(f'Got something: {d}')

 once(val=256) \
     | counter(something=Uint[8](2)) \
     | collect

 sim()

Everything is pretty much the same, except that the counter isn't defined with the async keyword, meaning that it is a hierarchical gear and only describes interconnection between its submodules. The qrange gear outputs both the iterator and a flag, called eot (for end-of-transaction), which marks the last count. We feed eot (via eot variable) to the when gear that will only output something when it sees value True on eot interface.


text:
Q: OPC client creates another instance of OPC server I have created OPC server using OPC Graybox.
When I launch this as a console application, everything is fine - multiple clients can connect and read the data from this sever.
However, the problem happens when the server is hosted within Windows Service.
When OPC client connects to OPC server, it creates another one instance of Windows Service and that does not fit me.
I found one workaround here: http://support.ge-ip.com/support/index?page=kbchannel&id=09237d4900112023bed2600678f
But, after choosing of 'Interactive user' on Identity Tab of the OPC Server, I need to reboot the service in order to apply the changes. And as soon as service is rebooted, Identity tab reverts back to the 'Launching user', so I didn't have to chance to check this solution.
Any ideas how to overcome this issue ?

A: "Interactive User" is usually not a good choice either. For OPC servers, and especially those that should run as Windows service, a specific, concrete user should be chosen. Try it. If such setting also keeps reverting to something else. then - to my knowledge - it is probably the server doing it itself, so you need to fix it; Windows does not do it.

A: You can try to:

*

*on the PC where the OPC server is installed go to the dcom settings (by launching dcomcnfg command);

*select your OPC server from the list  and open the properties panel;

*select the Identity tab;

*if checked, uncheck the Run application on this computer element;

See this image as example:
Disabling Run application on this computer in the Identity tab
This worked for me.


text:
Q: How is the non-existence of a solution proven? I've been wondering how an argument that a solution to a particular problem doesn't exist is put together.
For instance "Pour-El and Richards found an ordinary differential equation $\phi'(t)=F(t,\phi(t))$ with $F$ computable and no computable solution."
Another puzzling example is the non-computability of Chaitin's constant.
I'm not talking about trivial examples, e.g. the DE $f(x)=f(x)+1$.
Could you give examples of outlines of such proofs? The only strategy I can think of is showing that the assumption that a solution exists leads to a contradiction, but surely there are more sophisticated ways than this?
EDIT: In case it wasn't clear (it probably wasn't), I also would examples of proof strategies involved in proving the non-existence of solutions to, for instance, DEs. The reason my examples focuses on computability is because I couldn't find any examples of the non-existence.

A: It sounds like you're asking how you tell that a given object (solution to a DE, Chaitin's constant, etc.) is not computable, not that it doesn't exist. Indeed, the point is that these things do exist, and can be proved to be pretty weird. So let me talk a bit about how you show that something is not computable.
The easiest way to show that a function $f$ is incomputable is to exhibit - for each computable function $c$ - a value $n$ such that $f(n)\not=c(n)$. For example, let $\varphi_i$ be some canonical listing of all partial computable functions, and define $f(n)$ to be $\varphi_n(n)+1$, if $\varphi_n(n)$ is defined, and $0$ otherwise. Then immediately by definition $f$ is not computable!
Sometimes the argument along these lines is more involved - for instance, to show that the halting function $g$ (given by $g(n)=0$ if $\varphi_n(n)$ is defined, and $1$ otherwise) is not computable, we need to talk about constructing machines: if such a $g$ were computable, it would be $\varphi_k$ for some $k$. Now show that there is a computable $j$ such that $\varphi_j(i)$ is $1$ if $\varphi_k(i)=0$ and is undefined otherwise, and think about $\varphi_j(j)$ . . .
There is also coding. If I've already shown that some $f$ is not computable, then I can show that a function $\hat{f}$ is not computable by "reducing" $f$ to $\hat{f}$: showing how I can compute $f$ "relative to" $\hat{f}$. Since $f$ is not computable, neither is $\hat{f}$. This can be made precise - see "oracle Turing machines."


text:
Q: Overload make_heap? I have a std::vector<t_Mont> v, t_Mont have {float val, int i and int j}
I want to do make_heap(v.begin(), v.end()) and pop_head(v.begin(), v.end()) but I get a lot of errors on console. I think this is because I'm passing a vector of type t_mont.
I want to make_heap on the value of the variable val of v.
What I have to do to compile me? I have to overload make_heap and pop_head? How I do it?
Thanks.
My code:
std::vector<t_Mont> v;
for (int i = 0; i < nCellsHeight; i++) {
    for (int j = 0; j < nCellsWidth; j++) {
        t_Mont aux;
        aux.i = i;
        aux.j = j;
        aux.val = cellValues[i][j];
        v.push_back(aux);
    }
}

std::make_heap(v.begin(), v.end());
while (v.begin() != v.end()) {
    std::cout << "Best of v = " << v[0].val << std::endl;
    std::pop_heap(v.begin(), v.end());
    v.pop_back();
    std::make_heap(v.begin(), v.end());
}

A: t_Mont has to be comparable with operator< for this to work, or you have to use the other form of std::make_heap and pass a comparison functor alongside the iterators (if, for some reason, you don't want t_Mont to be generally sortable).
That is to say, you have to define
bool operator<(t_Mont const &lhs, t_Mont &rhs) {
  // return true if lhs is less than rhs, false otherwise.
}

so that you get a total order (i.e., a < b means !(b < a), a < b and b < c mean a < c, and !(a < a)), or
struct t_Mont_compare {
  bool operator()(t_Mont const &lhs, t_Mont &rhs) const{
    // return true if lhs is less than rhs, false otherwise.
  }
}

with the same conditions.

A: make_heap and related functions will, by default, compare values using <. You need to either provide an overload of that operator for your type:
bool operator<(t_Mont const & lhs, t_Mont const & rhs) {
    return lhs.val < rhs.val;
}

or provide a custom comparator when you call the functions:
auto comp = [](t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;};
std::make_heap(v.begin(), v.end(), comp);

If you're stuck with an ancient pre-lambda compiler, define a function type in full:
struct Comp {
    bool operator()(t_Mont const & lhs, t_Mont const & rhs){return lhs.val < rhs.val;}
};

std::make_heap(v.begin(), v.end(), Comp());

A: You have to define a function object for making comparisons between two t_Monts. The declaration of make_heap looks like this :
template <class RandomAccessIterator, class Compare>
void make_heap (RandomAccessIterator first, RandomAccessIterator last, Compare comp );

Or just create a function like this :
bool comp_tmonts(const t_Mont& a, const t_Mont& b)
{
   /* Insert your comparison criteria for less than here.
      Return a boolean value corresponding to whether a is less than b */
}

Then pass this to your make_heap function as the third argument :
make_heap(v1.begin(), v1.end(), comp_tmonts);


text:
Q: AWS - dynamodb - How to do a search in similar text? I have a table in dynamodb, and I store in it a content similar to this:
Product Code | Title
1 | Computer
2 | Notebook

But when I use the SCAN function to fetch the records, it only finds if I put "Computer" (Exactly the same)
If I put "computer" do not think anything.
Json being sent to SCAN:
{
    "TableName": "products",
    "ScanFilter": {
      "Title" : {
         "AttributeValueList": [
            {
               "S": "computer"
            }
         ],
         "ComparisonOperator": "CONTAINS"
      }
   }
}

A: DynamoDB doesn't support fuzzy matching for either of its' querying APIs. If you need fuzzy matching you will have to either use a different database technology or cone up with a combination of DynamoDB + something else.
ElasticSearch comes to mind as a great fulltext search engine that supports similarity searches very well.


text:
Q: Listbox does not add item to its list. If I use selection.None I am using an array to populate my listbox. It worked fine but when I set the listbox.selection.none (I don't want items to be selected) then My listbox adds item to its first index but after that. It keeps the same value in an does not add new values. below is the code what i am using to add items to listbox from array.
Private array(10) As Decimal ' adds student score to array

dim index as integer = 0 '

Private Sub PopulateScoreList() ' method called when button is clicked
    If index < 10 Then
        ' adds value to array at every button click event
        array(index) = Math.Round(value, 1)
    End If
    index += 1
    lbxTroopersScore.DataSource = Nothing
    lbxTroopersScore.DataSource = array

end sub

A: Seems like a bug.  Toggling the SelectionMode property fixes the problem:
lbxTroopersScore.DataSource = Nothing
lbxTroopersScore.SelectionMode = SelectionMode.One
lbxTroopersScore.SelectionMode = SelectionMode.None
lbxTroopersScore.DataSource = array


text:
Q: При position fixed все элементы сдвигаются влево, а должны оставаться на месте? Как сделать, чтобы меню было фиксированное и элементы оставались на местах?
Когда там ещё и логотип (он у меня на пк), то вообще в него немного залазит.
На имгуре фото до прокрутки и после ней:
https://imgur.com/a/UomFjGt

window.onscroll = function shownavbar() {
  var navbar = document.querySelector('.navbar');
  if (window.pageYOffset > 1) {
    navbar.classList.add('navbar_fixed');
  } else {
    navbar.classList.remove('navbar_fixed');
  }
}
body {
  height: 2000px;
}

.header {
  background-image: url('../img/main-bg.svg');
  background-repeat: no-repeat;
  background-size: 100%;
  overflow: hidden;
}

.m_auto {
  margin-left: 99px;
  margin-right: 80px;
  margin-top: 20px;
}

.navbar {
  overflow: hidden;
}

.navbar_fixed {
  position: fixed;
}

.logo {
  background-image: url('../img/logo.svg');
  background-repeat: no-repeat;
  width: 100%;
  width: 30px;
  height: 30px;
  float: left;
  padding-bottom: 10px;
}

.menu {
  float: right;
  padding-top: 2px;
}

.menu li {
  display: inline-block;
  font-family: OpenSans;
  font-style: normal;
  font-weight: normal;
  font-size: 10px;
  line-height: 14px;
  letter-spacing: 0.2em;
  text-transform: uppercase;
  margin-right: 25px;
}

.menu li:last-child {
  margin-right: 32px;
}

.menu li a {
  color: #000;
}

.burger {
  margin-top: 6px;
  width: 18px;
  height: 2px;
  background-color: #000;
  float: right!important;
  margin-right: 3px;
}

.burger::before {
  content: '';
  margin-top: 5px;
  width: 18px;
  height: 2px;
  background-color: #000;
  float: right!important;
}

.burger::after {
  content: '';
  margin-top: 3px;
  width: 18px;
  height: 2px;
  background-color: #000;
  float: right!important;
}

главная

о нас

контакты


text:
Q: AOLserver, apache2 I am using 3.13.0-77-generic #121-Ubuntu  x86_64 x86_64 x86_64 for hosting two websites.
Issue i faced is:
apaches services went down and sites down. When i checked, i got this error in restarting apache services:
(98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
(98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80
I checked all configuration and everything was perfect. I then checked AOLserver process were running.So i killed the process, and restarted apache services again.This is no the first time i faced this issue. It pops in all of a sudden, i had to kill AOLServer services to run apache2 services again.
My question is: What is AOLserver and what can i do to avoid such issues in future.
I could not find much information in logs about the server.
Thanks

A: AOL Server is America Online's Open-Source web server. AOLserver is the backbone of the largest and busiest production environments in the world. AOLserver is a multithreaded, Tcl-enabled web server used for large scale, dynamic web sites.
Apache is also a web server like AOL.
You could run both AOL and Apache2 using proxy module in apache2.
Also, Apache2 can be easily configured to work with AOL.
The fact is that AOL Server and Apache 2 Server are competing for port 8080

i suggest you run AOL on a separate port or uninstall it if you do not use it.

To run AOL Server on port 8080

Edit
/etc/aolserver4/aolserver4.tcl:
array set debian_config {
    HOSTNAME localhost
    ADDRESS 127.0.0.1
    HTTP_PORT 8080
    HTTPS_PORT 443
}

then run to restart both servers
/etc/init.d/aolserver4 restart
/etc/init.d/apache2 restart
then configure apache2 to use a proxy for requests by adding or editing an existing site in /etc/apache2/sites-available/
For instance i edited sudo nano /etc/apache2/sites-available/site1.conf and placed this code there
<VirtualHost *:80>
    ProxyPreserveHost On
    ProxyRequests Off
    ServerName www.site1.com
    ServerAlias site1.com
    ProxyPass / http://localhost:8080/site1/
    ProxyPassReverse / http://localhost:8080/site1/
</VirtualHost>

After which you enable the apache modules proxy & apache proxy_http with commands
sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart

It means you have to manually direct requests to the AOL server from Apache2 via proxy, keeing both servers active.


text:
Q: Unable to read FaultException from an asp.net core connected service I'm trying to catch the FaultException on a WCF client.
the generated reference contract is:
        [System.ServiceModel.OperationContractAttribute(Action="urn:wcfname#method", ReplyAction="*")]
        [System.ServiceModel.FaultContractAttribute(typeof(Error[]), Action= "urn:wcfname#method", Name="errors")]
        [System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
        [System.ServiceModel.ServiceKnownTypeAttribute(typeof(Response))]
        [System.ServiceModel.ServiceKnownTypeAttribute(typeof(Request))]
        service.response method(service.request request);

and the generated error class is:
    [System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Tools.ServiceModel.Svcutil", "2.0.2")]
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.Xml.Serialization.XmlTypeAttribute(Namespace="wcf")]
    public partial class Error
    {

        private string errorCodeField;

        private string errorStringField;

        private string subErrorCodeField;

        private string offendingFieldField;

        private System.DateTime timeStampField;

        private bool timeStampFieldSpecified;

        private string detailStringField;

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=0)]
        public string errorCode
        {
            get
            {
                return this.errorCodeField;
            }
            set
            {
                this.errorCodeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=1)]
        public string errorString
        {
            get
            {
                return this.errorStringField;
            }
            set
            {
                this.errorStringField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order=2)]
        public string subErrorCode
        {
            get
            {
                return this.subErrorCodeField;
            }
            set
            {
                this.subErrorCodeField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=3)]
        public string offendingField
        {
            get
            {
                return this.offendingFieldField;
            }
            set
            {
                this.offendingFieldField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=4)]
        public System.DateTime timeStamp
        {
            get
            {
                return this.timeStampField;
            }
            set
            {
                this.timeStampField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlIgnoreAttribute()]
        public bool timeStampSpecified
        {
            get
            {
                return this.timeStampFieldSpecified;
            }
            set
            {
                this.timeStampFieldSpecified = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlElementAttribute(Order=5)]
        public string detailString
        {
            get
            {
                return this.detailStringField;
            }
            set
            {
                this.detailStringField = value;
            }
        }
    }

the code to call the sercie is below:
try
{
   //call the service method
}
catch (FaultException<Error[]> ex)
{
   var errorElement = XElement.Parse(ex.CreateMessageFault().GetReaderAtDetailContents().ReadOuterXml());
   var xmlDetail = (string)errorElement;
}
catch (FaultException ex)
{
   var errorElement = XElement.Parse(ex.CreateMessageFault().GetReaderAtDetailContents().ReadOuterXml());
   var xmlDetail = (string)errorElement;

}

When theres a FaultExeption<Error[]> ex, it enters there, but the error is empty string.
If I comment that part, it enters on the FaultException ex, but again the error is empty string.
I'm using .netCore 3.1
Any advice is appreciated.

A: Throwing FaultException indicates that there is no problem with the channel. The exception was thrown by the service. WCF's FaultException message is too general to pinpoint a specific problem, so you can customize the exception message like this:
public class HomeService : IHomeService
      {
          public Student Get(string id)
          {
              try
              {
                  //Here, of course, an exception will be thrown
                 var result = Convert.ToInt32(id) / Convert.ToInt32("0");

         return new Student() { ID = Convert.ToInt32(id), Name = "hxc", SNS = "001" };
             }
             catch (Exception ex)
             {
                 var reason = new FaultReason("Exception thrown information");

                 var code = new FaultCode("500");

                 var faultException = new FaultException(reason, code, "It is GET that throws the exception");

                 throw faultException;
             }
         }
     }


text:
Q: Pointwise multiplication by unbounded function throws us out of $L^2(\mu)$ Let $(X,\mathcal{A},\mu)$ be a $\sigma$-finite measure space and let $\phi$ be a measurable function that is not an element of $L^\infty(\mu)$, i.e. $\phi\not\in L^\infty(\mu)$. I am trying to construct a function $g\in L^2(\mu)$ such that $\phi\cdot g\not\in L^2(\mu)$.
I tried partitioning $X$ in the sets $A_k=\{k\leq|\phi|<k+1\}$ so i could somehow control the behavior of $g$ on those sets relative to $\phi$, but I needed something more. I considered a partition of $X$ in disjoint sets of finite measure say $(X_n)$ and then I tried to take their co-partition. The problem arising is that I cannot determine which of the sets $A_k\cap X_n$ are of non-zero measure. I am really stuck here. Any ideas?

A: Replacing $g$ with $\frac{g\phi}{|\phi|}$ on $X$, which doesn't change the $L^2$ norm of $g$ we can first treat the case $\phi=|\phi| \ge 0$ and then use the above to complete the general case; writing $a_k=\mu(A_k)$, the hypothesis gives $a_k$ non zero for infinitely many $k$; for any $a_k= \infty$, we replace $A_k$ with a subset of finite positive measure $b_k$ which exists by sigma finitness, and make $g$ zero outside that on $A_k$, so we can actually assume $a_k$ finite to start with.
Then for all $k>0$ with $a_k \ne 0$, let $g= \frac{1}{k\sqrt{a_k}}$ on the corresponding $A_k$ and zero everywhere else.
It is obvious that the integral of $g^2$ is finite, being dominated by $\zeta(2)$, while the integral of $(\phi g)^2$ is at least an infinite sum of $1$'s, so infinite.

A: Another way of seeing this, is the following:
If $T:g\mapsto\phi g$ acted as $L^2(\mu)\to L^2(\mu)$, then by the closed graph theorem it would be $T\in\mathcal{B}(L^2(\mu))$. Indeed, if $g_n\to0$ in $L^2(\mu)$-norm and $\phi g_n\to h$, then $\|h\|_2^2=\langle h,h\rangle=\displaystyle{\lim_{n\to\infty}\langle \phi g_n, h\rangle=\lim_{n\to\infty}\langle g_n, \overline{\phi} h\rangle=0}$.
But $T$ is the multiplication operator by $\phi$, hence $\|T\|=\|\phi\|_\infty$, a contradiction.
(To see that $\|T\|\geq\|\phi\|_\infty,$ let $a<\|\phi\|_\infty$. Choose a measurable set $E$ of positive and finite measure such that $E\subset\{|\phi|>a\}$, consider the characteristic function of $E$ and apply $T$ to it).


text:
Q: Connection to http://xxxxx.com refused I am using SoapUI to test the third party web service(asmx). The testing service is SSL required, generally in most production cases the service is used over http, for the test goal the third party asks us to use SSL.
So I added the https uri to the SoapUI and invoked it.
However I got the error:
ERROR:org.apache.http.conn.HttpHostConnectException: Connection to http://xxxxx.com refused
at com.eviware.soapui.impl.wsdl.support.http.SoapUIMultiThreadedHttpConnectionManager$SoapUIClientConnectionOperator.openConnection(SoapUIMultiThreadedHttpConnectionManager.java:279)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:561)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
at com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport$Helper.execute(HttpClientSupport.java:233)
at com.eviware.soapui.impl.wsdl.support.http.HttpClientSupport.execute(HttpClientSupport.java:323)
at com.eviware.soapui.impl.wsdl.submit.transports.http.HttpClientRequestTransport.submitRequest(HttpClientRequestTransport.java:290)
at com.eviware.soapui.impl.wsdl.submit.transports.http.HttpClientRequestTransport.sendRequest(HttpClientRequestTransport.java:220)
at com.eviware.soapui.impl.wsdl.WsdlSubmit.run(WsdlSubmit.java:119)
at com.eviware.soapui.impl.wsdl.WsdlSubmit.submitRequest(WsdlSubmit.java:79)
at com.eviware.soapui.impl.wsdl.WsdlRequest.submit(WsdlRequest.java:217)
at com.eviware.soapui.impl.wsdl.teststeps.WsdlTestRequestStep.run(WsdlTestRequestStep.java:364)
at com.eviware.soapui.impl.wsdl.support.AbstractTestCaseRunner.runTestStep(AbstractTestCaseRunner.java:211)
at com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner.runCurrentTestStep(WsdlTestCaseRunner.java:47)
at com.eviware.soapui.impl.wsdl.support.AbstractTestCaseRunner.internalRun(AbstractTestCaseRunner.java:138)
at com.eviware.soapui.impl.wsdl.support.AbstractTestCaseRunner.internalRun(AbstractTestCaseRunner.java:46)
at com.eviware.soapui.impl.wsdl.support.AbstractTestRunner.run(AbstractTestRunner.java:129)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
    Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:123)
at com.eviware.soapui.impl.wsdl.support.http.SoapUIMultiThreadedHttpConnectionManager$SoapUIClientConnectionOperator.openConnection(SoapUIMultiThreadedHttpConnectionManager.java:262)

I am sure that I set Proxy to :None in file > Preferences >Proxy settings.
Also I turned off the Windows Firewall.
I also tried another tool Storm to test the web service. And I got another error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it xxx.xxx.x.xxx:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
 --- End of inner exception stack trace ---
 at System.Web.Services.Protocols.WebClientProtocol.GetWebResponse(WebRequest request)
 at System.Web.Services.Protocols.HttpWebClientProtocol.GetWebResponse(WebRequest request)
 at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
 at DirectLinkTrustV0102.ValidateCaller(ValidateCallerInput input)
 --- End of inner exception stack trace ---
 at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
 at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
 at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
 at Storm.UI.Forms.FormMainOps.clo@651.Invoke(Object[] methodParams@41)
 at <StartupCode$Storm>.$Type.bgworker.run@51@57_2.Invoke(DoWorkEventArgs dArgs)
 at <StartupCode$Storm>.$Type.bgworker.run@51@57_1.Invoke(Object sender, DoWorkEventArgs e)
 at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)

BTW, I can open it from the browser.
Thanks for help.

A: You tell that to invoke the server use of https is required, however it seems that you're using http instead since the error message from soapui is:
ERROR:org.apache.http.conn.HttpHostConnectException: Connection to http://xxxxx.com
And from Storm:
System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it xxx.xxx.x.xxx:80
So check that you're really using the https (default port is 443) in your soapui request, because probably the server is refusing the connection in port 80 since it's listenting in 443.
Hope it helps,

A: Finally I figured it out. When you add the uri to SoapUI, even it has the https format. The SoapUI still use http as default in the request. You may might overlook it.
You have to manually to edit the endpoint in the address bar of Request1.


text:
Q: Python 3.7/buildozer - Application crash on Android after start I want to compile my python script to APK and run it on Android. I'm using kivy, os, pika, threading, and own module "RabbitMQ".
Lubuntu 18.04 with Python 3.6
and for code I use Python 3.7.
In buildozer.spec I've got requirements = python3,kivy,RabbitMQ and android.permissions = INTERNET.
When I run my app on Android it starts loading and then it just crash.
Here are my logcat logs:
01-18 21:28:27.937 29220 29255 I python  :  Traceback (most recent call last):
01-18 21:28:27.937 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/python3-libffi-openssl-sqlite3/armeabi-v7a__ndk_target_21/python3/Lib/threading.py", line 917, in _bootstrap_inner
01-18 21:28:27.937 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/jnius/__init__.py", line 54, in jnius_thread_hook
01-18 21:28:27.938 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/other_builds/python3-libffi-openssl-sqlite3/armeabi-v7a__ndk_target_21/python3/Lib/threading.py", line 865, in run
01-18 21:28:27.938 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/app/main.py", line 216, in start
01-18 21:28:27.938 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/app.py", line 829, in run
01-18 21:28:27.938 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/app/main.py", line 211, in build
01-18 21:28:27.939 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/app/main.py", line 96, in __init__
01-18 21:28:27.939 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/uix/floatlayout.py", line 65, in __init__
01-18 21:28:27.939 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/uix/layout.py", line 76, in __init__
01-18 21:28:27.940 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/uix/widget.py", line 361, in __init__
01-18 21:28:27.940 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/uix/widget.py", line 469, in apply_class_lang_rules
01-18 21:28:27.940 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/lang/builder.py", line 538, in apply
01-18 21:28:27.941 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/lang/builder.py", line 659, in _apply_rule
01-18 21:28:27.941 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/lang/builder.py", line 654, in _apply_rule
01-18 21:28:27.941 29220 29255 I python  :    File "kivy/_event.pyx", line 188, in kivy._event.EventDispatcher.__cinit__
01-18 21:28:27.941 29220 29255 I python  :    File "kivy/properties.pyx", line 447, in kivy.properties.Property.link
01-18 21:28:27.942 29220 29255 I python  :    File "kivy/properties.pyx", line 632, in kivy.properties.NumericProperty.init_storage
01-18 21:28:27.942 29220 29255 I python  :    File "kivy/properties.pyx", line 418, in kivy.properties.Property.init_storage
01-18 21:28:27.942 29220 29255 I python  :    File "kivy/properties.pyx", line 655, in kivy.properties.NumericProperty.convert
01-18 21:28:27.942 29220 29255 I python  :    File "kivy/properties.pyx", line 663, in kivy.properties.NumericProperty.parse_str
01-18 21:28:27.943 29220 29255 I python  :    File "kivy/properties.pyx", line 670, in kivy.properties.NumericProperty.parse_list
01-18 21:28:27.943 29220 29255 I python  :    File "kivy/properties.pyx", line 296, in kivy.properties.dpi2px
01-18 21:28:27.943 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/utils.py", line 505, in __get__
01-18 21:28:27.943 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/kivy/metrics.py", line 163, in dpi
01-18 21:28:27.944 29220 29255 I python  :    File "/home/virtual/Downloads/.buildozer/android/platform/build-armeabi-v7a/build/python-installs/myapp/jnius/reflect.py", line 159, in autoclass
01-18 21:28:27.944 29220 29255 I python  :    File "jnius/jnius_export_func.pxi", line 26, in jnius.jnius.find_javaclass
01-18 21:28:27.944 29220 29255 I python  :  jnius.jnius.JavaException: Class not found b'org/renpy/android/Hardware'
01-18 21:28:27.944 29220 29255 I python  :

A: There's 'jnius' in the errors, are you using it in your app? If so, just add 'pyjnius' to requirements in the spec file.


text:
Q: jsp populating object array Im new to JSP and trying to create a web application where I can retrieve a list of actor from mysql db and populate it in the JSP page.
I'm successfully able to retrieve the actor(firstname, lastname, actor_id) from the mysql db and populate in a actors arraylist object but unable to populate the same in the JSP page,
Here is my code,
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="com.dbconnect.Actor,java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>All the actors from SAKILA database</title>
</head>
<body>
Im in get actors.jspp

<%ArrayList<Actor> acrs =  (ArrayList<Actor>)request.getAttribute("actorslist");%>
<c:forEach var="Actor"  items="${acrs}">
    FirstName:<c:out value="${Actor.getFirstname()}"></c:out>
</c:forEach>

%>

</body>
</html>

Servlet code

package com.dbconnect;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class actorservlet
 */
public class actorservlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public actorservlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Im in actorsservlet");
        Actors acrs = new Actors();
        ArrayList<Actor> actorslist = null;
        try {
            actorslist = acrs.getactors();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (Actor ac:actorslist)
            System.out.println(ac.firstname);
        request.setAttribute("actorslist", actorslist);
        RequestDispatcher dispatcher = request.getRequestDispatcher("getactors.jsp");
        //response.sendRedirect("getactors.jsp");
        dispatcher.forward(request, response);
        return;
    }

}

Actors.java

package com.dbconnect;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class Actors {
    List<Actor> ls = new ArrayList<Actor>();
    DbContext db = null;
    Actors(){

        try {
            this.db = new DbContext();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public ArrayList<Actor> getactors() throws ClassNotFoundException,
            SQLException {

        ResultSet rs = this.db.getrows();
        populateactorlist(rs);
        return (ArrayList<Actor>) ls;
    }

    public void populateactorlist(ResultSet rs) throws SQLException {
        while (rs.next()) {
            Actor rc = new Actor();
            rc.setActor_id(rs.getInt("actor_id"));
            rc.setFirstname(rs.getString("first_name"));
            rc.setLastname(rs.getString("last_name"));
            ls.add(rc);
        }
    }

    }

}

Actor.java
package com.dbconnect;

public class Actor {
    Integer actor_id = null;
    String firstname = null;
    String lastname = null;

    public Integer getActor_id() {
        return actor_id;
    }

    public void setActor_id(Integer actor_id) {
        this.actor_id = actor_id;
    }

    public String getFirstname() {
        return firstname;
    }

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

}

A: I'm not sure about the extraneous tags.  Try this:
<% ArrayList<Actor> acrs =  (ArrayList<Actor>)request.getAttribute("actorslist"); %>
<c:forEach var="Actor"  items="${acrs}">
    FirstName:<c:out value="${Actor.getFirstname()}"/><br/>
</c:forEach>

In particular, delete the lower %> (a typo?)


text:
Q: Sound beats mathematical expression I am reading about sound beats. According to the superposition principle, if at a certain position the two waves are given by, let say,
$$\ y_a(t)=Asin(2\pi f_at)$$
$$\ y_b(t)=-Asin(2\pi f_bt)$$
then the total wave will be
$$\ y_a(t)+y_b(t)=[2Asin(\frac{1}{2}(2\pi)( f_a-f_b)t]cos\frac{1}{2}(2\pi)( f_a+f_b)t$$
Now, my question is, when grouping the terms in this expression, why do you say that the $sin(\frac{1}{2}(2\pi)( f_a-f_b)t$ is the amplitude factor and not the $cos\frac{1}{2}(2\pi)( f_a+f_b)t$. How can you know that it's the sine not the cosine that is varying the amplitude.
Edit: my real question is that why is it the $f_a-f_b$ not the $f_a+f_b$ term that is modulating the amplitude.
Image source: university physics by young and freedman.

A: It's not particularly relevant that it is the $\sin$ term rather than the $\cos$ term, except in so far as that's how the expansion of the functions work.
Given we start with the expression
$$\begin{align}
y(t) &= y_a(t) + y_b(t)\\
     &= 2A\sin\left(2\pi \frac{f_a - f_b}{2}t\right)
          \cos\left(2\pi \frac{f_a + f_b}{2}t\right)\tag{1}
\end{align}
$$
The thing to look at is what this looks like when $f_a$ is very close to $f_b$, and in particular when $\left|f_a - f_b)\right| \ll (f_a + f_b)$.
In this case it's useful to define
$$
\begin{align}
f &= \frac{f_a + f_b}{2}\\
\Delta f &= \frac{f_a - f_b}{2}
\end{align}
$$
And $\left|\Delta f\right| \ll f$
So our expression now looks like
$$y(t) = 2A\sin(2\pi\Delta f t)\cos(2\pi ft)$$
Depending on how close in frequency $f_a$ & $f_b$ are, $\Delta f$ can be very small indeed: it can be zero in fact.  But $f$ is not going to be zero unless both $f_a$ & $f_b$ are zero (let's quietly assume that $f_a \ge 0$ & $f_b \ge 0$, which we can safely do).
So, if these are audio frequencies, what this is going to sound like is a tone of frequency $f\approx f_a \approx f_b$, changing slowly in volume at a frequency of $\Delta f$ which may be very small.
That's why it's that term which is thought of as modulating the amplitude.
Here are two pictures which, I hope, make it clear why it is the difference term which should be thought of as doing the modulating.  First of all here is a second of $\sin (200 \pi t)$: a $100\,\mathrm{Hz}$ sine wave:

Now here is a second of $\sin(200\pi t) + \sin(204\pi t)$: a waveform made up of $100\,\mathrm{Hz}$ and $102\,\mathrm{Hz}$ sine waves:

I think it is extremely obvious that this is a high-frequency wave being modulated by a low-frequency wave.
(Note that both of these pictures have some artifacts in due to my inadequate plotting skills.)

In the original version of this answer I thought the question was why the $\sin$ term rather than a $\cos$ term is doing the modulating, and I had a rather grotty paragraph showing that you could make it be either.  Here is a cleaned-up version of that, for posterity.
First of all, define $\omega_a = 2\pi f_a$ & $\omega_b = 2\pi f_b$: this is just to get rid of a bunch of annoying factors of $2\pi$: $\omega$ is the angular frequency.  To make things simpler I'll also make $A=1$: again this is just to make this term go away so I have less to write.
Now the original expression looks like
$$\sin(\omega_a t) - \sin(\omega_b t)$$
And if we assume $\omega_a \approx \omega_b$ we can write $\omega_a = \omega +\Delta\omega$ & $\omega_b = \omega - \Delta\omega$.  Then the above becomes
$$\sin(\omega t + \Delta\omega t) - \sin(\omega t - \Delta\omega t)
= 2\sin(\Delta\omega t)\cos(\omega t)$$
by the double-angle formula for $\sin$.
But what if, instead, we consider
$$
\begin{align}
\sin(\omega t + \Delta\omega t) - \sin(\omega t - \Delta\omega t - \pi)
&= \sin(\omega t + \Delta\omega t) + \sin(\omega t - \Delta\omega t)\\
&= 2\cos(\Delta\omega t)\sin(\omega t)
\end{align}
$$
This is just offsetting one of the terms by a constant of $\pi$: acoustically this is the same thing.  But now using the same double-angle formula we find the term doing the modulating is $\cos$ not $\sin$: it doesn't make any difference, in fact.

A: It's convention.  It's how we typically define modulation.
You are absolutely correct that mathematically, it doesn't matter if you are modulating around $\frac{f_a-f_b}{2}$ or $\frac{f_a+f_b}{2}$.  However, when we talk about modulation, we will always refer to the slower frequency as the one that is modulating the higher frequency.
In this particular example, the difference is arbitrary. In other cases, it will not be.  When we look at how we use modulation in practical applications, its virtually always using a low frequency signal to modulate a high frequency carrier (with a fixed amplitude).  Doing so provides lots of convenient mathematical properties which we leverage.  Doing it the other way (modulating a low frequency carrier with a high frequency signal) just doesn't provide the behaviors we want.  It provides other behaviors.
For example, one well known use of modulation is to modulate the audio-frequency signals from a radio station into a frequency band which can be easily transmitted through airspace.  In such cases, the signal is in the low kHz, and the carrier is in high kHz to MHz.
So when your wave question showing beats can be written in a form which looks like modulation, we'll always declare the low frequency side to be modulating the amplitude.


text:
Q: Jenkinsfile and different strategies for branches I'm trying to use Jenkins file for all our builds in Jenkins, and I have following problem.
We basically have 3 kind of builds:

*

*pull-request build - it will be merged to master after code review, and if build works

*manual pull-request build - a build that does the same as above, but can be triggered manually by the user (e.g. in case we have some unstable test)

*an initial continuous deliver pipeline - this will build the code, deploy to repository, install artifacts from repository on the target server and start the application there

How should I contain all of the above builds into a single Jenkinsfile.
Right now the only idea I have is to make a giant if that will check which branch it is and will do the steps.
So I have two questions:
1. Is that appropriate way to do it in Jenkinsfile?

*How to get the name of currently executing branch in multi-branch job type?

For reference, here's my current Jenkinsfile:
def servers = ['server1', 'server2']

def version = "1.0.0-${env.BUILD_ID}"

stage 'Build, UT, IT'
node {
    checkout scm
    env.PATH = "${tool 'Maven'}/bin:${env.PATH}"
    withEnv(["PATH+MAVEN=${tool 'Maven'}/bin"]) {
        sh "mvn -e org.codehaus.mojo:versions-maven-plugin:2.1:set -DnewVersion=$version -DgenerateBackupPoms=false"
        sh 'mvn -e clean deploy'
        sh 'mvn -e scm:tag'
    }
}

def nodes = [:]
for (int i = 0; i < servers.size(); i++) {
    def server = servers.get(i)
    nodes["$server"] = {
        stage "Deploy to INT ($server)"
        node {
            sshagent(['SOME-ID']) {
                sh """
                ssh ${server}.example.com <<END
                hostname
                /apps/stop.sh
                yum  -y update-to my-app.noarch
                /apps/start.sh
                END""".stripIndent()
            }
        }
    }
}

parallel nodes

EDIT: removed opinion based question

A: Using this post, this worked for me:
        stage('...') {
            when {
                expression { env.BRANCH_NAME == 'master' }
            }
            steps {
                ...
            }
        }

A: 1) I don't know if it is appropriate, but if it resolves your problem, I think is appropriate enough.
2) In order to know the name of the branch you can use BRANCH_NAME variable, its name is taken from the branch name.
${env.BRANCH_NAME}

Here is the answer:
Jenkins Multibranch pipeline: What is the branch name variable?

A: We followed the model used by fabric8 for builds, tweaking it as we needed, where the Jenkinsfile is used to define the branch and deployment handling logic, and a release.groovy file for build logic.
Here's what our Jenkinsfile looks like for a pipeline that continuously deploys into DEV from master branch:
#!groovy
import com.terradatum.jenkins.workflow.*

node {

  wrap([$class: 'TimestamperBuildWrapper']) {
    checkout scm

    echo "branch: ${env.BRANCH_NAME}"
    def pipeline = load "${pwd()}/release.groovy"

    if (env.DEPLOY_ENV != null) {
      if (env.DEPLOY_ENV.trim() == 'STAGE') {
        setDisplayName(pipeline.staging() as Version)
      } else if (env.DEPLOY_ENV.trim() == 'PROD') {
        setDisplayName(pipeline.production() as Version)
      }
    } else if (env.BRANCH_NAME == 'master') {
      try {
        setDisplayName(pipeline.development() as Version)
      } catch (Exception e) {
        hipchatSend color: 'RED', failOnError: true, message: "
BUILD FAILED:

Check console output at ${env.JOB_NAME} [${env.BUILD_NUMBER}]

${e.message}

", notify: true, room: 'Aergo', v2enabled: false
        throw e; // rethrow so the build is considered failed
      }
    } else {
      setDisplayName(pipeline.other() as Version)
    }
  }
}

def setDisplayName(Version version) {
  if (version) {
    currentBuild.displayName = version.toString()
  }
}

Note: you can find the code for our global pipeline library here.

A: You can add If statement for  multiple stages if you want to skip multiple stages according to the branch as in:
if(env.BRANCH_NAME == 'master'){
     stage("Upload"){
        // Artifact repository upload steps here
        }
     stage("Deploy"){
        // Deploy steps here
       }
     }

or, you can add it to individual stage as in:
stage("Deploy"){
  if(env.BRANCH_NAME == 'master'){
   // Deploy steps here
  }
}

A: for questions 2 you may be able to do
sh 'git branch > GIT_BRANCH'
def gitBranch = readFile 'GIT_BRANCH'
since you're checking out from git

A: Don't know if this what you want..
I prefer because it's look more structured.
Jenkinsfile
node {
    def rootDir = pwd()

    def branchName = ${env.BRANCH_NAME}

    // Workaround for pipeline (not multibranches pipeline)
    def branchName = getCurrentBranch()

    echo 'BRANCH.. ' + branchName
    load "${rootDir}@script/Jenkinsfile.${branchName}.Groovy"
}

def getCurrentBranch () {
    return sh (
        script: 'git rev-parse --abbrev-ref HEAD',
        returnStdout: true
    ).trim()
}

Jenkinsfile.mybranch.Groovy
echo 'mybranch'
// Pipeline code here

A: In my scenarium, I have needed run a stage Deploy Artifactory only if the branch was master(webhook Gitlab), otherwise I couldn't perform the deploy.
Below the code of my jenkinsfile:
stages {
    stage('Download'){

        when{
            environment name: 'gitlabSourceBranch', value: 'master'

        }

        steps{
            echo "### Deploy Artifactory ###"

            }
    }

}