text:
Q: Sending objects through socket streams Trying to write a program that will allow clients to send an object to each other. I'm currently using the ObjectOuptutStream to send it across sockets and whenever I try to read or write an object from the object stream, it gives the exception: java.io.NotSerializableException. I searched online about this exception, and the solution I am getting mostly was to implement the Serializable interface on the object you are sending or reading from the stream. Which I did, but still receives this exception.
Here's the object class:
public class Event implements Serializable {

    private static final long serialVersionUID = 1L;

    Integer from;
    Vector<Integer> timestamp;

    public Event(int identifier, Vector<Integer> timestamp) {
        this.from = identifier;
        this.timestamp = timestamp;
    }

    int getFromID() {
        return from;
    }

    Vector<Integer> getTimestamp() {
        return timestamp;
    }

}

Here's the section of the Client class that is writing to other sockets
    Random rand = new Random();

    int temp;
    while (eventCount < 100) {
        System.out.println("Generating Event");
        int choice = rand.nextInt(5);
        if (choice == 0) {
            temp = timestamp.get(identifier);
            ++temp;
            timestamp.set(identifier, temp);
        } else {
            int randC = rand.nextInt(outputClients.size());
            ClientSocket cc = outputClients.get(randC);
            cc.out.writeObject(new Event(identifier, timestamp));
        }
        System.out.println("Done Generating Event");
    }

And here's the threads that are reading the object
public class ClientConnection extends Thread {
    Socket socket;
    ObjectOutputStream out;
    ObjectInputStream in;
    Random rand = new Random();
    public ClientConnection(Socket s) {
        this.socket = s;
        try {
            out = new ObjectOutputStream (socket.getOutputStream());
            in = new ObjectInputStream (socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // execute the event
    private void executeEvent(int from, Vector<Integer> x) {
        int temp;
        synchronized (timestamp) {
            for (int i = 0; i < timestamp.size(); ++i) {
                if (x.get(i) > timestamp.get(i)) {
                    timestamp.set(i, x.get(i));
                }
            }
            temp = timestamp.get(from);
            ++temp;
            timestamp.set(from, temp);
        }
    }

    @Override
    public void run () {
        while (true) {
            System.out.println("Reading events");
            if (!isAlive) {
                break;
            }
            try {
                Event event = (Event) in.readObject();
                executeEvent(event.getFromID(), event.getTimestamp());
            } catch (ClassNotFoundException e) {

            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(timestamp);
        }
    }
}

And here's the Client class for full context (assuming all the appropriate packages are imported)
public class Computer {

static final int MAX_SYSTEMS = 2;                   // MAX SYSTEMS
static Vector<Integer> timestamp = new Vector<Integer>();
static int[] timestamp1 = new int[MAX_SYSTEMS];     // Time-stamp
static int identifier;                              // Computer ID
static int eventCount = 0;                          // Event Counts
static boolean isAlive = true;                      // Check if the computer is alive

Socket sockToServer;
PrintWriter outputToServer;
BufferedReader inputFromServer;
String textFromServer;

ServerSocket ss;

static ArrayList<ClientSocket> outputClients = new ArrayList<ClientSocket>();
static ArrayList<ClientConnection> inputClients = new ArrayList<ClientConnection>();

Log log;

public static void main(String[] args) throws IOException {
    new Computer("127.0.0.1", 8000);
}

public Computer(String hostname, int port) throws IOException {
    // Instantiate server socket
    int socketPort = port + identifier + 1;
    System.out.println(socketPort);
    ss = new ServerSocket(socketPort);

    System.out.println("Server Socket Instantiated");

    // Creating sockets (with streams) to write to stream
    for (int i = 0; i < MAX_SYSTEMS; ++i) {
        if (i != identifier) {
            Socket thing1 = new Socket(hostname, port + i + 1);
            ClientSocket cs = new ClientSocket (thing1);
            outputClients.add(cs);
        }
    }

    log.write("Client Sockets Instantiated\n");

    // Create threads for reading objects and updating timestamp
    for (int i = 0; i < MAX_SYSTEMS - 1; ++i) {
        ClientConnection clientConn = new ClientConnection(ss.accept());
        clientConn.start();
        inputClients.add(clientConn);
    }

    log.write("Server connected to clients");

    Random rand = new Random();

    // Writing Events

    int temp;
    while (eventCount < 100) {
        System.out.println("Generating Event");
        int choice = rand.nextInt(5);
        if (choice == 0) {
            temp = timestamp.get(identifier);
            ++temp;
            timestamp.set(identifier, temp);
        } else {
            int randC = rand.nextInt(outputClients.size());
            ClientSocket cc = outputClients.get(randC);
            cc.out.writeObject(new Event(identifier, timestamp));
        }
        System.out.println("Done Generating Event");
    }

    log.write("Computer finished generating events. Continue listening...\n");

    outputToServer.println("Finish");

    // Wait for Tear Down Message
    while (true) {
        try {
            textFromServer = inputFromServer.readLine();
            if (textFromServer.equals("Tear Down")) {
                isAlive = false;
                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    log.write("Computer shutting off....");

    for (int i = 0; i < outputClients.size(); ++i) {
        ClientSocket sc = outputClients.get(i);
        sc.socket.close();
    }

    sockToServer.close();

}

// client socket class (organizing)
public class ClientSocket {
    Socket socket;
    ObjectOutputStream out;
    ObjectInputStream in;

    public ClientSocket(Socket s) {
        try {
            this.socket = s;
            this.out = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Client Socket Created");
    }
}

public class Event implements Serializable {

    private static final long serialVersionUID = 1L;

    Integer from;
    Vector<Integer> timestamp;

    public Event(int identifier, Vector<Integer> timestamp) {
        this.from = identifier;
        this.timestamp = timestamp;
    }

    int getFromID() {
        return from;
    }

    Vector<Integer> getTimestamp() {
        return timestamp;
    }

}

// send event thread
public class ClientConnection extends Thread {
    Socket socket;
    ObjectOutputStream out;
    ObjectInputStream in;
    Random rand = new Random();
    public ClientConnection(Socket s) {
        this.socket = s;
        try {
            out = new ObjectOutputStream (socket.getOutputStream());
            in = new ObjectInputStream (socket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // execute the event
    private void executeEvent(int from, Vector<Integer> x) {
        int temp;
        synchronized (timestamp) {
            for (int i = 0; i < timestamp.size(); ++i) {
                if (x.get(i) > timestamp.get(i)) {
                    timestamp.set(i, x.get(i));
                }
            }
            temp = timestamp.get(from);
            ++temp;
            timestamp.set(from, temp);
        }
    }

    @Override
    public void run () {
        while (true) {
            System.out.println("Reading events");
            if (!isAlive) {
                break;
            }
            try {
                Event event = (Event) in.readObject();
                executeEvent(event.getFromID(), event.getTimestamp());
            } catch (ClassNotFoundException e) {

            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println(timestamp);
        }
    }
}
}

TL;DR Trying to read and write object through sockets using Object(Output/Input)Stream object. When I do so, I get the NotSerializableException, even though I implemented the Serializable interface in the class that was being written and read from the stream.
All help is appreciated!
(edit: stacktrace)
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: timetableexchange.Computer
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.defaultReadFields(Unknown Source)
    at java.io.ObjectInputStream.readSerialData(Unknown Source)
    at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    at timetableexchange.Computer$ClientConnection.run(Computer.java:239)
Caused by: java.io.NotSerializableException: timetableexchange.Computer
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
    at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at timetableexchange.Computer.<init>(Computer.java:128)
    at timetableexchange.Computer.main(Computer.java:39)
java.io.NotSerializableException: timetableexchange.Computer
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
    at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
    at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
    at java.io.ObjectOutputStream.writeObject0(Unknown Source)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at timetableexchange.Computer.<init>(Computer.java:128)
    at timetableexchange.Computer.main(Computer.java:39)

A: Now that you have supplied the stacktrace .... I see the problem!
You have created Event as an inner class of Computer.  That means that an Event has an implicit link to the enclosing Computer instance ... which will be serialized along with the Event instance.
But Computer is not Serializable.
A (probably incorrect) solution would be to make Computer implement Serializable.  But that means you would send an instance of Computer with every separately serialized Event ... which is why it is probably wrong.
A better solution would be to declare Event as static so that it doesn't have a reference to the enclosing Computer.  As far as I can see, it doesn't need to be an "inner" class.  It could just be a "nested" class, or even a top-level class.
Advice:  When you use nested and inner classes, make sure that you indent them correctly ... to make it easier for other people to spot what is going on.


text:
Q: Newton's Method Java Currently I am creating (trying) a program for Newton's Method and its suppose to allow you to guess the initial root and give you the roots. But I can't figure out how to put the
x1=x0-f(x0)/f(x0) also needs a loop
Here's my code currently :
import java.util.Scanner;

public class NewtonsMethod {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter your guess for the root:");
        double x = keyboard.nextDouble();
        double guessRootAnswer =Math.pow(6*x,4)-Math.pow(13*x,3)-Math.pow(18*x,2)+7*x+6;
            for(x=x-f(x)/f(x));

        System.out.println("Your answer is:" + guessRootAnswer);

    }
}

A: You've misstated how newton's method works:
The correct formula is:
xn+1 <= xn-f(xn)/f '(xn)
Note that the second function is the first order derivative of the first one.
How the first order derivative looks depends on the exact nature of the function.
If you know what f(x) looks like, when you code the program, you can also fill in the code for the first derivative. If you have to figure it out at runtime, it looks like much more or a massive undertaking.
The following code from: http://www.ugrad.math.ubc.ca/Flat/newton-code.html
demonstrates the concept:
class Newton  {

    //our functio f(x)
    static double f(double x) {
        return Math.sin(x);
    }

    //f'(x) /*first derivative*/
    static double fprime(double x) {
        return Math.cos(x);
    }

    public static void main(String argv[]) {

        double tolerance = .000000001; // Stop if you're close enough
        int max_count = 200; // Maximum number of Newton's method iterations

/* x is our current guess. If no command line guess is given,
   we take 0 as our starting point. */

        double x = 0;

        if(argv.length==1) {
            x= Double.valueOf(argv[0]).doubleValue();
        }

        for( int count=1;
            //Carry on till we're close, or we've run it 200 times.
            (Math.abs(f(x)) > tolerance) && ( count < max_count);
             count ++)  {

            x= x - f(x)/fprime(x);  //Newtons method.
            System.out.println("Step: "+count+" x:"+x+" Value:"+f(x));
        }
        //OK, done let's report on the outcomes.
        if( Math.abs(f(x)) <= tolerance) {
            System.out.println("Zero found at x="+x);
        } else {
            System.out.println("Failed to find a zero");
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: LINQ to Entities with inline function not recognized I am getting the following error on a LINQ query:
LINQ to Entities does not recognize the method 'System.String getGroupOwner(System.String)' method, and this method cannot be translated into a store expression.

I found this issue which seems to be very similar: LINQ to Entities does not recognize the method
I know the problem is that LINQ needs to convert the statment into SQL and the function can not be included but I am struggling figuring out how to rewrite this.
Here are my 2 functions:
    public IQueryable<Group> GetGroups()
    {
        string userEID = HttpContext.Current.Request.LogonUserIdentity.Name.ToUpper();
        return db.Groups.Where(sg => sg.GroupActive == true && userEID == getGroupOwner(sg.GroupSecurity)).OrderBy(g => g.GroupName);
    }

    private string getGroupOwner(string GName)
    {
        PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, GName);
        System.DirectoryServices.DirectoryEntry de = (System.DirectoryServices.DirectoryEntry)group.GetUnderlyingObject();
        var owner = de.Properties["managedBy"];
        return owner.Value.ToString().ToUpper();
    }

Any help would be greately appreciated! Thanks in advance.
EDIT #1:
Thanks for the comment @DevilSuichiro.  Here is my first revision which I think is a little closer.  Is this on the right track? What is the syntax for removing the item.
public IQueryable<Group> GetGroups()
{
    string userEID = HttpContext.Current.Request.LogonUserIdentity.Name.ToUpper();
var rs = db.Groups.Where(sg => sg.GroupActive == true).OrderBy(g => g.GroupName);
        foreach (var gname in rs)
        {
                var groupOwner = getGroupOwner(gname.GroupSecurity);
                if (groupOwner != userEID)
                {
                    //I think I need to remove gname from rs here - What is the proper syntax?
                }
        }
        return rs;
}

A: You can't remove items from an IEnumerable while you are enumerating them that will produce an error. What you can do however is select all the elements which you want and return those. Something like this.
public IQueryable<Group> GetGroups()
{
    string userEID = HttpContext.Current.Request.LogonUserIdentity.Name.ToUpper();
    var rs = db.Groups.Where(sg => sg.GroupActive == true).OrderBy(g => g.GroupName);
    var toReturn = new List<Group>();
    foreach (var gname in rs)
    {
            var groupOwner = getGroupOwner(gname.GroupSecurity);
            if (groupOwner == userEID)
            {
                toReturn.Add(gname);
            }
    }
    return toReturn.AsQueryable<Group>();
}


text:
Q: How to create file from byte array and send it to TelegramBot In Service1 I create a byte array and send it to Kafka.
In Service2 I receive a message from Service1, create a PDF file using this byte array and send it to TelegramBot, which sends it to the user.
Service 1
And that's how I send a byte array to Kafka
byte[] file = _pdfBuilder
.AddObject(o =>
{
o.HtmlContent = html;
})
.Convert();

var result = await producer.ProduceAsync(_producerTopic, new Message<Null, string>()
{
Value = Encoding.Unicode.GetString(file)
}, cancelToken.Token);

Service 2
That's how I tried to create PDF file and send it to Telegram Bot
using (var fs = new FileStream("FileName.pdf", FileMode.Create))
{
    foreach (var bt in bytes)
    {
        fs.WriteByte(bt);
    }

    fs.Seek(0, SeekOrigin.Begin);
    var document = new InputOnlineFile(fs, "file.pdf");
    await _client.SendDocumentAsync(id, document);
}

Or this
await using var memoryStream = new MemoryStream(bytes);
var doc = new InputOnlineFile(memoryStream, "file.pdf");
await _client.SendDocumentAsync(id, doc);

Or
var memoryStream = new MemoryStream(bytes);
var doc = new InputOnlineFile(memoryStream, "file.pdf");
await _client.SendDocumentAsync(id, doc);

So the problem is: in a chat with Telegram Bot I receive an empty PDF file.
That's also how I used to create a file in the controller (the file wasn't empty)
 byte[] file = _pdfBuilder
                .AddObject(o =>
                {
                    o.HtmlContent = html;
                })
                .Convert();

 return File(file, "application/pdf");

A: Unicode encoding and decoding breaks the pdf file.
If you need send file as string use Base64 convert
var byteArray = new byte[] {1,2,3,4,5,6,7,8,9};
var encString = System.Convert.ToBase64String(byteArray);
var decBytes = System.Convert.FromBase64String(encString);
//result: byte[9] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }


text:
Q: Mechanics - Friction I'm confused by this question:

...
After resolving forces, I got $T=20g\sin{60} + 0.4\cdot 20g\cos{60} = 209N $
However, this is the answer for part B. After looking through solutions, the minimum tension required is when the frictional force is acting up the slope, lowering the amount of force needed to keep it up.
But, when would the frictional force be acting up the slope? This makes no sense to me. If the force of tension is upwards, surely the friction will always act oppositionally, downwards.
If anything, wouldn't the minimum effect of friction be 0, when the tension is equal to the component of mass parallel to the slope?
Making $T_{\text{min}} = 20g\sin{60}$.

$ F_{\text{friction}} \le \mu F_{\text{normal-reaction}}$

A: You have correctly noted that when the frictional force is acting up the slope, it lowers the amount of force needed to keep the package up. So for the part A of the problem you have to consider it with a negative sign. This leads you to a minimum tension of
$$T=20g\sin{60} - 0.4\cdot 20g\cos{60} \approx 131N $$


text:
Q: How to validate dynamic datepicker in jquery .Validation()? I am trying to insert dynamic datepicker in the database. Everything works fine! except jquery .validation. Done a validation rule if the input fields are empty a required message should be displayed has "please select a date" for ex: if I add three dynamic rows, while kept it in empty and pressed submit button, it shows validation message as "Please select a date" Now move to the three rows!
a) In first row I have picked a date, then I pressed submit button, It shows "Please select a date" in remaining input fields
b) Then next I have selected a date in a second input field and press the submit button, In here what needs to happen is third input field shows the validation message, but the datepicker automatically show in the second input field. I don't know why is automatically showing datepicker in the second input field while its already date has picked...

            <button type="button" id="add_details_button" class="btn btn-info add_details_button"> Add Date</button>    //class name used for onclick to add row

                            Date
                            Delete

$(document).ready(function() {
    // Append table with add row form on add new button click
    $(".add_details_button").click(function(){    //button click to add row
        var index = $("#details").index();
        var randaom_val = Math.floor(Math.random() * 100000000)    //Generating unique key for the added row
        var row_index = index+randaom_val;
        var row = '
' +
            '<input class="datepicker_recurring_start" name="date[]" id="date'+row_index+'" data-date-format="dd/mm/yyyy" placeholder="Visit Date"  class="form-control"/>	' + '<button type="button" class="delete btn btn-danger">Delete</button>	' + '
'
        $("#details").append(row);
        $(".datepicker_recurring_start").datepicker({
        autoclose: true
    })
});
    // Delete row on delete button click
    $(document).on("click", ".delete", function() {
        $(this).parents("tr").remove();
    });
});

//Jquery Validation
$(function() {
    $("#add_date_form").validate( {
        // Rules for form validation
        rules: {
            'date[]': {
                required: true,
            },
        },
        // Messages for form validation
        messages: {
            'date[]': {
                required: 'Select a valid visit date'
            },
        },
        // Do not change code below
        errorPlacement: function(error, element) {
        error.insertAfter(element);
        },
        submitHandler: function(form) {
            var details_row_count = $('#details tr').length;
            if (details_row_count<=1) {
                var msg = '

 Invalid Input...';
                $.notific8(msg,{ theme: 'ruby',life: 500 });
                return false;
            }
            $('#submit_date').attr("disabled", true);
            form.submit();
        }
    });
});

A:

$(document).ready(function() {
var count=0;
    // Append table with add row form on add new button click
    $(".add_details_button").click(function(){    //button click to add row
        var index = $("#details").index();
        var randaom_val = Math.floor(Math.random() * 100000000)    //Generating unique key for the added row
        var row_index = index+randaom_val;
        var row = '
' +
            '<input class="datepicker_recurring_start" name="dateField['+count+']" id="date'+row_index+'" data-date-format="dd/mm/yyyy" placeholder="Visit Date"  class="form-control" required/>	' + '<button type="button" class="delete btn btn-danger">Delete</button>	' + '
';
            count=count+1;
        $("#details").append(row);
        $(".datepicker_recurring_start").datepicker({
           autoclose: true
        });
});
    // Delete row on delete button click
    $(document).on("click", ".delete", function() {
        $(this).parents("tr").remove();
    });
});

//Jquery Validation
$(function() {
 $("#add_date_form").validate();

    $("#add_date_form").validate( {
        // Rules for form validation

        // Messages for form validation
        messages: {
            'dateField[]': {
                required: 'Select a valid visit date'
            },
        },
        // Do not change code below
        errorPlacement: function(error, element) {
        error.insertAfter(element);
        },
        submitHandler: function(form) {
            var details_row_count = $('#details tr').length;
            if (details_row_count<=1) {
                var msg = '

 Invalid Input...';
                $.notific8(msg,{ theme: 'ruby',life: 500 });
                return false;
            }
            $('#submit_date').attr("disabled", true);
            form.submit();
        }
    });
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<form name="add_date_form" id="add_date_form" method="POST" autocomplete="off" class="form-separated">

            <button type="button" id="add_details_button" class="btn btn-info add_details_button"> Add Date</button>

                            Date
                            Delete

                <button type="submit" name="submit_date" id="submit_date" class="btn btn-primary submit"> Submit</button>

</form>

If you create inputs with same name won't work
<input type="text" name="date[]" />
<input type="text" name="date[]" />
<input type="text" name="date[]" />
<input type="text" name="date[]" />

Instead of this
 <input type="text" name="date[0]" />
    <input type="text" name="date[1]" />
    <input type="text" name="date[2]" />
    <input type="text" name="date[3]" />

Just add indexes for each inputs
and in validator write rules for dateField[] or include required attribute in input tag.
I hope this will help you.


text:
Q: How can i add a setOnClickListener to my ListView Android I am new on Stack Overflow and i read this Thread ( ListView with Add and Delete Buttons in each Row in android ) and i implemented the Answer ( https://stackoverflow.com/a/23021960/7262380 ) in my code. All works fine. But now i want that if i click on a List View Item that anything happen what i have to do?
My actual Code (list Adapter)
package de.control;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;

import java.util.ArrayList;

public class listAdapter extends BaseAdapter implements ListAdapter {

    //Create Variables

    private ArrayList<String> list = new ArrayList<String>();
    private ArrayList<Sort> aktuelleObjektListe = new ArrayList<>();
    private Context context;
    public static DBHelper dataSource;
    TextView quantity = null;
    public static final String LOG_TAG = listAdapter.class.getSimpleName();

    //Finished

    //Create ListAdapter

    public listAdapter(ArrayList<String> list, Context context) {
        this.list = list;
        this.context = context;
        dataSource = new DBHelper(context);
        dataSource.open();
        aktuelleObjektListe = dataSource.getAllSorts();
        dataSource.close();
    }

    //Finished

    //Unused but required

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int pos) {
        return list.get(pos);
    }

    @Override
    public long getItemId(int pos) {
        return 0;
        //just return 0 if your list items do not have an Id variable.
    }

    //Finished

    //Update ListView ( is Called by "adapter.notifyDataSetChanged();" )

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View view = convertView;
        if (view == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.listlayout, null);

        }

        TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
        listItemText.setText(list.get(position));

        quantity = (TextView)view.findViewById(R.id.quantity_double);
        quantity.setText( Integer.toString(  aktuelleObjektListe.get(position).getQuantity()  ) );

     //Finished

        //Handle ADD and DELETE Button

        Button add1toSort = (Button)view.findViewById(R.id.add1toSort);
        Button remove1fromSort = (Button)view.findViewById(R.id.remove1fromSort);

    add1toSort.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {

            dataSource.open();

            Sort sort = dataSource.getAllSorts().get(position);

            dataSource.updateSortInDB(sort.getId(), sort.getSort(), (sort.getQuantity() + 1) );

            aktuelleObjektListe = dataSource.getAllSorts();

            dataSource.close();

            notifyDataSetChanged();
        }
    });

    remove1fromSort.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) {

            dataSource.open();

            Sort sort = dataSource.getAllSorts().get(position);

            dataSource.updateSortInDB(sort.getId(), sort.getSort(), (sort.getQuantity() - 1) );

            aktuelleObjektListe = dataSource.getAllSorts();

            dataSource.close();

            notifyDataSetChanged();
        }
    });

    //Finished
    return view;
}

}

My actual Code (MainActivity)
package de.control;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;

public class overview extends AppCompatActivity {

    //Create Variable

    public static DBHelper dataSource;
    public static final String LOG_TAG = overview.class.getSimpleName();
    public static final String tmp = "Test";

    ListView possessionList;
    Button addSort;

    listAdapter adapter;
    public ArrayList<String> listItems;
    public static ArrayList<Sort> Objects;

    //Finished

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.overview);

        // Create ListView (ID: possessionList)

        dataSource = new DBHelper(this);
        dataSource.open();
        Objects = dataSource.getAllSorts();

        possessionList = (ListView)findViewById(R.id.overview_possessionList);
        listItems = new ArrayList<String>();

        adapter = new listAdapter(listItems, this);
        possessionList.setAdapter(adapter);

        Log.d(LOG_TAG, "Die Datenquelle wird geöffnet.");

        Log.d(LOG_TAG, "ListView wird Aktuelisiert");
        updateList();

        Log.d(LOG_TAG, "Die Datenquelle wird geschlossen.");
        dataSource.close();

        //Finished

        // Handle what happend by Pressing a List Item (DOESENT WORK)

         possessionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Log.d(LOG_TAG, "Test");
            }
        });

        //Finished

        // Switch Label on Button (ID: addSort)

        addSort = (Button)findViewById(R.id.overview_completeAddition);
        final Intent addIntent = new Intent(overview.this,addsort.class);

        addSort.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                startActivity(addIntent);
            }
        });

        //Finished
    }

    // Add all Objekts to the ListView

    public boolean updateList()
    {
        try {
            listItems.clear();

            Objects = dataSource.getAllSorts();

            for (int i = 0; i < Objects.size(); i++) {
                listItems.add(Objects.get(i).getSort());
            }

            adapter.notifyDataSetChanged();

            return true;
        }
        catch (Exception ex){
            return false;
        }
    }

    //Finished

    //Add the Menü

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //Finished

}

A:
How can i add a setOnClickListener to my ListView Android

You should implement setOnItemClickListener to your possessionList listView
possessionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // your code
    }
});

Another alternative would be add android:descendantFocusability="blocksDescendants" in the LinearLayout or RelativeLayout, not inside listView element.
Example
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            .....
    android:descendantFocusability="blocksDescendants"
    tools:context="de.control.overview">

A: possessionList.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {

        Log.i("Hello!", "Y u no see me?");

    }
});

from ListView with OnItemClickListener android

A: It would be better for you to use recyclerview instead of listView.
// Item Click Listener for the listview
 OnItemClickListener itemClickListener = new OnItemClickListener() {
       @Override
       public void onItemClick(AdapterView<?> parent, View container, int
                                     position, long id) {
                // Getting the Container Layout of the ListView
                LinearLayout linearLayoutParent = (LinearLayout) container;

                // Getting the inner Linear Layout
                LinearLayout linearLayoutChild = (LinearLayout )
                 linearLayoutParent.getChildAt(1);

                // Getting the Country TextView
                TextView tvCountry = (TextView) linearLayoutChild.getChildAt(0);

                Toast.makeText(getBaseContext(), tvCountry.getText().toString(),
                 Toast.LENGTH_SHORT).show();
            }
        };

        // Setting the item click listener for the listview
        listView.setOnItemClickListener(itemClickListener);

A: For example, If I have a list view like this:
ListView mListView = (ListView) mLayout.findViewById(R.id.my_list_view);

You can use setOnItemClickListener for click on each item in your list view event:
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //Do what you want to each item here
    }
});

Example with more details: https://www.androidhive.info/2011/10/android-listview-tutorial/

A: Try adding android:focusable="false" to your text views and buttons
    in your listlayout.xml elements and
 add this line android:descendantFocusability="blocksDescendants" in list layout's parent layout.


text:
Q: python: How can combine rows in dataframe I tried to combine rows with apply function in dataframe but couldn't.
I would like to combine rows to one list if column (c1+c2) information is same.
for example
Dataframe df1
         c1  c2  c3
    0    0   x  {'a':1 ,'b':2}
    1    0   x  {'a':3 ,'b':4}
    2    0   y  {'a':5 ,'b':6}
    3    0   y  {'a':7 ,'b':8}
    4    2   x  {'a':9 ,'b':10}
    5    2   x  {'a':11 ,'b':12}

expected result
Dataframe df1
        c1   c2  c3
    0    0   x  [{'a':1 ,'b':2},{'a':3 ,'b':4}]
    1    0   y  [{'a':5 ,'b':6},{'a':7 ,'b':8}]
    2    2   z  [{'a':9 ,'b':10},{'a':11,'b':12}]

A: Source Pandas DF:
In [20]: df
Out[20]:
   c1 c2                  c3
0   0  x    {'a': 1, 'b': 2}
1   0  x    {'a': 3, 'b': 4}
2   0  y    {'a': 5, 'b': 6}
3   0  y    {'a': 7, 'b': 8}
4   2  x   {'a': 9, 'b': 10}
5   2  x  {'a': 11, 'b': 12}

Solution:
In [21]: df.groupby(['c1','c2'])['c3'].apply(list).to_frame('c3').reset_index()
Out[21]:
   c1 c2                                       c3
0   0  x     [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}]
1   0  y     [{'a': 5, 'b': 6}, {'a': 7, 'b': 8}]
2   2  x  [{'a': 9, 'b': 10}, {'a': 11, 'b': 12}]

NOTE: I would recommend you to avoid using non-scalar values in Pandas DFs cells - this might cause various difficulties and performance issues


text:
Q: Como posso criar um CheckBox utilizando o Helper Html.CheckBoxFor para um campo Nullable? Meu campo está da seguinte forma em minha classe:
public bool? meuCampo { get; set; }

E em minha view está assim:
@Html.CheckBoxFor(m => m.meuCampo)

Só que dessa forma não é permitido, porque não posso converter explicitamente o tipo bool? para bool, então para tentar resolver isso fiz da forma abaixo, usando cast:
@Html.CheckBoxFor(m => (bool)m.meuCampo)

Pórem, assim também ocorre um erro que é o seguinte:
Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Então de acordo com os fatos, teria alguma outro forma de criar checkbox, utilizando o Helper Html, com propriedades do tipo Nullable<bool>?

A: Vale a pena dar uma olhada em EditorTemplates do Asp.NET MVC. Eles possuem um padrão de CoC (Convention over Configuration) de implementação. Para configurar você pode criar um template em:
Views\Shared\EditorTemplates\Boolean.cshtml
@model Boolean?
@Html.CheckBox("", Model.HasValue && Model.Value)

E utilizar na sua view:
@Html.EditorFor(m => m)
@Html.LabelFor(m => m)

Exemplo: Extending Editor Templates for ASP.NET MVC

A: Yuri, o CheckBoxFor espera um bool, isto pq o checked tem apenas dois estados, selecionado ou não.
opcionalmente você pode usar o HtmlHelper.CheckBox e informar o nome da propriedade como string.
@Html.CheckBox("meuCampo", Model.HasValue && Model.Value)

caso realmente precise trabalhar com três estados, utilize o attributo indeterminate:
@{
dynamic htmlAttributes = new ExpandoObject();
if (!Model.HasValue)
    htmlAttributes.indeterminate = "indeterminate";
}
@Html.CheckBox("meuCampo", Model.HasValue && Model.Value, htmlAttributes as IDictionary<string, Object>;)


text:
Q: Suggestions for linux/unbuntu with access to usb port I need to get a linux or ubuntu (the former preferably) on windows10 and have it have access to the usb port. Anyone have suggestions on where I should start?

A: If you boot into (say) Ubuntu running from a USB drive then you will have instant access to the other USB ports by default in a file-manager window.
But if you're trying to see the files on the actual USB which is already running the Ubuntu install you can:

*

*Use df -h to find out the path of your USB drive dev directory (eg. /dev/sda1).

*Create a mounted directory there with : cd && mkdir temp_usb

*Mount a new USB device into the that new directory with sudo mount /dev/sda1 temp_usb
You will then be able to browse to temp_usb.
You can also use lsusb | more to see what's connected to the USB ports which might help you troubleshooting.


text:
Q: How to create unit tests for a FastAPI endpoint that makes request to another endpoint? I have a FastAPI app that makes requests to other endpoint within a function that handles a particular request.
How can I build unit tests for this endpoint using fastapi.testclient.TestClient?
import fastapi
import requests
import os

app = fastapi.FastAPI()

# in production this will be a k8s service to allow for
# automatic scaling and load balancing.
# The default value works when the app is run using uvicorn
service_host = os.environ.get('SERVICE_HOST', 'localhost:8000')

@app.post('/spawner')
def spawn():
    # an endpoint that makes multiple requests to set of worker endpoints
    for i in range(4):
         url = 'http://'+service_host+f'/create/{i}'
         requests.post(url)
    return {'msg': 'spawned the creation/update of 4 resources'}

@app.post('/create/{index}')
def worker(index: int):
    # an endpoint that does the actual work of creating/updating the resource
    return {'msg': f'Created/updated resource {index}'}

A: How to write the unit tests depends on what specifically you want to be checking.
For example, from your sample code, if you just want to check that your /spawner endpoint properly calls your /create endpoint a certain number of times, you can use Python's unittest.mock.patch to patch the requests.post call such that it doesn't make the actual call, but you can inspect the call it would have made. (See How can I mock requests and the response? for examples on how to mock external calls made by the requests library.)
You still use FastAPI's TestClient to make the call to your endpoint, but while the .post call is patched:
from fastapi.testclient import TestClient
from main import app

from unittest.mock import patch

def test_spawn():
    client = TestClient(app)
    mocked_response = requests.Response()
    mocked_response.status_code = 200

    with patch("requests.post", return_value=mocked_response) as mocked_request:
        response = client.post("/spawner")

    # Expect that the requests.post was called 4 times
    # and it called the /create/{index} endpoint
    assert mocked_request.call_count == 4
    called_urls = [call.args[0] for call in mocked_request.call_args_list]
    assert called_urls[0].endswith("/create/0")
    assert called_urls[1].endswith("/create/1")
    assert called_urls[2].endswith("/create/2")
    assert called_urls[3].endswith("/create/3")

    # Expect to get the msg
    assert response.status_code == 200
    assert response.json() == {"msg": "spawned the creation/update of 4 resources"}

patch returns a Mock object, which has attributes like call_count telling you how many times the requests.post function was called and a call_args_list storing the arguments for each call to requests.post. Then, your test can also assert that if everything behaved as expected, then it should return the expected response.
Now, going back to what I said, the usefulness of this test largely depends on what specifically are you hoping to gain from writing the tests. One problem with this test is that it isn't strictly black-box testing, because the test "knows" how the endpoint is supposed to work internally. If the point is to make sure, for example, that calling /spawner with some query parameter ?count=N results in N number of spawned resources, then maybe this kind of test is useful.
Another thing, this kind of test makes sense if you are making actual external calls to some other API, and not to your own endpoint. User JarroVGit mentioned in the comments that a better implementation would be, instead of making a POST request, you can refactor /spawner to call the endpoint function directly and pass the /create response:
@app.post("/spawner")
def spawn():
    # an endpoint that makes multiple requests to set of worker endpoints
    results = [worker(i) for i in range(4)]
    return {
        "msg": "spawned the creation/update of 4 resources",
        "results": results,
    }

@app.post("/create/{index}")
def worker(index: int):
    # an endpoint that does the actual work of creating/updating the resource
    worker_inst.create(index)
    return {"msg": f"Created/updated resource {index}"}

The test can be made simpler by patching whatever is in /create to not create the actual resources (here, I'm assuming some sort of a worker_inst.create(index) that does the actual creation):
def test_spawn():
    client = TestClient(app)

    # Patch the actual create/update resources to *not* create anything
    with patch.object(WorkerInst, "create"):
        response = client.post("/spawner")

    # Expect to get the msg
    assert response.status_code == 200
    assert response.json() == {
        "msg": "spawned the creation/update of 4 resources",
        "results": [
            {"msg": "Created/updated resource 0"},
            {"msg": "Created/updated resource 1"},
            {"msg": "Created/updated resource 2"},
            {"msg": "Created/updated resource 3"},
        ],
    }

I don't know what kind of "resources" your app is creating, but you can possibly convert that unit test into a more useful integration test, by removing the patch-ing of worker and just letting the worker create the resources, then let the test assert that 1) the correct resources were created, and 2) the /spawner endpoint returned the expected response. Again, depends on what "resources" is and the purpose of your tests.


text:
Q: titanium maps user location near annotation Im building an app with titanium and i am creating multiple annotations on a google map.
My question is if somehow i can check if user location is inside an annotation and lets say fire an alert. Is this possible?
In a similar project with javascript i was creating circles around annotations and then checking if user was inside this circle.
Something like this:
Circles[k] = new google.maps.Circle({
    map: map,
    clickable: false,
    radius: 35,
    fillColor: '#fff',
    fillOpacity: .6,
    strokeColor: '#313131',
    strokeOpacity: .4,
    strokeWeight: .8,
    center: new google.maps.LatLng(json.markers[k].lat, json.markers[k].lon)
});
BoundsArray[k] = Circles[k].getBounds();

Thank you

A: Geofencing (http://mobile.tutsplus.com/tutorials/iphone/geofencing-with-core-location/)
Geofencing is the process in which one or more geofences are monitored and action is taken when a particular geofence is entered or exited. Geofencing is a technology very well suited for mobile devices. A good example is Apple's Reminders application. You can attach a geofence to a reminder so that the application notifies you when you are in the vicinity of a particular location (figure 1). This is incredibly powerful and much more intuitive that using traditional reminders that remind you at a certain date or time.
IOS Module Implementation for Titanium:
http://www.clearlyinnovative.com/blog/post/34758523489/appcelerator-titanium-quickie-ios-geofencing-module#.UZVL3CtARYg
I believe there is a tutorial on converting Skyhook's SDK to a module in Titanium.  This looks like the result.
https://github.com/aaronksaunders/ClearlyInnovativeSkyhookModule


text:
Q: Why $PSL_3(\mathbb F_2)\cong PSL_2(\mathbb F_7)$? Why are groups $PSL_3(\mathbb{F}_2)$ and $PSL_2(\mathbb{F}_7)$ isomorphic?
Update. There is a group-theoretic proof (see answer). But is there any geometric proof? Or some proof using octonions, maybe?

A: (A sketch of a proof from http://www.math.vt.edu/people/brown/doc/PSL(2,7)_GL(3,2).pdf by E.Brown and N.Loehr.)
$PSL_3(\mathbb F_2)$ is the group of automorphisms of $\mathbb F_8$ as a vector space over $\mathbb F_2$. Fix a generator $x$ in $\mathbb F_8^{\times}$. It defines a map $\mathbb P^1(\mathbb F_7)\to\mathbb F_8$: $k\mapsto x^k$ (we define $x^\infty:=0$).
Now, for $f\in PSL_2(\mathbb F_7)$ the map $x^k\mapsto x^{f(k)}$ is, in general, not $\mathbb F_2$-linear, but the map $x^k\mapsto x^{f(k)}+x^{f(\infty)}$ is$^1$. And the map $T:f\mapsto(x^k\mapsto x^{f(k)}+x^{f(\infty)})$ gives a desired isomorphism $PSL_2(\mathbb F_7)\to PSL_3(\mathbb F_2)$.
$^1$ There is no conceptual explanation in the paper, but a check for generators of $PSL_2(\mathbb F_7)$ isn't hard --- and a check that $T$ is a homomorphism finishes the proof.

A: There is a reasonably geometric proof in Section 1.4 of Noam Elkies' The Klein Quartic in number theory.  A very rough summary is as follows.  The unique simple group $G$ of order $168$ has a $3$-dimensional irreducible representation $V$ which is defined over a number field $k$.  By reducing this representation modulo a prime over $2$ we obtain a $3$-dimensional representation of $G$ over $\mathbb{F}_2$ which identifies $G$ with $\text{GL}_3(\mathbb{F}_2)$ by simplicity (and a counting argument).  By reducing this representation modulo a prime over $7$ we obtain a $3$-dimensional representation of $G$ over $\mathbb{F}_7$ which is, as it turns out, the symmetric square of the defining representation of $\text{PSL}_2(\mathbb{F}_7)$.

A: (Idea of a proof from V.Dotsenko's paper in http://www.mccme.ru/free-books/matprosd.html (in Russian))
Consider 28-element set of 4-tuples of points on $\mathbb{P}^1(\mathbb{F}_7)$ with cross-ratio equal to 3. Identifying 4-tuple with its complement (recall that there are exactly 8 points on $\mathbb{P}^1(\mathbb{F}_7)$) one gets 14-element set $X$ — exactly the number of points + the number of lines on $\mathbb{P}^2(\mathbb{F}_2)$. The set $X$ consists of 2 orbits of $PSL_2(\mathbb F_7)$, $P$ and $L$. Define a tuple from $P$ and a tuple from $L$ to be incident if they intersect by 2 elements. Claim: 1) result is indeed $\mathbb{P}^2(\mathbb{F}_2)$; 2) induced homomorphism $PSL_2(\mathbb{F}_7)\to PSL_3(\mathbb F_2)$ is an isomorphism.

Update (2 years later). This is just Klein correspondence!
For any 8-element set $X$ its powerset $2^X$ is a vector space over $\mathbb F_2$. Let $V$ be the quotient of the subspace generated by subset with even number of elements by $\langle X\rangle$. Now the set $Q$ of 4-tuples of points of X up to complement can be viewed as a Klein quadric (aka $Gr(2,4)$, aka $PGr(1,3)$) inside $\mathbb P(V)$. Permutations of $X$ act on planes on $Q$, and these planes correspond to points and planes of $\mathbb P^3$. Now even permutations map points to points and planes to plains and this gives isomorphism $A_8\to PSL_4(\mathbb F_2)$.
Now for $X=\mathbb P^1(\mathbb F_7)$ its restriction on $PSL_2(\mathbb F_7)\subset A_8$ gives isomorphism $PSL_2(\mathbb F_7)\to PSL_3(\mathbb F_2)\subset PSL_4(\mathbb F_2)$.

A: At the last joint meetings in SF there was a talk about exactly this.
http://www.ams.org/amsmtgs/2124_abstracts/1056-z1-379.pdf
I went to the talk but I don't remember the explicit isomorphism; but at the very least a very concrete answer exists.

A: Can't leave comments yet, but the details of there being only one simple group of order 168, and why PSL(2,7) and PSL(3,2) are order 168 and simple, are spelled out on pages 141-147 in Smith and Tabachnikova's "Topics in Group Theory".
Steve

A: Both are simple groups of order 168, and each simple group of order $168$
is isomorphic to $PSL_2(7)$. An extended exercise, with hints. Prove the following:
Let $G$ be a simple group of order $168$.
It has $8$ Sylow $7$-subgroups.
It can be identified with a subgroup of $A_8$.
Labelling the objects it acts on as $\infty,0,1,\ldots,6$
one Sylow $7$-subgroup is generated by $g=(0\ 1\ 2\ 3\ 4\ 5\ 6)$.
The group $G$ is $2$-transitive.
The normalizer of $\langle g\rangle$ is generated by $g$ and
$h=(1\ 2\ 4)(3\ 6\ 5)$.
The setwise stabilizer $H$ of $\{\infty,0\}$ is generated by $h$
and another element $k$ which is the product of $(\infty\ 0)$ and
three other disjoint transpositions.
If $H$ is cyclic, then the Sylow $2$-subgroup of $G$ would be unique,
leading to a contradiction.
So $H$ is nonabelian and we can take $k=(\infty\ 0)(1\ 6)(2\ 3)(4\ 5)$.
Finally $G$ is $PSL_2(7)$.

A: The group $G=\operatorname{PSL}_2(7)$ acts on $X=P^1(\mathbb{F}_7)$. Fix $p\in X$, and consider the action of the stabilizer subgroup $G_p=\{g\in G:g\cdot p=p\}$ on the set $\binom{X\setminus\{p\}}{3}$ of $3$-element subsets of $X\setminus\{p\}$. It has three orbits, of sizes $7$, $7$ and $21$; this can be checked by considering cross-ratios. Pick one of the small ones: one can check that it is a triple Steiner system $S(2,3,7)$, so it is isomorphic as a design, to $P^2(\mathbb{F}_2)$.
Playing a bit with this construction can be used to realize the isomorphism explicitely.
Later. An observation, which helps explainwhy this works, is that if $o\in\binom{X}{4}$ is one of the $G$-orbits of size $14$, then the automorphism group of $o$ (that is, the set of permutations of $X$ which map elements of $o$ to elements of $o$) is $\operatorname{GL}_3(\mathbb{F}_2)\rtimes\mathbb{F}_2^3$, the group of affine maps of $\mathbb{F}_2^3$ (here  \rtimes is supposed to mean crossed product). Fixing an element $p\in X$, as I did above, amounts to picking a 'zero' in $\mathbb{F}_2^3$ viewed as an affine space, that is, looking at it as a vector space. (This puts a structure of affine $3$-space over $\mathbb{F}_2$ on $X$, and if we start with the other $14$-element orbit $o'\in\binom{X}{4}$ we get another structure of affine $3$-space over $\mathbb{F}_2$; $\operatorname{PGL}_2(7)$ is precisely the set of permutations of $X$ which preserves both affine structures)


text:
Q: SharedPreferences default values I have a settings.xml file that contains Preferences for my app. All the values by default are set to "true" and its used by PreferenceActivity in my app.
In my main activity I read the values through
     SharedPreferences sp=PreferenceManager.getDefaultSharedPreferences(appContext);
     Boolean key = sp.getBoolean("M", false);

it gets me whatever I need at any run except the first time. Only when I open my app for the first time and doesn't open my settings menu I get "false". I mean I have to open menu and only after that the app run correctly.
Any suggestions?

A: Because yor are getting the default value for first time.
that is false -->
Boolean key = sp.getBoolean("M", false);

use this
Boolean key = sp.getBoolean("M", true);

A: Use sp.getBoolean("M", true); instead. Default values in preferences file is what it will be when preferences activity is first started. SharedPreferences know nothing about your settings.xml.
Alternatively you can have a separate defaults.xml file (or any other name) containing all the default values for all preferences. Then you use these values in both settings.xml (@bool/default_M_value) and your application (sp.getBoolean("M", getResources().getBoolean(R.bool.default_M_value))).
I personally would stick to first approach though.


text:
Q: ffmpeg: aphasemeter, meaning of measurement I tried really hard to find information online about phase and stereo imaging, but information is rather vague. I have been asked to keep the stereo image of an audio track between +0.5 and +1.0 but in the audio engineering world I keep hearing about a stereo image range of 180 degrees broken down into "center 90 range, left 45 range and right 45 range". I can't quite figure out what's asked of me exactly, beyond "don't make things too out of phase" which isn't very specific, especially after the numbers 0.5 and 1.0 have been thrown at me.
So, I remembered that outside of DAWs and goniometers plugins, ffmpeg's aphasemeter filter provides values between 1 and -1 where 1 is totally in phase (mono) and -1 is totally out of phase (I guess left channel and right channel are exactly opposite). This looks like the "between +0.5 and +1.0" requirement I've been asked to abide by.

*

*Over what time span is the output of aphasemeter calculated ? What time span is sensible to use ? Is it good to measure over 300ms like RMS ? Or 50ms because that's the time a 20Hz signal (lowest audible) does a full cycle ?

*How is this number between -1 and 1 calculated ?

*The phasing detection option of aphasemeter accepts a parameter between 90 and 180: how does that relate to -1 and 1 ?

*How does this relate to "center 90, left 45 and right 45", you see in all phase plugins ? I know a hard panned left (signal fully left, right channel muted) would be at the edge of the "center 90 range" and the goniometer would be leaning left at a 45 degree angle. Does that result in aphasemeter outputting 0.5 ? Edit: no it does not, I've tried to discard the right channel of an audio and evaluate phase with a phase meter, and it is not constant. Also I tried make left and right channel identical: the output is always 1.0 which is expected, but when I make left and right channel perfectly opposite, I don't always get -1.0 as output (actually I get it only rarely) but the output values are consistently negative. I don't really understand then what aphasemeter is outputting

Thank you for shedding some light on what these numbers really mean.

A: Audio is comprised of samples. A 48000 Hz stereo stream has 48000 samples in each channel (left and right) for each second of audio. However, these samples are chunked into frames; a typical frame size is 1024 samples (of each channel) but different codecs use different sizes. These samples may have varying bit depth and be either integer or floating-point values.
What the aphasemeter filter does is first convert the source stream to floating point so each sample value is between +1 and -1. It also converts it to a stereo stream. This means that all other channel layouts (mono, 5.1 ..etc) are rematrixed to stereo. Then for each pair of samples in a frame, it will calculate
   left * right * 2
-----------------------
left*left + right*right

This is the phase difference for a pair of samples. If the denominator is 0, then phase difference is 1. The mean phase across all pairs of samples in a frame is the phase difference measurement for that frame.
As for how these values correspond to angles, this answer may be of use: https://dsp.stackexchange.com/a/10916


text:
Q: How to print java System.out.println in jmeter UI Listner response data I just started playing with jmeter, I wrote a small java sampler test, which send request to server and get a UUID in response, I am printing this response as System.out.println in my test
I am running jmeter on windows, so this response get printed on cmd window and not in jmeter UI Listener, which is right ( since cmd is console out )
I wanted to find out, if there is any way to setup logger ?
what are standard practices to handle these situation in jmeter ?
I will appreciate if someone can explain with a small example

A: Use the the command-line option -j jmeterlogfile


text:
Q: What is the Python equivalent for the R function names( )? The function names() in R gets or sets the names of an object. What is the Python equivalent to this function, including import?
Usage:
names(x)

names(x) <- value

Arguments:
(x) an R object.
(value) a character vector of up to the same length as x, or NULL.
Details:
Names() is a generic accessor function, and names<- is a generic replacement function. The default methods get and set the "names" attribute of a vector (including a list) or pairlist.
Continue R Documentation on Names( )

A: In Python (pandas) we have .columns function which is equivalent to names() function in R:
Ex:
# Import pandas package
import pandas as pd

# making data frame
data = pd.read_csv("Filename.csv")

# Extract column names
list(data.columns)

A: not sure if there is anything directly equivalent, especially for getting names.  some objects, like dicts, provide .keys() method that allows getting things out
sort of relevant are the getattr and setattr primitives, but it's pretty rare to use these in production code
I was going to talk about Pandas, but I see user2357112 has just pointed that out already!

A: There is no equivalent. The concept does not exist in Python. Some specific types have roughly analogous concepts, like the index of a Pandas Series, but arbitrary Python sequence types don't have names for their elements.


text:
Q: Azure Instance with linux machine docker timing out on requests I have a python script in a docker that runs and collects data from an api on a loop.
`for idx, items in enumerate(SearchList):
#get access token
access_token = GetPricingAccTok()
#request id to get results
reqid = RequestIdCompSearch(items, access_token)

#api to get results by doing a while loop appending results together till api returns 100% as completed percentage
Result = GetReqResults(reqid, access_token)

Pricings = GetPricingDict(Result)

filenamepricing =  "pricinghistory/CorrectFormat/Pricings_Data_{idn}_{ts}.json".format(
        idn = idx,
        ts= dt.datetime.now().isoformat()
    )

GetAzContainer().upload_blob(
        name=filenamepricing,
        data=json.dumps(obj= Pricings, indent=4),
        blob_type='BlockBlob'
    )
`

When i run and test this code locally on my windows machine it works well without an issue and completes the requests
but in the docker on azure container instance it then returns an error showing that the connection has timed out. Not sure what the difference is between the running it locally and in the docker that i then recieve this error.
I have tried addinng this code at the start
import socket
from urllib3.connection import HTTPConnection
HTTPConnection.default_socket_options =(HTTPConnection.default_socket_options + [
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) #Enables the feature
,(socket.SOL_TCP, socket.TCP_KEEPIDLE, 45) #Overrides the time when the stack willl start sending KeppAlives after no data received on a Persistent Connection
,(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10) #Defines how often thoe KA will be sent between them
,(socket.SOL_TCP, socket.TCP_KEEPCNT, 60) #How many attemps will your code try if the server goes down before droping the connection.
]
)
but it still times out. showing the below error
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 445, in _make_request
six.raise_from(e, None)
File "<string>", line 3, in raise_from
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 440, in _make_request
httplib_response = conn.getresponse()
File "/usr/local/lib/python3.8/http/client.py", line 1348, in getresponse
response.begin()
File "/usr/local/lib/python3.8/http/client.py", line 316, in begin
version, status, reason = self._read_status()
File "/usr/local/lib/python3.8/http/client.py", line 277, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/local/lib/python3.8/socket.py", line 669, in readinto
return self._sock.recv_into(b)
File "/usr/local/lib/python3.8/ssl.py", line 1241, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/lib/python3.8/ssl.py", line 1099, in read
return self._sslobj.read(len, buffer)
TimeoutError: [Errno 110] Connection timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/site-packages/requests/adapters.py", line 440, in send
resp = conn.urlopen(
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 755, in urlopen
retries = retries.increment(
File "/usr/local/lib/python3.8/site-packages/urllib3/util/retry.py", line 532, in increment
raise six.reraise(type(error), error, _stacktrace)
File "/usr/local/lib/python3.8/site-packages/urllib3/packages/six.py", line 770, in reraise
raise value
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 699, in urlopen
httplib_response = self._make_request(
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 447, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
File "/usr/local/lib/python3.8/site-packages/urllib3/connectionpool.py", line 353, in _raise_timeout
raise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='service.xxx.com', port=443): Read timed out. (read timeout=None)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "src/script.py", line 298, in <module>
reqid = RequestIdCompSearch(items, access_token)
File "src/script.py", line 111, in RequestIdCompSearch
InitResp =rq.post( ReqUrl, headers= ReqHead,  data=Jsondata)
File "/usr/local/lib/python3.8/site-packages/requests/api.py", line 117, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 529, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/sessions.py", line 645, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python3.8/site-packages/requests/adapters.py", line 532, in send
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='service.xxxx.com', port=443): Read timed out. (read timeout=None)


text:
Q: how can i remove the quotes in around the string and the int in the data dumped in my yaml file I'm converting csv file to yaml file using python.how can i remove the quotes around the string and int in the yaml file and please also tell a way to remove ... between the lines and please also help with indentation
input in csv file is :-
{Field name,type,maxLength,Description}
{name,string,20,sdscbjxfgc xtcvhgx}
{DOB,Number,6,the date of birth}

my python code is:
def csvToYaml(csvFile, output):
stream = open(output, 'w',encoding='utf-8')
csvOpen = csv.reader(codecs.iterdecode(csvFile, 'utf-8'))
keys = next(csvOpen)
hardcoded=['type:object','properties:']
yaml.safe_dump(hardcoded,stream,default_flow_style=False,allow_unicode=True,sort_keys=False)
for row in csvOpen:
    new = 'description:|'
    list_1={row[0]:{
        'type':row[1],
        'MaxLength':row[2],
        }}
    yaml.safe_dump(list_1,stream,default_flow_style=False,sort_keys=False)
    yaml.safe_dump(new,stream,default_flow_style=False,sort_keys=False)
    yaml.safe_dump(row[3],stream,default_flow_style=False,sort_keys=False)

i'm expecting the output to be like :
type: object
properties:
  name:
    type: string
    MaxLength: 20
    description:|
      name of the person
  DOB:
    type: Number
    MaxLength: 6
    description:|
      the date of birth

but i'm getting this output:
type: object
properties:
  name:
    type: string
    MaxLength: '20'
description:|
...
sdscbjxfgc xtcvhgx
...
  DOB:
    type: Number
    MaxLength: '6'
description:|
...
the date of birth
...

A: This comlpete code (I had to add all the imports and file building etc):
With pyyaml:
import yaml
import csv

with open ("k.txt","w") as f:
    f.write("""{Field name,type,maxLength,Description}
{name,string,20,sdscbjxfgc xtcvhgx}
{DOB,Number,6,the date of birth}""")

def csvToYaml(csvFile, output):
    stream = open(output, 'w',encoding='utf-8')
    csvOpen = csv.reader(csvFile)
    keys = next(csvOpen)
    hardcoded=['type:object','properties:']
    yaml.safe_dump(hardcoded,stream,default_flow_style=False,allow_unicode=True,sort_keys=False)
    for row in csvOpen:
        list_1={row[0]:{
            'type':row[1],
            'MaxLength':row[2],
            'description:|':row[3]
            }}
        yaml.safe_dump(list_1,stream,default_flow_style=False,sort_keys=False)

with open("k.txt") as f:
    csvToYaml(f,"out.txt")

with open("out.txt") as f:
    print(f.read())

prints:
- type:object
- 'properties:'
'{name':
  type: string
  MaxLength: '20'
  description:|: sdscbjxfgc xtcvhgx}
'{DOB':
  type: Number
  MaxLength: '6'
  description:|: the date of birth}

You need to remove your "extraneous" dumping calls to yaml.safe_dump(new, ...). It has superflous characters in it, you might need to switch to some other yaml package or find the parameters that allow you to minimize the generated yaml.

With ruamel.yaml:
from ruamel.yaml import YAML
import csv

with open ("k.txt","w") as f:
    f.write("""Field name,type,maxLength,Description
name,string,20,sdscbjxfgc xtcvhgx
DOB,Number,6,the date of birth""")

yaml = YAML()
yaml.indent(mapping=4, sequence=6, offset=3)

def csvToYaml(csvFile, output):
    stream = open(output, 'w',encoding='utf-8')
    csvOpen = csv.reader(csvFile)
    keys = next(csvOpen)
    hardcoded=['type:object','properties:']
    yaml.dump(hardcoded,stream)
    for row in csvOpen:
        list_1= { row[0]: {
            'type':row[1],
            'MaxLength':row[2],
            'description:|':row[3]
            }}
        yaml.dump(list_1,stream)

with open("k.txt") as f:
    csvToYaml(f,"out.txt")

with open("out.txt") as f:
    print(f.read())

Output:
   -  type:object
   -  'properties:'
name:
    type: string
    MaxLength: '20'
    description:|: sdscbjxfgc xtcvhgx
DOB:
    type: Number
    MaxLength: '6'
    description:|: the date of birth

A: *

*As per basic python by default file opener will consider as string internally.
If you will replace 'MaxLength':row[2], with 'MaxLength':int(row[2]), then you will get expected output.

*[Que] How to remove quotes around 'properties:'
Ans. 1st parameter of yaml.safedump can accept any datatype. And in your scenario (properties: with colon) internally its considering as dictionary. So you can pass hard-coded value properties as dictionary instead of list and value as None.
Check given link for more information Can I dump blank instead of null in yaml/pyyaml?
I have not worked on YAML so, I am not sure whether it is optimal solution or not. Please upvote if you find my answer useful.

A: Only JSON solved similar issue for me, sorry YAML.


text:
Q: Why does my survey app make memory leak? (Multiple UIViews and UITextViews in one UIScrollView) I am trying to make a survey app but I can't make the memory management although I am using ARC. My app makes memory leak. I get memory warning. When I make my app in interface builder statically there is no problem but when i make my app programmatically I get memory problem. Why is that happening? Here is my code:
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
int soruAdedi = 20;
@interface ViewController ()

@end

@implementation ViewController
@synthesize scrollView2;
-(void)textViewBicimle: (UITextField *)textAlani{
    [textAlani.layer setBorderColor:[[[UIColor blackColor] colorWithAlphaComponent:1.0] CGColor]];
    [textAlani.layer setBorderWidth:1.0];
}

- (void) tableCiz:(NSMutableArray *)hucreler sutun:(int)sutunSayisi satir:(int)satirSayisi{
    int z = 0;
    for (int i =0;i<satirSayisi;i++){
        for(int j=0;j<sutunSayisi&&z<satirSayisi*sutunSayisi;j++,z++){
            [self textViewBicimle:[hucreler objectAtIndex:z]];
            [[hucreler objectAtIndex:z] setFrame:CGRectMake((20+j*100), (20+i*40), 100, 40)];
        }
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{

}

-(void)hucreArrayOlustur: (int)sutunSayisi suankiView:(UIView *)soruViewIki satir:(int)satirSayisi{
    for (int i = 0; i <sutunSayisi*satirSayisi; i++){
        textView = [[UITextField alloc]init];
        textView.text = @"dsgfdh";
        [hucreArray addObject:textView];
        [soruViewIki addSubview:textView];
    }
}

-(void)viewOlustur{
    for (int i = 0; i <soruAdedi; i++){
        hucreArray = [[NSMutableArray alloc]init];
        if (i == 0){
            soruView = [[UIView alloc]initWithFrame:CGRectMake(20, 20, 728, 0)];
            soruView.clipsToBounds = YES;
            soruView.backgroundColor = [UIColor lightGrayColor];
            [self hucreArrayOlustur:5 suankiView:soruView satir:10];
            [self tableCiz:hucreArray sutun:5 satir:10];
            CGRect frame = soruView.frame;
            CGRect frame2 = [[hucreArray objectAtIndex:49] frame];
            frame.size.height =  frame2.origin.y+frame2.size.height+34;
            soruView.frame = frame;
            [viewArray addObject:soruView];
            [scrollView2 addSubview:soruView];
        }
        else{
            CGRect frameGecici = [[viewArray objectAtIndex:i-1] frame];
            float geciciY = frameGecici.origin.y+frameGecici.size.height+1;
            soruView = [[UIView alloc]initWithFrame:CGRectMake(20, geciciY, 728, 0)];
            soruView.clipsToBounds = YES;
            soruView.backgroundColor = [UIColor lightGrayColor];
            [self hucreArrayOlustur:5 suankiView:soruView satir:10];
            [self tableCiz:hucreArray sutun:5 satir:10];
            CGRect frame = soruView.frame;
            CGRect frame2 = [[hucreArray objectAtIndex:49] frame];
            frame.size.height =  frame2.origin.y+frame2.size.height+34;
            soruView.frame = frame;
            [viewArray addObject:soruView];
            [scrollView2 addSubview:soruView];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    scrollView2.delegate = self;
    scrollView2.contentSize = CGSizeMake(0, 8000);
    viewArray = [[NSMutableArray alloc]init];
    [self viewOlustur];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setScrollView2:nil];
    [super viewDidUnload];
}
@end


text:
Q: Show that there exists exactly one number $x$ in $[0,1]$ s.t. $f(x)=x$
Suppose that $f$ is continuous and differentiable on $[0, 1]$, that
  $0\leq f (x) \leq 1$ for each $x\in [0, 1]$, and that $f '(x) \ne 1$
  for all $x \in [0, 1]$. Show that there exists exactly one number $x
> \in [0, 1]$ such that $f (x) = x$.

So far I have done proving there is at least one $x \in [0,1]$ by IVT.
If $f(0)=0$ and $f(1)=1$ then we are done
else, if $f(0)>0$ and $f(1)<1$.
Let $g(x)=x-f(x)$ then $g(1)= 1 -f(1)>0$ and $g(0)= - f(0)<0$
Then I am trying to prove there is exactly one $x \in [0,1]$ s.t $f(x)=x$
So am I suppose to prove this by contradiction with mean value theorem or Rolle's? If so, how should I set this up?

A: You have shown that $g(0)g(1)<0$ so there must be a $a\in[0,1]$ such that $g(a)=0$ , by IVT, thus $f(a)=a$.
If there is another $b\neq a$ (WLOG $b>a$) such that $f(b)=b$, then applying MVT on $[a,b]$ givves $f'(c)[b-a]=f(b)-f(a)\Rightarrow f'(c)=1$, for some $c\in(0,1)$, a contradiction.


text:
Q: Help with date formats What's the correct format to parse this string:
"Mon, 14 Mar 2011 15:36:00 GMT"
into a NSDate using NSDateFormatter?

A: NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss zzzz"];
NSDate *myDate = [dateFormatter dateFromString:strPubDate];

A: NSString *dateStr = [NSString stringWithString:@"Mon, 14 Mar 2011 15:36:00 GMT"];
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc] init] autorelease];
[dateFormat setDateFormat:@"EEE, d MMM yyyy HH:mm:ss zzzz"];
NSDate *date = [dateFormat dateFromString:dateStr];


text:
Q: Visual studio formatting of selection in CSS editor not working Some strange issue appeared while working in Visual Studio 2010.
 Formatting for whole CSS file works fine CTRL+K,CTRL+D, but trying to format code inside of selection CTRL+K,CTRL+F shows an error:
 The key combination (CTRL+K, CTRL+F) is bound to command (Format Selection) which is not currently available.

Does anybody know what causes this behaviour?

A: When trying the second command, were you still formatting CSS or a different file type (.cs)?
Code which requires compiling can't be edited whilst running (debugging). HTML, CSS and Javascript can be edited whilst the code is currently running.
Not sure if that is the cause of your issue but that is how I can reproduce it.


text:
Q: How to fix json saving error Spring Boot database? I have such model for saving:
@Table("EXPERIMENTS")
data class Experiment(
    @Id val id: Long,
    val userId: Long,
    val time: String,
    @JsonProperty
    val data: Any
)

such saving processor:
@PostMapping("/experiment")
fun saveUserExperiment(@RequestBody experiment: Experiment) = service.saveExperiment(experiment)

such service:
@Service
class ExperimentService(val db: ExperimentRepository) {
    fun saveExperiment(experiment: Experiment) = db.save(experiment)
...
}

and I save it via postman in such way:
POST /experiment HTTP/1.1
Content-Type: application/json
User-Agent: PostmanRuntime/7.29.2
Accept: */*
Postman-Token: 1c2aaf40-8933-4988-b92a-6694539c3aba
Host: localhost:8080
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 105

{
"userId":1,
"time": "2018-10-18 05:30:57.907",
"data": {"red":123,"blue":123,"green":123}
}

HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sat, 30 Jul 2022 15:57:55 GMT
Keep-Alive: timeout=60
Connection: keep-alive

{"id":7,"userId":1,"time":"2018-10-18 05:30:57.907","data":{"red":123,"blue":123,"green":123}}

during saving I receive such error:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.util.ReflectionUtils (file:/Users/_t/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.3.2/152489ed8223a6ad19065a3cd1ee6b9e20c0b82f/spring-core-5.3.2.jar) to field java.util.LinkedHashMap.head
WARNING: Please consider reporting this to the maintainers of org.springframework.util.ReflectionUtils
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

and also after fetching the list of models I receive such error:
Parameter specified as non-null is null: method com.example.demo.models.Experiment.<init>, parameter data

list I receive in such way:
@Query("select * from experiments")
fun getExperiments(): List<Experiment>

my database has such table:
experiments: table
    + columns
        id: int NN auto_increment = 1
        user_id: mediumtext NN
        time: timestamp default CURRENT_TIMESTAMP
        data: json
    + keys
        #1: PK (id) (underlying index PRIMARY)

I'm not sure whether it is ok that I receive 200OK response from the api but json field is null even if I have it filled.

A: There are two different things going on here. First, the minor one:
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.util.ReflectionUtils (file:/Users/_t/.gradle/caches/modules-2/files-2.1/org.springframework/spring-core/5.3.2/152489ed8223a6ad19065a3cd1ee6b9e20c0b82f/spring-core-5.3.2.jar) to field java.util.LinkedHashMap.head
WARNING: Please consider reporting this to the maintainers of org.springframework.util.ReflectionUtils
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

As the prefix shows, this is a warning, not an error: it's not stopping your program from working (though, as it says, a later Java release might).
They cause is an incompatibility between the version of Spring you're using and the Java Module System that was introduced in Java 9, and is discussed in this question. One simple workaround might be to run it on Java 8.

The actual error is this one:
Parameter specified as non-null is null: method com.example.demo.models.Experiment.<init>, parameter data

That's about nullability. As you probably know, Kotlin distinguishes between references that could be null, and those that can't.
You've defined your JSON property as: val data: Any, and the Any type is non-nullable: Kotlin won't allow it to hold a null value. (To allow a null, you'd specify it as Any?, with a question mark.)
However, the Spring framework is based on Java, which doesn't make that distinction: all its references can potentially be null. And so there are some unfortunate corner cases which throw up unexpected nulls like this.
For some reason, your DB query is returning a null value for that field; when it tries to construct an instance of your Experiment class to hold the returned data, the Kotlin runtime spots the null and gives the error above. (It's not spotted at compile-time, unfortunately, because Spring works much of its magic at run-time.)
So there are two potential approaches to fixing it:

*

*Prevent Spring returning null for that field. I don't think it's possible to guarantee this in all circumstances, as it might depend on what data can be in your database, as well as how the query is performed. (It's probably worth looking at your data and the query to understand why it's coming back as null, though.)

*Specify the field as nullable (Any?), and handle the null case yourself. That would make your code very slightly less clean, but a lot safer and more robust.


text:
Q: Is ActiveMQ + Spring STOMP good for scaling websockets, or should we look towards something else? We have a Spring Boot backend which also maintains bidirectional (STOMP over) websocket connections with clients (browser tabs). We've implemented this using STOMP Broker Relay (server side) + ActiveMQ (message broker). There's also a heartbeat message exchanged every 25s to keep connections alive.
Problem we are facing
Till about 1K connections, this setup seems to work fine.
Once it goes beyond few thousand connections in ActiveMQ, we are running into some weird issues:
browser is able to successfully connect and subscribe to a topic on ActiveMQ through Spring Boot, however no messages are successfully received by it, all while being able to exchange heartbeats every 25s!
Our Spring Backend has increased CPU utilization where there is one thread tcp-client-loop that consumes 1 full CPU.
We have also shared our complete investigation below.
Question
Is this architecture with some tunables, a good solution for scaling up to ~100k concurrent websocket connections tomorrow? If not, what are some industry recommended alternatives for sending notifications to a browser? We've also been looking at socket.io + redis pub/sub for the huge amount of references on the internet but unsure if it's actually a better approach.
Investigation so far

*

*Our backend logs show that events are being published and relayed to the client, however these events have an empty payload and contain stompMessageType as OTHER instead of the supposed value MESSAGE. We have also used a stomp client on the terminal to connect with ActiveMQ directly and noticed no messages coming in from subscribed topics during this period, so this has turned our attention towards something wrong on the ActiveMQ broker side.

*During this same high traffic time period, we've noticed our backend being stuck in a tcp-client-loop thread, however haven't been able to pinpoint if this is related to connections with the ActiveMQ server or not.
P.S. - we have decided to rule out the tcp connection limit during high traffic due to connections being established successfully. We've also configured ActiveMQ to accept 50k connections over STOMP instead of the default 1k.

*There's little to nothing we have been able to find out from ActiveMQ's logs (and web console) for errors around publishing or consuming, even at the DEBUG and TRACE log levels. CPU utilisation hovers around just 5% during this time.


text:
Q: Silent Letters In Words Containing Double Letters I'm doing an exercise, which says find the silent letters in some words. one of them is "OFFICE"

*

*Does this word have 1 or 2 silent letters? The final 'E'     Or     final 'E' + one of 'F's

*Are double letters considered one sound? if yes, Do they have any roles? for example putting stress there!

Consider the word 'aim'. Is that "i" considered silent letter? what about "steak". is that "a" useless and let's say that 'e' is making the 'eɪ' sound? these are many words like this. veil, may, rain, awful(NAmer)


text:
Q: ffmpeg streaming very inefficiently basically what I'm doing is grabbing a twitch stream via streamlink and outputting it to a youtube stream via ffmpeg. When looking up how I could do that I (admittedly) just copied the first command on the documentation and tweaked it a bit and ended up with this command:
 streamlink -O twitch.tv/boxbox best | ffmpeg -i pipe:0 -s 1920x1200 -framerate 30 -vcodec libx264 -preset veryfast -s 1280x720 -threads 0 -f flv "rtmp://a.rtmp.youtube.com/live2/-------------"

running this command works, a stream appears on youtube, but it is very laggy. the console tells me that I'm streaming at a consistent 9fps which is not really what I want. Since this is my very first experience with ffmpeg I dont really know what is causing this. It might even be my server since I'm running a pretty cheap debian VPS. Is this expectable or can I tweak this to stream it better?

A:
ffmpeg streaming very inefficiently
Since this is my very first experience with ffmpeg I dont really know what is causing this.

What makes you think it's inefficient?  You're re-encoding video.  This takes a ton of CPU.

It might even be my server since I'm running a pretty cheap debian VPS.

Very likely.
In any case you have a couple options.  The best thing to do is to not re-encode the video.  If Twitch is giving you H.264 and AAC audio, then use -vcodec copy -acodec copy.
Another thing you can do (although not likely on a VPS) is force hardware acceleration.  This will result in some mediocre video quality (not that you probably care anyway since you're already re-encoding a previously encoded video) but will run without significant impact on the CPU.  FFmpeg has support for a bunch of GPUs.  You'll have to pick one compatible with whatever hardware you're using.
What you should do is not relay the stream, but stream multiple streams from the original source.  This will help you avoid quality loss by re-encoding.


text:
Q: Design pattern for application with multiple editions I would be curious to know if there is a design/architectural pattern for creating applications that have multiple editions (for example how Windows has Home, Standard or Ultimate editions).
The main idea is that I would like to create an application that gives the users different features, depending on the edition that they have (basic, advanced, full). Someone suggested using plugins... is this a good aproach?
Thanks!

A: I think patterns won't help you in this situation.
All these versions (basic, advanced, full) differs in various set of modules. If you support good modularity in your program you can have only separated build scripts corresponding to each of your version where you can setup set of modules.

A: There are a number of options.
Conceptually, the simplest thing is to build 3 different applications, re-using where you can. So, you might have an "engine", providing shared functionality, and 3 separate applications running on the engine - "basic", "advanced", "full". This is kinda what the MS operating system flavours are - the engine is the basic operating system, and the different editions contain different applications built on top of the engine.
The benefit of this route is that you can create a conceptually valid product - you don't have lots of dependencies between editions, and if the "full" edition decides not to include features from the "basic" edition because they don't make sense, they don't have to worry about breaking that dependency.
The second model is to build a single application, and control its behaviour through configuration - either at build time or at run time. "ifdef" for instance allows a single C code file to target different operating systems; the number of processors supported by different flavours of the same SQL database engine might be controlled by run-time configuration.
This has the advantage that you have a single code base to manage, but introduces very tight coupling between the editions, and quickly becomes unmanageable.
Lots of applications use the "plug-in" model; this is a variation on the first option, in that it requires you to build a framework application first, and the capabilities of each edition are limited by what your framework can do. Many games ware designed in this way, and the difference between versions basically depends on which plug-ins ship with the game.
This is architecturally very clean, but presents real risks to the project - your smartest developers will all want to work on the framework, and nobody wants to work on the actual product; if your framework developers guess wrong on what the real requirements are, you end up with a brilliant framework that supports the wrong product. Also, the framework tends to focus very much on computer sciencey issues like logging or plug-in configuration, and not so much on the real business questions. I've seen this at first hand, and it was kinda tragic.
Unless you have unlimited time and budget, I'd start with option 1, and evolve to option 3 once you've got your first release out the door.


text:
Q: Why is my edit issue affect other columns? Link to my sheet: https://docs.google.com/spreadsheets/d/1gkWCU0fHotORi-urOfuHjGGiqrnYcdtZQ9bZhm7XLIk/edit?usp=sharing
Question:
How can I fix an edit issue when deleting dates or unchecking a checkbox without it affecting other columns. (please see images)
How my 'Function' button works:
Menu panel: Function > Insert New Column
Insert as many columns as I want by manipulating the script.
How my AutoTimeStamp script works:
Once checkboxes are checked (Column C), Dates automatically apply to Column D.
How my 'Copy' script works:
Once Insert New Column is activated, it makes a copy of Columns C and D from left to right. This also applies the TimeStamp feature to every newly created column.
Function Button:

Newly Created Columns

Clicking checkboxes and autodating is successful

Error When deleting dates

Error when on last column

Here is the Insert New Column Function:

var ss = SpreadsheetApp.getActive();

function onOpen() {
  var menu = [{name:"Insert New Columns", functionName:"addColumn"}];
  ss.addMenu("Functions", menu);
}

function addColumn() {
  var sh = ss.getActiveSheet(), lCol = sh.getLastColumn();
  var lRow = sh.getLastRow(), range = sh.getRange(1,lCol-1,lRow,2);
  sh.insertColumnsAfter(lCol,10);
  var newRange = sh.getRange(1,lCol+1,lRow,10);
  var columnWidths = SpreadsheetApp.CopyPasteType.PASTE_COLUMN_WIDTHS
  range.copyTo(newRange);
  range.copyTo(newRange,columnWidths,false);
  newRange.setFormulas(newRange.getFormulas());
}

Here is the AutoTimeStamp script:

var COLUMNTOCHECK = 3;
var DATETIMELOCATION = [0, 1];
var SHEETNAME = 'Training Dash'

function onEdit(e) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  if( sheet.getSheetName() == SHEETNAME ) {
    var selectedCell = ss.getActiveCell();
    if( selectedCell.getColumn() >= COLUMNTOCHECK) {
      var dateTimeCell = selectedCell.offset(DATETIMELOCATION[0],DATETIMELOCATION[1]);
      dateTimeCell.setValue(new Date());
      }
  }
}

This is the Copy script along side some macros.

function Copy() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getActiveSheet().insertColumnsAfter(spreadsheet.getActiveRange().getLastColumn(), 2);
  spreadsheet.getActiveRange().offset(0, spreadsheet.getActiveRange().getNumColumns(), spreadsheet.getActiveRange().getNumRows(), 2).activate();
  var sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn(), sheet.getMaxRows(), 1).activate();
  sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn() - 2, sheet.getMaxRows(), 2).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
};

function UntitledMacro() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getActiveSheet().insertColumnsAfter(spreadsheet.getActiveRange().getLastColumn(), 2);
  spreadsheet.getActiveRange().offset(0, spreadsheet.getActiveRange().getNumColumns(), spreadsheet.getActiveRange().getNumRows(), 2).activate();
  var sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn() - 2, sheet.getMaxRows(), 2).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn(), sheet.getMaxRows(), 2).activate();
  sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn() - 2, sheet.getMaxRows(), 2).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_COLUMN_WIDTHS, false);
};
function UntitledMacro1() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn(), sheet.getMaxRows(), 2).activate();
  spreadsheet.getActiveSheet().insertColumnsAfter(spreadsheet.getActiveRange().getLastColumn(), 2);
  spreadsheet.getActiveRange().offset(0, spreadsheet.getActiveRange().getNumColumns(), spreadsheet.getActiveRange().getNumRows(), 2).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet15'), true);
  spreadsheet.getCurrentCell().offset(-2, 0, 17, 2).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Training Dash'), true);
  spreadsheet.getCurrentCell().activate();
  spreadsheet.getRange('Sheet15!A1:B17').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn(), sheet.getMaxRows(), 2).activate();
  sheet = spreadsheet.getActiveSheet();
  sheet.getRange(1, spreadsheet.getCurrentCell().getColumn() - 2, sheet.getMaxRows(), 2).copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_COLUMN_WIDTHS, false);
};
function UntitledMacro2() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getRange('E:N').activate();
  spreadsheet.getActiveSheet().insertColumnsBefore(spreadsheet.getActiveRange().getColumn(), 10);
  spreadsheet.getActiveRange().offset(0, 0, spreadsheet.getActiveRange().getNumRows(), 10).activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet15'), true);
  spreadsheet.getRange('A1:B17').activate();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Training Dash'), true);
  spreadsheet.getRange('E1:N1').activate();
  var currentCell = spreadsheet.getCurrentCell();
  spreadsheet.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate();
  currentCell.activateAsCurrentCell();
  spreadsheet.getRange('Sheet15!A1:B17').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
  spreadsheet.getRange('E:N').activate();
  spreadsheet.getRange('O1:P16').copyTo(spreadsheet.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_COLUMN_WIDTHS, false);
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Sheet15'), true);
  spreadsheet.getActiveSheet().hideSheet();
};

A:
The problem lies in this line of code in OnEdit(e)
`if( selectedCell.getColumn() >= COLUMNTOCHECK) { `

This seeks to determine only if the column number of the selected cell is greater than or equal to 3. Whether the column contains a checkbox or a date is not considered. So when a date is deleted, OnEdit kicks in, evaluates that the column is greater than 3, and so puts a datestamp in the cell adjacent to the selected cell.
The solution is to check whether the column of the selected cell is an odd or even number. Column numbers containing checkboxes are odd, column numbers containing datestamps are even. So, if the column number is odd, then OnEdit should proceed as usual, but if the column number is even, then OnEdit should do nothing.
The test for odd/even is done using modulus. Refer this extensive discussion.

Replace the problem code with this line:
` if (selectedCell.getColumn() >= COLUMNTOCHECK && selectedCell.getColumn() % 2 == 1) {`

The differences are:
&&  - meaning "AND" - the code is now evaluating two outcomes
selectedCell.getColumn() % 2 == 1 - an outcome of 1 (one) identifies an odd number.


text:
Q: update role app users in Azure AD using Microsoft Graph API I have different roles of an app called power.
enter image description here
Each user has a role assigned and I want to be able to change a role to a user with graph api using graph explorer and connect it to power apps.
enter image description here
enter image description here
With this request i have the id role of all users but I don't know how to update them
GET https://graph.microsoft.com/v1.0/{id}/users?$expand=appRoleAssignments
If there is another api or connector with which I can do it and connect it with powerapps, it also works for me.

A: Yes, you should be sending a request as below (from Grant an appRoleAssignment for a service principal)
Endpoint
https://graph.microsoft.com/v1.0/servicePrincipals/{appObjectId}/appRoleAssignedTo
{appObjectId} should be the Enterprise Application (service principal) object ID
Method
POST
Request headers
Content-type: application/json

Request Body
{
    "principalId": "",
    "resourceId": "",
    "appRoleId": ""
}

principalId = The user/group object ID
resourceId = The Enterprise Application object ID, which is the same ID used in the endpoint {appObjectId}
appRoleId = The app role ID, which can be found in the App Registration manifest


text:
Q: How to change text dynamically in a qlabel to get next value of the database by a pushbutton? I want to change the text in my label by the next value in the database from a pushbutton. I tried the following code, it didn't work-
void category::on_pushButton_clicked()
{
QString d;
QSqlQuery qry;
QVariant b=0,s=0;
b = qry.exec("select count id from category");
if(b>=s)
{
    s++;
    qry.prepare("select heading from category");
    qry.exec();
    d=qry.value(0).toString();
    ui->label_2->setText(d);

}}

It shows the error:-"invalid operands to binary expression('QVariant' and 'QVariant')" in the if statement-
error picture(for more understanding)
I changed QVariant to int, and it didn't show any error but when i run it doesn't change the text on clicking pushbutton

A: Firstly, you should check it in this way: "if (qry.exec())". Secondly, you can see what's wrong with this "QString log = qry.lastError().text();"