text:
Q: jquery ajax return function not working I am trying to do a simple ajax request with jquery, and do something based on the return value. The problem is, the ajax request works fine, but the function checking the return data doesn't seem to work on the if "data.result == 1"
It returns fine and the ajax request succeeds (database entry is removed properly), the problem is the checking of the result.
The PHP inside the ajax request:
if($_POST && isset($_SESSION['user_id']) && $_SESSION['user_id'] != 0)
{
  if ($user->delete_user_notification($_POST['note_id']))
  {
    echo json_encode(array("result" => 1));
    return true;
  }
}

The jquery js:
  $('.delete_notification').click(function()
  {
    event.preventDefault();
    var note_id = $(this).data('note-id');

    $.post('/includes/ajax/delete-notification.php', {'note_id':note_id},
    function(data)
    {
      if (data.result == 1)
      {
        alert(note_id);
        $('#note-' + note_id).remove();
      }
    });
  });

I've checked what "data" returns and it is correct:
{"result":1}


text:
Q: Is it possible to have on service check multiple hosts on nagios I have a few hosts that check for the temperature through snmp, and I was wondering if I could combine the 4 different services into one service that checks all 4 hosts temperatures. I know that they have different OID's, but I was hoping there was a way to do that.
Thanks!

A: You can have a check do anything you can program. The only thing you need to do is craft the output of your check such that Nagios can parse it. In this specific case, I might implement this as a passive check.

A: If you're using the stock check_snmp plugin, you can check all 4 temperatures at once. See the first note in the --help output:

*

*Multiple OIDs (and labels) may be indicated by a comma or space-delimited
  list (lists with internal spaces must be quoted). Maximum: 8 OIDs.

If you're using some other plugin, like a custom variant of check_snmp, this is a perfect use case for check_multi.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I share a link and photo with Instagram using PHP How do I share a link and photo with Instagram using PHP? I can't find anything for "share photo with instagram".

A: By "share photo with instagram", do you mean that you are trying to post a picture to Instagram via PHP? You cannot post pictures to Instagram via the API.


text:
Q: Where to download param partition image for Meizu Pro5? I have a damaged "param" partition on my Meizu Pro 5 ubuntu edition.
I am now in recovery mode. a TWRP 3.0 adb enabled.
My param partition (a small 4M) (/dev/sda21) got wiped.
Can someone tell me:
What is that partition for?
Can I reboot without bricking the phone?
Where can I get a pristine image for this partition?
If someone else has a meizu pro5, can you provide it?
This partition image is not in the device-*.tar.gz from ubuntu system images.

A: The partition is mostly empty. I have scavenged this info from another meziu pro5 phone.
Hope it will help another poor soul that will mess up the internal flash.
To recreate the partition information run this:
(head -c 320 /dev/zero
echo -e -n "\xCCUactivateStats\x00\xC0\x01\xC5\x04"
head -c 43 /dev/zero
echo -e -n "\xE3"
head -c 4193920 /dev/zero) > test.img

The md5sum of the partition should be: e69ac803431a05cf0b59d23129221861


text:
Q: Did Dumbledore mend Hagrid's wand with the Elder Wand? We all know that Hagrid got expelled because he got framed of the murder of Moaning Myrtle, real name Myrtle Warren, and that got his wand snapped in half.
But we also that Dumbledore was the master of the Elder Wand sometime after that since his expulsion was in 1943, and Dumbledore defeated Grindelwald in 1945.
So did Dumbledore fix Hagrid's wand when he became Headmaster?

A: It looks like Hagrid's wand was not fixed. Hagrid's spells normally did not work out well.

Hagrid looked down at his umbrella and stroked his beard.
"Shouldn'ta lost me temper," he said ruefully, "but it didn't work anyway. Meant ter turn him into a pig, but I suppose he was so much like a pig anyway there wasn't much left ter do."
Harry Potter and the Sorcerer's Stone, Chapter 4, The Keeper of the Keys

Broken wand can be used for casting spells, but there is no guarantee that it will work. In fact, Hagrid does mention that he still has pieces of his wand and the fact that he uses his umbrella for performing spell is an indication that the broken pieces of the wand is inside his umbrella.

"Good wand, that one. But I suppose they snapped it in half when you got expelled?" said Mr. Ollivander, suddenly stern.
"Er — yes, they did, yes," said Hagrid, shuffling his feet. "I've still got the pieces, though," he added brightly.
"But you don't use them?" said Mr. Ollivander sharply.
"Oh, no, sir," said Hagrid quickly. Harry noticed he gripped his pink umbrella very tightly as he spoke.
Harry Potter and the Sorcerer's Stone, Chapter 5, Diagon Alley

We see Ron using his broken wand through out Chamber of Secrets with limited success.

"Ron was having far worse problems. He had patched up his wand with some borrowed Spellotape, but it seemed to be damaged beyond repair. It kept crackling and sparking at odd moments, and every time Ron tried to transfigure his beetle it engulfed him in thick gray smoke that smelled of rotten eggs. Unable to see what he was doing, Ron accidentally squashed his beetle with his elbow and had to ask for a new one. Professor McGonagall wasn't pleased."
Harry Potter and The Chamber of Secrets, Chapter 6, Gilderoy Lockhart


text:
Q: Delphi - prevent against SQL injection I need to protect an application from SQL injection. Application is connecting to Oracle, using ADO, and search for the username and password to make the authentication.
From what I've read until now, the best approach is by using parameters, not assigning the entire SQL as string. Something like this:
query.SQL.Text := 'select * from table_name where name=:Name and id=:ID';
query.Prepare;
query.ParamByName( 'Name' ).AsString := name;
query.ParamByName( 'ID' ).AsInteger := id;
query.Open;

Also, I'm thinking to verify the input from user, and to delete SQL keywords like delete,insert,select,etc...Any input character different than normal ASCII letters and numbers will be deleted.
This will assure me a minimum of security level?
I do not want to use any other components than Delphi 7 standard and Jedi.

A:
This will assure me a minimum of security level?

Yes parametrized queries should protect you from SQL injection which would be easy to test. Simply input some dangerous string in the name variable and see what happens. Normally you should get 0 rows returned and not an error.

A: Safe
query.SQL.Text := 'select * from table_name where name=:Name';

This code is safe because you are using parameters.
Parameters are always safe from SQL-injection.
Unsafe
var Username: string;
...
query.SQL.Text := 'select * from table_name where name='+ UserName;

Is unsafe because Username could be name; Drop table_name;
Resulting in the following query being executed.
select * from table_name where name=name; Drop table_name;

Also Unsafe
var Username: string;
...
query.SQL.Text := 'select * from table_name where name='''+ UserName+'''';

Because it if username is ' or (1=1); Drop Table_name; --
It will result in the following query:
select * from table_name where name='' or (1=1); Drop Table_name; -- '

But this code is safe
var id: integer;
...
query.SQL.Text := 'select * from table_name where id='+IntToStr(id);

Because IntToStr() will only accept integers so no SQL code can be injected into the query string this way, only numbers (which is exactly what you want and thus allowed)
But I want to do stuff that can't be done with parameters
Parameters can only be used for values. They cannot replace field names or table names.
So if you want to execute this query
query:= 'SELECT * FROM :dynamic_table '; {doesn't work}
query:= 'SELECT * FROM '+tableName;      {works, but is unsafe}

The first query fails because you cannot use parameters for table or field names.
The second query is unsafe but is the only way this this can be done.
How to you stay safe?
You have to check the string tablename against a list of approved names.
Const
  ApprovedTables: array[0..1] of string = ('table1','table2');

procedure DoQuery(tablename: string);
var
  i: integer;
  Approved: boolean;
  query: string;
begin
  Approved:= false;
  for i:= lo(ApprovedTables) to hi(ApprovedTables) do begin
    Approved:= Approved or (lowercase(tablename) = ApprovedTables[i]);
  end; {for i}
  if not Approved then exit;
  query:= 'SELECT * FROM '+tablename;
  ...

That's the only way to do this, that I know of.
BTW Your original code has an error:
query.SQL.Text := 'select * from table_name where name=:Name where id=:ID';

Should be
query.SQL.Text := 'select * from table_name where name=:Name and id=:ID';

You cannot have two where's in one (sub)query

A: If you allow the user to influence only the value of parameters that will be bound into an sql command text with placeholders, then you don't really need to inspect what the user enters: the simplest way to avoid SQL injection, as you mention, is to avoid concatenated SQL, and using bound variables (or calling procedures) does this (it also has the advantage - mileage/relevance depends on the database -  of allowing the engine to re-use query plans).
If you are using Oracle, then you need to have a really good reason for not using bound variables: Tom Kyte has a ton of good information about this on his site http://asktom.oracle.com. Just enter "bound variables" in the search box.


text:
Q: How would I create this array of object using pointer Basically I want to create an array of objects with a size which is passed through from one class to another i.e.
Object * ArrayOfObjects = new Object[Size];

Whilst that creates an array successfully, it doesnt allow me to use constructors.
How can I create an array of my objects then define each object in the array?

A: Once you allocate memory for the array you can then assign to it by looping:
for (int i = 0; i < Size; ++i)
{
    ArrayOfObjects[i] = Object( /* call the constructor */ );
}

Or you can use a vector to do the same but with more ease of use:
std::vector<Object> ArrayOfObjects = { Object(...), Object(...) };

A: What you're asking may not actually be the best thing to do - which would be to use something like std::vector or something, but under the hood what they're going to do is what your question asks about anyway.
Then you can either assign or placement new each entry:
for (size_t i = 0; i < Size; ++i)
{
     // Option 1: create a temporary Object and copy it.
     ArrayOfObjects[i] = Object(arg1, arg2, arg3);
     // Option 2: use "placement new" to call the instructor on the memory.
     new (ArrayOfObjects[i]) Object(arg1, arg2, arg3);
}

A: Once you allot memory, as you did. You initialize each object by traversing the array of objects
and call its constructor.
#include<iostream>
using namespace std;
class Obj
{
    public:
    Obj(){}
    Obj(int i) : val(i)
    {
        cout<<"Initialized"<<endl;
    }
    int val;
};
int allot(int size)
{

    Obj *x= new Obj[size];
    for(int i=0;i<10;i++)
        x[i]=Obj(i);

     //process as you need
     ...
}


text:
Q: Suspended mode is not working correctly on Ubuntu 12.04 LTS After I did get my PC into the suspended mode, I can't get the PC on again. In Windows 7 there's no problem at all.
Does it take a very long time to get PC to turn on again from suspended mode in Ubuntu? Because of this problem I did restart the PC at every suspended mode was activated.
Please give me some help on this

A: You can refer this ubuntuforum thread:
Ubuntu 12.04 LTS Suspend not working FIX by DragonNinja9


text:
Q: How to run commands under su using java processbuilder? I have adjusted my /etc/pam.d/su file such that I can switch user from a  particular user vs to root without password.
When I run su - -c "ls -l /tmp" using the terminal it produces the output and it does not require any password. But when I try to do it using java ProcessBuilder it doesn't work. Following is my code:
import java.io.File;
import java.util.concurrent.TimeUnit;

class a {
    public static void main(String args[]) {
        try {
            String cmd[] = {"su", "-", "-c", "\"ls -l /tmp\""};
            ProcessBuilder pb = new ProcessBuilder(cmd).redirectOutput(new File("a"));
            Process process   = pb.start();
            if(!process.waitFor(5, TimeUnit.SECONDS)){
                process.destroy();
                process.waitFor();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I have checked my output file a (as in above code), it is blank. But when String cmd[] = {"ls", "-l", "/tmp"}; my output file a is not blank, it produces proper output. I want to use su to run other programs but I am just test it using ls.
Is there a way to run the above java code properly?


text:
Q: MongoDB joining collection to itself with lookup and pipeline, based on date: no results in joined result set I'm trying to join a collection to itself so in one query I can receive the document and the document(s) immediately preceding it. I'm attempting to do this using aggregate and `$lookup'.
Here is some example data:
[
  {
    "_id": {
      "$oid": "61e40955cb65f4a8edec3461"
    },
    "ImageName": "2022-01-16-120228.png",
    "Start": {
      "$date": "2022-01-16T12:02:29.437Z"
    }
  },
  {
    "_id": {
      "$oid": "61e40957cb65f4a8edec3463"
    },
    "ImageName": "2022-01-16-120230.png",
    "Start": {
      "$date": "2022-01-16T12:02:31.443Z"
    }
  },
  {
    "_id": {
      "$oid": "61e4095acb65f4a8edec3469"
    },
    "ImageName": "2022-01-16-120233.png",
    "Start": {
      "$date": "2022-01-16T12:02:33.189Z"
    }
  },
  {
    "_id": {
      "$oid": "61e4095ccb65f4a8edec346b"
    },
    "ImageName": "2022-01-16-120235.png",
    "Start": {
      "$date": "2022-01-16T12:02:35.288Z"
    }
  }]

With each document in this collection I want to bring back the document immediately preceding it when ordered by the Start date, like this:
db.Captures.aggregate([{
  $lookup: {
    from: 'Captures',
    as: 'precedingCaptures',
    let: {
      'start': '$Start'
    },
    pipeline: [
      {
        $sort: {
          'Start': -1
        }
      },
      { $match: {
        'Start': {$lt: '$$start'}
      }},
      { '$limit': 1 }
    ]
  }
}])

However in my resulting document precedingCaptures is empty. What am I doing wrong?

A: You cannot use the "simple" form of $match with pipeline $lookup.  You must use the $expr form as noted here: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/
This will work:
db.foo.aggregate([
    {$lookup: {
        from: 'foo',
        as: 'precedingCaptures',
        let: { 'start': '$Start'},
        pipeline: [
            { $match: {$expr: {$lt:['$Start','$$start']} }},  // $expr form
            { $sort: {'Start': -1}},
            { $limit: 1 }
        ]
    }}
]);


text:
Q: Responsive footer html I made a footer with html, css and bootstrap and it's responsive to some kind of exctent but when it gets to mobile size instead of the images being in a row they stack up and gets in a column, how can i fix this? I want i to be the same when it comes down to mobile size as it is when it is in desktop size. I hope you understand, sorry for my bad english. Here is the html:

  /*Facebook*/

.fb-icon img {
  width: 60px;
  height: 60px;
  display: block;
  margin: auto;
}

/*Twitter*/

.twitter-icon img {
  width: 60px;
  height: 60px;
  display: block;
  margin: auto;
}

/*Mail*/

.mail-icon img {
  width: 60px;
  height: 60px;
  display: block;
  margin: auto;
}

.container {
  margin-top: 120px;
  width: 30%;
}

@media (max-width: 767px) {
  /*Facebook*/
  .fb-icon img {
    width: 70px;
    height: 70px;
    display: block;
    margin: auto;
    padding: 5px;
  }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet" />

A: By default, if you check your bootstrap you will see that bootstrap is using col-sm-4 on mobile devices and has a max-width: 100% css property. Just add this css snipped into your media query
@media (max-width: 767px) {
  /*Facebook*/

  .col-sm-4 {
    max-width:33.3%;
    display:inline-block;
  }
....
}


text:
Q: Object Following X Coords of Mouse Position Tkinter I am trying to make pong, I want my paddle to follow the x position of the mouse. I just had the x position of the mouse assigned to a variable and it would add to itself every time I moved the mouse then just go off the screen. I now changed it a little bit but I just cannot get it to work
ERRORS:
    Traceback (most recent call last):
    File "Tkinter.py", line 1536, in __call__
    return self.func(*args)
    File "animationTest.py", line 51, in motion
    self.diff = self.x - canvas.coords(self.paddle)
    TypeError: unsupported operand type(s) for -: 'int' and 'list'

CODE:
from Tkinter import *
import time

HEIGHT = 500
WIDTH = 800
COLOR = 'blue'
SIZE = 50

root = Tk()

canvas = Canvas(root, width=WIDTH, height=HEIGHT, bg=COLOR)
canvas.pack()

class Ball:

   def __init__(self, canvas):
      self.ball = canvas.create_oval(0, 0, SIZE, SIZE, fill='black')
      self.speedx = 6
      self.speedy = 6
      self.active = True
      self.move_active()

   def ball_update(self):
      canvas.move(self.ball, self.speedx, self.speedy)
      pos = canvas.coords(self.ball)
      if pos[2] >= WIDTH or pos[0] <= 0:
            self.speedx *= -1
      if pos[3] >= HEIGHT or pos[1] <= 0:
            self.speedy *= -1

   def move_active(self):
      if self.active:
         self.ball_update()
         root.after(1, self.move_active)

class Paddle:

   def __init__(self, canvas):
      self.paddle = canvas.create_rectangle(0,0,100,10, fill='red')
      canvas.bind('<Motion>', self.motion)
      self.active = True
      self.move_active

   def motion(self, event):
      self.x = event.x
      self.diff = self.x - canvas.coords(self.paddle)
      print('the diff is:' ,self.diff)
      print('the click is at: {}'.format(self.x))

   def move_active(self):
      if self.active:
         self.motion()
         root.after(1, self.move_active)

run = Ball(canvas)
run2 = Paddle(canvas)
root.mainloop()

A: There's no reason to read the current coordinates. You can use the event.x to calculate the new coordinates without knowing what the current coordinates are.
def motion(self, event):
    '''update paddle coordinates using current mouse position'''
    canvas.coords(self.paddle, event.x-50, 0, event.x+50, 10)

This simply overrides the coordinates 0,0,100,10 that you set in the __init__ method with new ones based on the mouse position.


text:
Q: AWS RDS to S3 Error. "The XML WAS NOT WELL FORMED" I am trying to migrate specific data from RDS(MYSQL) to S3 using AMAZON DATA PIPELINE. but i get the error

"The XML you provided was not well-formed or did not validate against
  our published schema (Service: Amazon S3; Status Code: 400; Error
  Code: Malformed XML"

enter image description here
enter image description here

A: It might be caused by using invalid-XML-characters in some part of the S3 objects. See https://github.com/aws/aws-sdk-java/issues/333 .
To dig deeper, please provide more information:

*

*Is this caused by an API call? If so what SDK do you use and what exactly is the call?

*Can you share the pipeline configuration?

A: Instead of building a custom architecture, i used the RDS - S3 full copy template. that seems to eliminate the error. although not yet getting the data in the s3 bucket, but i can access the empty csv file.

A: You need to set LifecycleTransition properties Days and Storage Class.
LifecycleConfiguration newConfiguration = new LifecycleConfiguration
        {
            Rules = new List<LifecycleRule>
            {
                new LifecycleRule
                        {
                             Id = "some id here",
                             Filter = new LifecycleFilter()
                             {
                                 LifecycleFilterPredicate = new LifecyclePrefixPredicate()
                                 {

                                 }
                             },
                             Status = LifecycleRuleStatus.Enabled,
                             Transitions = new List<LifecycleTransition>
                             {
                                  new LifecycleTransition
                                  {
                                       Days = 0,
                                       StorageClass = S3StorageClass.Glacier
                                  }
                              },
                             Expiration = new LifecycleRuleExpiration()
                             {
                                   Days = 1
                             }
                        }
            }
        };


text: Q: Coefficient of expansion of $\,x\,$ What is the simplest way to find the coefficient of, for example, $\,x^{ 6 }$ in $\left(x+1\right)\cdot\left(x+2\right)\cdot \ldots\cdot\left(x+10\right)\,$? My teacher says that the easiest way is listing, but it doesn't help for high powers.


text:
Q: JSp displays foreign currencies as junk I am trying to display foriegn currencies in my jsp using formatnumber tag from apache fmt tag-lib, it displays junk char data. i can confirm that in controller 'the dynamic currency symbol value' being displayed correctly when I print out on console and I explicitly set response object encoding to UTF-8 and jsp page encoding and charset to UTF-8 as well. Setting the locale wont help as the transaction are in foriegn currencies and any transaction can be viewed on any part of the world.
Seems like there is a bug with formatnumber tag , but not sure about any alternatives for that.
mail-archives.apache.org/mod_mbox/tomcat-taglibs-user/200308.mbox/%3C000001c36bc5$4ee81db0$0100a8c0@pentium3%3E
I checked this EURO and yen .
I pasted the part of code of my jsp http://pastebin.com/eZAKKeJ9. I tried printing out browser to make sure what's being pass to tag, so its junk line 545 tells and line 564 tell the formatnumber being passed with currency.
  and handler http://pastebin.com/H21fdbZm . Checked the browser to make sure it had default changed to UTF-8. Any help is appreciated.
edit: spam  doesnt allow me to post more than 2 links.

A: From your code:
currencySymbol="${txnFormBean.originalCurrencySymbol}"

This problem can occur when the bean property actually returned a non-UTF-8 character. You need to fix it in the source where this character originated. Is it a Java file? Ensure that file is saved as UTF-8. Is it a properties file? Ensure that you use an unicode escape sequence. Is it a database entry? Ensure that the table uses UTF-8. Etc.


text:
Q: Is there an R command to show all functions defined in the environment? Is there an R command that shows all functions defined in the environment?
For example, ls() shows all objects in the environment, but I need one that shows only the functions. I need to take all functions defined in the environment and since these are many, listing them is not suitable. Also because, every time I add a new function, I have to modify the list.


text:
Q: difference between various way of defining an object in javascript In javascript we can define an object prototype in various way.
First one
var foo={
a:1,
b:2
}

Second is
var foo=function(){
this.a=1;
this.b=2;
}

what i know is that the first on is an object itself while for creating an object from second definition we have to use new foo(). is there any other differences between these two definition. and if both are same then what is a need of second if not then what is need of first?

A: They are not the same, the second is a constructor for the Object:

var foo = {
  a: 1,
  b: 2
}
console.log("First: ",
    typeof foo, // object
    JSON.stringify(foo), // {a:1,b:2}
    foo.constructor) // function Object() { [native code] }

var foo = function() {
  this.a = 1;
  this.b = 2;
}
console.log("Second: ",
    typeof foo, // function
    JSON.stringify(foo), // undefined, foo is not an Object, it's a function!
    foo.constructor) // function Object() { [native code] }

var foo = new foo()
console.log("Thrid: ",
    typeof foo, // object
    JSON.stringify(foo), // {a:1,b:2}
    foo.constructor) // function() {  this.a = 1;  this.b = 2;}

So even after creating both object you will have a diffrence in their .constructor attribute. As the first Object was created by the Native constructor vor Object in JavaScript, and the second was created by your custom constructor.
But thats the only diffrence


text:
Q: How do I search trough query results, to prevent making to many requests I have the below set of queries, but I'm sure this isn't DRY. However, I can't find out how to filter trough the deals var instead of querying again for each var. Is it possible?
deals = Deal.all
won = Deal.find( :all, :conditions => ["status = 'won'"] ).count
pending = Deal.find( :all, :conditions => ["status = 'pending'"] ).count
lost = Deal.find( :all, :conditions => ["status = 'lost'"] ).count

A: Use GROUP BY SQL clause:
Hash[Deal.all(:select => 'status, count(*) as count', :group => 'status').map{|e|
  [e.status, e.count]
}]

Edit: I forgot that you already have all the records loaded. In that case, you can get counts per status this way:
Hash[deals.group_by(&:status).map{|k,v| [k,v.count]}]

A: You can use following:-
Deal.find(:all, :select => 'status, count(id) as deal_count', :group => 'status')

A: You can use Array#select:
deals = Deal.all
won   = deals.select { |deal| deal.status == 'won' }.length
# similar for pending and lost

A: I think you can use Ruby's inject function for this:
won = deals.inject(0) {|total, deal| deal.status == 'won' ? total + 1 : total }

A: if your Deal objects are ActiveRecord objects (which is typically the case for models), you can launch the count on the data base:
won = Deal.count_by_sql("select count(*) from deals where status = 'won'")
Another way to do it would be to write the sql query that would do the all the count for you, and group them by status:
count_by_status = Deal.find_by_sql("select status,count(*) from deals group by status;")
Then you can use the result (which will be an array of hashes I think).


text:
Q: Core 7 - Api error handling, model state validation + UseExceptionhandler I am currently working on implementing some Apis using swagger/swashbuckle in net core 7 and implementing some error handling, I've gone down the route of using an exception handler. With separate endpoints from dev/prod.
E.g. Startup.cs
            if (env.IsDevelopment())
            {
                ...details ommited
                app.UseExceptionHandler("/dev-error");
            }
            else
            {
                ...details ommited
                app.UseExceptionHandler("/error");
            }

ErrorController.cs
[AllowAnonymous]
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorController : Controller
{
    private ILogger _logger;

    public ErrorController(ILogger logger)
    {
        _logger = logger;
    }

    [Route("dev-error")]
    public IAttempt DevError()
    {
        var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
        var exception = context.Error;

        return Attempt.Fail(exception);
    }

    [Route("error")]
    public IAttempt Error()
    {
        var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
        var exception = context.Error;

        _logger.Log(LogLevel.Error, exception, exception.Message);

        switch (exception)
        {
            case UnauthorizedAccessException:
                Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                return Attempt.Fail("Unauthorised");

            default:
                Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                return Attempt.Fail("Generic Error");
        }
    }
}

The idea is that all responses are of IAttempt, so that the FE user can check if its succeeded etc. and whether to handle the result or exception in a user friendly way.
This has been working great up until now when I've been implementing Api's that require the model to be validated. I wanted to amend the IAttempt class to provide modelstate feedback, however I have tried many approaches and cant seem to get modelstate validation flow through the exception handler.
I wanted to implement a custom ValidationException that contains the errors which is then handled in these controllers. But when an exception is thrown in either an IActionFilter or when overriding the InvalidModelStateResponseFactory the exception isn't caught by the exception handler.
Is there a work around? Am I missing something?
Alternatively I could define a InvalidModelStateResponseFactory that returns a similar model(IAttempt), but it would be nice for Failed requests to be handled in one place.
Cheers in advance

A: I think you can make the InvalidModelStateResponseFactory redirect to the ErrorController, sending the required data to create your response

A: According to your description, I suggest you could consider using the customer action filter to achieve your requirement.
Inside the custom action filter, we could get the model state's results, then you could throw  the exception inside it.
More details, you could refer to below codes:
1.Create the custom action filter:
public class CustomValidationActionFilter : IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext context)
    {
        if (!context.ModelState.IsValid)
        {
            var errorList = context.ModelState.Values
                .SelectMany(m => m.Errors)
                .Select(m => m.ErrorMessage)
                .ToList();

            throw new Exception();
        }

     }

    public void OnActionExecuting(ActionExecutingContext context) { }
}

2.Inside the program.cs
builder.Services.AddControllersWithViews(options =>
{
    options.Filters.Add(new CustomValidationActionFilter());
});

Then if it thrown the exception, it will go to the controller's error action method, since you set the global exception handler.

A: I was unnecessarily over complicating things so I have dropped what I attempted to do as in theory responses should be handled accordingly to their response status code rather then the object thats passed in.


text:
Q: Looking for assistance with Graphic Card Dtriver. Help I am using a Galaxy Nvidia GeForce GT610 Graphics Card on my console while running the Ubuntu 14.04LTS OS. I am confused. I need to figure out which of the drivers would be the best that apear to use in the list of Drivers available....?? Someone. Please help me.

A: One of them will say "Recommended" to the right, and when you highlight it the description area will say "tested" and have a little red ribbon next to it.  Those are generally the ones I pick.


text:
Q: Selenium(Python) - How to get text after image tag

       givemetext

How do I get the text givemetext with python selenium?

A: In presented here XML "givemetext" text belongs to
.
So, in order to retrieve this text you have to get that web element and extract it's text.
Something like:
text_value = driver.find_element(By.XPATH,"//li[@class='user']").text

Still need to validate the selected locator is unique, no problem with wait / delay, the element is not inside iframe etc.

A: The text givemetext is a text node within it's ancestor
.
To print the text givemetext just after the <image> you can use either of the following Locator Strategies:

*

*Using css_selector:
print(driver.find_element(By.CSS_SELECTOR, "ul.meta li.user").text)

*Using xpath:
print(driver.find_element(By.XPATH, "//ul[@class='meta']//li[@class='user'][./img[@class='classname' and @src='some url']]").text)

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "ul.meta li.user"))).text)

*Using XPATH:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//ul[@class='meta']//li[@class='user'][./img[@class='classname' and @src='some url']]"))).text)

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python


text:
Q: How can I retrieve the P4 ROOT variable value in a Windows Batch file? I want to retrieve the p4 CLIENT ROOT variable that appears in p4 info but not sure how. I am new to batch scripts myself. I've taken a look at http://answers.perforce.com/articles/KB_Article/Accessing-Perforce-Environment-Variables-From-a-Windows-Batch-File but I changed CLIENT to ROOT but it doesn't seem to work.
EDIT:
I've found a way to make the commands in that tutorial to work but that defeats the purpose of what I am trying to achieve because I have to manually set P4ROOT in the command line. Instead I am assuming I don't know the root folder so I want to find it from p4 info somehow.

A: As Bryan noted, the client root and the server root are two different things, and it's good to be clear on which one it is you're trying to get (it sounds like you want to get the client root for the current client; this is set in the client spec and not in any environment variable on either the client or server side).  You can get them both from the output of "p4 info", though, and you can use the -F global option to p4 to isolate either field with minimal fuss:
Client root:
p4 -Ztag -F %clientRoot% info

Server root:
p4 -Ztag -F %serverRoot% info

See http://www.perforce.com/blog/130826/fun-formatting for more on the -F option.

A: You can parse the output of p4 set P4CLIENT to get the client name, then parse the output of p4 client clientname to get the root.  Ugly, but functional:
@for /f "tokens=2 delims== " %c in ('p4 set P4CLIENT') do @(for /f "tokens=2" %r in ('p4 client -o %c ^| findstr /c:"Root:" ^| findstr /v #') do echo %r)

If you're using this in a batch file, double each of the percent signs.
EDIT - Alternately, and much easier, now that I look at it:
for /f "tokens=3" %r in ('p4 info ^| findstr /c:"Client root:"') do echo %r

Again, double the percents if you're using this in a batch file.


text:
Q: Theme not rendering Thanks your time. I tried searching  errors  typing in wp-config.php to review the Mime Apache settings in my I EC2 AWS instance where is my WordPress
I also installed a new, clean, WordPress, in the same instance but the problem persist in the theme and in the wp login the CSS Html does not load. You can see it in url: bitcommit.ec


text:
Q: Magento 2: How to make custom fee taxable
*

*I want to add a tax on custom fee. tax calculation is perfect and gets tax amount but it's not set in TAX files in quote_address in the database.
public function collect(
    \Magento\Quote\Model\Quote $quote,
    \Magento\Quote\Api\Data\ShippingAssignmentInterface $shippingAssignment,
    \Magento\Quote\Model\Quote\Address\Total $total
){

  $total->setTaxAmount($total->getTaxAmount()+$taxAmount);
  $total->setBaseTaxAmount($total->getBaseTaxAmount()+$taxAmount);
}

*I try to set tax Amount in collect method but it's not set.

*I want to same like this thiscode. it's Magento1 but I want Magento 2

A: You may please use below code to set tax amount in quote address and quote tables:
$quote->setTaxAmount($total->getTaxAmount() + $taxAmount);
$quote->setBaseTaxAmount($total->getBaseTaxAmount() + $taxAmount);

$address = $shippingAssignment->getShipping()->getAddress();
$address->setTaxAmount($total->getTaxAmount() + $taxAmount);
$address->setBaseTaxAmount($total->getBaseTaxAmount() + $taxAmount);

I hope this help to you. If you have any further query feel free to ask.
Happy to help!
Thanks,

A: Instead of a call to $total->setTaxAmount() you need to use addTotalAmount:
$total->addTotalAmount('tax', $amount);
$total->addBaseTotalAmount('tax', $baseAmount);


text:
Q: Connect monitor (DVI / VGA) to S-Video / TV-Out I have an ATI Radeon HD 4850 graphics card in my computer. It has two DVI sockets and an S-Video / TV-OUT socket. There are alreay two monitors connected to the two DVI sockets.
I have a third (currently unused) monitor with DVI and VGA (Sub-D) connection.

*

*Is it possible to use this third monitor with this graphics card?

*If yes: How do I connect the monitor to the graphics card?

*Are there any adapters or cables between S-Video / TV-OUT and DVI or VGA?
I use Linux as OS with the fglrx drivers. While the configuration may become difficult, too, my current problem is the hardware connection.
graphics card specification: http://www.amd.com/us/products/desktop/graphics/ati-radeon-hd-4000/hd-4850/Pages/ati-radeon-hd-4850-specifications.aspx

A: I did not buy an composite to VGA adapter, yet so I am not 100% sure, but seems like it is not possible to use a third monitor with independent resolution and display content with this graphics card.
Read the comments abhove and this is from the specification of the graphics card:

*

*Two independent display controllers

Drive two displays simultaneously with independent resolutions, refresh rates, color controls and video overlays for each display

Thx to Ignacio Vazquez-Abrams

A: Although I have not looked up your card specifically, most standard video cards will only support 2 video outputs.  Even though there is a 3rd connection for s-video, you will not be able to use it concurrently with the 2 DVI outputs.
As for the second part of the question, there are adapters that will convert s-video to VGA, you probably wont want to.  S-video is very old technology and is designed for TV.  Images from s-video will not look very sharp on a modern LCD, nor will the resolution be very high.


text:
Q: JSON to XML Transformation using XSLT 3.0 I am using Java 1.8, Saxon-HE version 9.9.1-4 version and xslt3.0 to tranform the JSON to XML.
Input JSON
{
    "analystId": "Test",
    "jobId": "",
    "profileData": {
        "allAuthorCoverage": false,
        "assetClasses": [
            {
                "code": "Test1"
            }
        ]

    }
}

XSLT3.0
<xsl:stylesheet version="3.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" />
  <xsl:strip-space elements="*"/>
  <xsl:param name="jsonText"/>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template name="init">
    <xsl:apply-templates select="json-to-xml($jsonText)"/>
  </xsl:template>

 <xsl:template match="*[@key]" >
  <xsl:element name="{@key}">
    <xsl:apply-templates/>
  </xsl:element>
</xsl:template>

</xsl:stylesheet>

Output XML Generated
<?xml version="1.0" encoding="UTF-8"?>
<map xmlns="http://www.w3.org/2005/xpath-functions">
   <analystId xmlns="">Test</analystId>
   <jobId xmlns=""/>
   <profileData xmlns="">
      <allAuthorCoverage>false</allAuthorCoverage>
      <assetClasses>
         <map xmlns="http://www.w3.org/2005/xpath-functions">
            Test1
         </map>
      </assetClasses>
   </profileData>
</map>

Output XML Expected
<?xml version="1.0" encoding="UTF-8"?>
<analystId>Test</analystId>
<jobId />
<profileData>
    <allAuthorCoverage>false</allAuthorCoverage>
    <assetClasses>
        Test1
    </assetClasses>
</profileData>

We can still see <map> element and xmlns attribute in the generated output and my requirement is to remove the same.
Please help me to remove the Map element from the generated output and xmlns attribute as well.
Also in case I expand my json structure with new attributes these map element and xmlns attribute should not be added back again.

A: If you don't use the identity template you have used and instead omit it only your template to transform elements with a key attribute into elements of the name of the key value and any text nodes will create output:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="3.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all">

    <xsl:param name="jsonText" as="xs:string"><![CDATA[{
    "analystId": "Test",
    "jobId": "",
    "profileData": {
        "allAuthorCoverage": false,
        "assetClasses": [
            {
                "code": "Test1"
            }
        ]

    }
}]]></xsl:param>

    <xsl:output indent="yes" />
    <xsl:strip-space elements="*"/>

    <xsl:template name="xsl:initial-template">
        <xsl:apply-templates select="json-to-xml($jsonText)"/>
    </xsl:template>

    <xsl:template match="*[@key]" >
        <xsl:element name="{@key}">
            <xsl:apply-templates/>
        </xsl:element>
    </xsl:template>

</xsl:stylesheet>


text:
Q: How do I display a message to user at the end of a function's return output? I am creating a function that imports a .txt file and returns a data.frame. At times I want to display a message to the user to go along with the data. My problem is that by including the message in the body of the function, it is displayed before the data, and in a large data.frame with many rows, the user likely will never see it.
For example, given:
foo=function(cars){
  message('Pay attention to me!')
  return(cars)
}

If the user enters:
foo(cars)

The function will display my message, but only before the returned object (in this case the data cars from R's base package. How can I display my message() contents at the bottom of the returned data.frame?
I have tried returning the message too, but to no avail:
foo=function(cars){
  return(cars,message('help!'))
}

I notice that the warning() and stop() functions both display their text at the end of the data.frame, but I am wanting to display a message that is neither a warning nor an error, but just an FYI.
To clarify, ideally, the message would be displayed when the function is called (regardless of if the output is assigned to a variable name or not) but it would not be displayed every time the resulting object is used. foo(cars) should display the message, as should obj=foo(cars). But just obj should not.

A: Since Andrie's answer to a similar question of mine did not quite apply to data frames (it returned an empty frame), I've made a minor adjustment to print.bar() in that answer that seems to work well with data frames (so far at least).
foo <- function(x) {
    ## put all your function code here - 'x' will be the return value
    class(x) <- c("bar", class(x))
    x
}

print.bar <- function(x, message = TRUE, ...) {
    ## the only difference is the absence of this line
    NextMethod(x)
    if(message) message("I am a message, hear me ROAR!!")
}

tail(foo(mtcars))
#                 mpg cyl  disp  hp drat    wt qsec vs am gear carb
# Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.7  0  1    5    2
# Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.9  1  1    5    2
# Ford Pantera L 15.8   8 351.0 264 4.22 3.170 14.5  0  1    5    4
# Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.5  0  1    5    6
# Maserati Bora  15.0   8 301.0 335 3.54 3.570 14.6  0  1    5    8
# Volvo 142E     21.4   4 121.0 109 4.11 2.780 18.6  1  1    4    2
# I am a message, hear me ROAR!!

As of this edit, I am having difficulty implementing the request in the comments below (no message printing under the object after assignment has been made and then object called).  One possible workaround for this is to use suppressMessages() when assigning
obj <- suppressMessages(foo(mtcars))

So when calling in the console, foo() will print the message.  When assigning obj, the message will not print when subsequently printing obj

A: This isn't a direct answer, but I think that if it's that important for the user to see the message perhaps a warning is appropriate after all. Alternatively, you can pause the display to give the user a chance to read the message, either for a fixed amount of time:
foo=function(cars){
  message("pay attention to me!")
  Sys.sleep(2)
  return(cars)
}

or until the user confirms:
foo=function(cars){
  x <- readline("pay attention to me!\n(press enter to continue)")
  return(cars)
}


text: Q: Online/Offline status in aws chime sdk A user's online/offline presence can be determined in AWS Chime webapp,but there is no User Presence indicator feature in aws chime SDK.Why?And how to implement it in AWS Chime SDK.


text:
Q: Where does gitignore effect? git add, git commit or git push I added a .gitignore file after git add .. I'd like to know if I can proceed to git commit and push it and git will ignore the files.
If not how should I delete the files which I git added.
Where does .gitignore affect? git add, git commit or git push?

A: If your gitignore is for file you already added, you need also to:

*

*git rm --cached thosefiles(remove them from the index, not from the disk)

*git add -A (will record those deletions plus your gitignore=

*git commit and push

A: There are a few ways to go about this. Here's one way.
Firstly let's undo that git add . for the file you don't want git to track. Run this git reset HEAD <file to remove>. Now, add the .gitignore file with git add .gitignore and git commit -m 'your comment'. Now if you do git status you should find that git is not indicating that your file is untracked.
I am assuming your .gitignore file already contains things to ignore
As for "Where does .gitignore affect?"
When you update your .gitignore file it will make it so that git will not see/find files and directories that you're trying to ignore. So if you were to do a git status you would not see those files or directories. If you did a git add . those files and directories would not be added since git does not see them. However, if git is already tracking the file or directory and you then update the .gitignore you will find that it doesn't just ignore those already tracked files. You will have tell git to untrack them.

A: you can
read the article it will clear your thoughts about .gitignone and FYI you can put those file entries into .gitignore those you wants to don't add into consideration on adding and commiting your files.


text:
Q: How do I add a checkmark to my-sites save settings hook I want to add a checkmark to the my-sites.php through a hook and then press save settings and have it do a function that executes a SQL query.
I've added the checkmark but I don't know how to go further now, I've read about hooks in forms and everything but what I put into my-sites.php is already in a form so my guess is I should be able to use the submit action of that form?
//Adds checkmarks to the my-sites.php interface My Websites.
function makeLiableCheckMark($links) {
  ..wp_enqueue's....

  global $user_blog;
  global $wpdb;
  $blog_id = $user_blog->userblog_id;

  $sitemetaRowExists = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM ".$wpdb->base_prefix."sitemeta WHERE site_id=%d AND meta_key=%s",$blog_id,'aansprakelijk_voor_facturatie'));
  if($sitemetaRowExists > 0) {
      echo '<input type="checkbox" name="liable_id" value="disable" checked> blabla.<br>';
    }
    else {
      echo '<input type="checkbox" name="liable_id" value="enable"> blabla';
    }

A: It sounds as though have altered the page to submit your data. Assuming that that code work properly:

*

*my-sites.php loads admin.php
10  require_once( dirname( __FILE__ ) . '/admin.php' );

*Which fires the load-{pagenow} hook
330         /**
331          * Fires before a particular screen is loaded.
332          *
333          * The load-* hook fires in a number of contexts. This hook is for core screens.
334          *
335          * The dynamic portion of the hook name, `$pagenow`, is a global variable
336          * referring to the filename of the current page, such as 'admin.php',
337          * 'post-new.php' etc. A complete hook for the latter would be
338          * 'load-post-new.php'.
339          *
340          * @since 2.1.0
341          */
342         do_action( 'load-' . $pagenow );

That is probably the hook you need, but based on the very generic information you've provided it is hard to write much code.


text:
Q: How to delete specific patterns with sed bash i have a bash script that contains the following :
#!/bin/bash
##############################################################
# LOCAL COLORS                                               #
##############################################################
export nc="\e[0m"
export underline="\e[4m"
export bold="\e[1m"
export green="\e[1;32m"
export red="\e[1;31m"
export yellow="\e[1;33m"
export blue="\e[1;34m"
export cyan="\e[1;36m"

and when i open the log:
$ echo "${red}############${nc}" | tee log

the characters from the variables appears, so i've trying to delete it using sed like this:
sed -i 's|\e[1;31m||g' log

but always i have the following error :

sed: -e expression #1, char 10: unterminated `s' command

i will appreciate your help with this
Thanks

A: In sed you'll likely need to escape the \e and the [:
sed -i 's|\\e\[1;31m||g'

Otherwise they get misinterpreted and will break the pattern.

A: I suggest to use:
sed -i 's|\x1b\[1;31m||g' log


text:
Q: Models of $T$ in cardinallity $\kappa$ are isomorphic Assume that $T$ is a consistent set in a countable language $\mathscr{L}$ with no finite models. There is a cardinal $\kappa$ such that every two models of $T$ with cardinallity of $\kappa$ are isomorphic. Show that for every closed formula (i.e without free variables), $\varphi$, one and only one of the sets $T\cup\{\neg\varphi\}$, $T\cup\{\varphi\}$ is consistent.
I guess I should use the Compactness Theorem, but I can't see how exactly.
Would like to have some help here.

A: Hint: Use the Lowenheim-Skolem Theorem. If a theory over a countable language has an infinite model, then it has a model of cardinality $\kappa$ for every infinite cardinal $\kappa$,

A: OK I think I got it.
Assume that both of the sets, $T\cup\{\neg\varphi\},T\cup\{\varphi\}$ are consistent.
Then since $\mathscr L$, they have models from every cardinallity (from Lowenheim-Skolem). Take them from cardinallity $\kappa$.
Then $m_{1}$ is a model of $T\cup\{\neg\varphi\}$ of cardinallity $\kappa$, and $m_{2}$ is a model of $T\cup\{\varphi\}$ of cardinallity $\kappa$.
Particullary, $m_{1}$ and $m_{2}$ are models of $T$ from cardinallity $\kappa$ therefore they are isomorphic (given) and so they should satisfy the same closed formuals, which a contraction ($\varphi$ is the witness for that...).
Now, ok, so both of the sets can't be consistent. therefore it's only of them, or no one of them. Is it even possible that no of them will be consistent?


text:
Q: Equelheight.js loading issue I am using Equelheight.js to make blocks on my site same height but now when the page load it the blocks is the same height but the writing in my block goes over the blocks. The writing get loaded from the database. The issue is that the content gets loaded after jquery function. I hope this make sense at all.
Jquery
$(document).ready(function () {
    $(".article-block").equalHeight();
});

CSS
.article-block
{
background-color: #fff;
text-align: left;
padding: 21px 21px;
margin: 0 0 15px 0;
position: relative;
}

HTML

        @item.Title

        @item.DateCreated

        @item.Introduction

        Read more

A: Can you post a fiddle?
Anyway, try to add this CSS:
.article-block div{overflow:auto;}

But it will show scrollbar on the div.
Or, you could call the jQuery .equalHeight(); after the content loaded. Call $(".article-block").equalHeight(); last. Like this;

        @item.Title

        @item.DateCreated

        @item.Introduction

        Read more

Let me know if it works.

A: I found solution I just added a delay for jquery function to kick off:
setTimeout(function(){
    $(".article-block").equalHeight();
}, 500);


text:
Q: problem in testing spring boot when().thenReturn part I am trying to test my code in spring boot but I catch
java.lang.NullPointerException

exception when I run my code.
here are my Models:
package com.Loyalty.OpenLoyalty.Models.User;

import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import javax.swing.text.StyledEditorKit;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;

@Entity

@Table(name = "ol__user")
@DynamicUpdate
@EntityListeners(AuditingEntityListener.class)
public class ol__user {
    public ol__user() {
    }
    public ol__user(String first_name, String last_name, String Email, String username, String password, String dtype, Boolean is_active,ol__roles role,String salt,Timestamp create_at){
        super();
        this.first_name=first_name;
        this.last_name=last_name;
        this.password=password;
        this.email=Email;
        this.is_active=is_active;
        this.username=username;
        this.dtype=dtype;
        this.role=role;
        this.salt=salt;
        this.create_at=create_at;

    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "system-uuid")
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(name = "id", unique = true, nullable = false)
    private String id;

    @Column(name = "username", nullable = true)
    private String username;

    @Column(name = "password", nullable = false)
    private String password;

    @Column(name = "salt", nullable = true)
    private String salt;

    @Column(name = "is_active", nullable = false)
    private Boolean is_active;

    @Column(name = "create_at", nullable = true)
    private Timestamp create_at;

    @Column(name = "email", nullable = false)
    private String email;

    @Column(name = "password_requested_at", nullable = true)
    private Timestamp password_requested_at;

    @Column(name = "confirmation_token", nullable = true)
    private String confirmation_token;

    @Column(name = "deleted_at", nullable = true)
    private Timestamp deleted_at;

    @Column(name = "last_login_at", nullable = true)
    private Timestamp last_login_at;

    @Column(name = "dtype", nullable = false)
    private String dtype;

    @Column(name = "temporary_password_set_at", nullable = true)
    private Timestamp temporary_password_set_at;

    @Column(name = "action_token", nullable = true)
    private String action_token;

    @Column(name = "referral_customer_email", nullable = true)
    private String referral_customer_email;

    @Column(name = "newsletter_used_flag", nullable = true)
    private Boolean newsletter_used_flag;

    @Column(name = "phone", nullable = true)
    private String phone;

    @Column(name = "status_type", nullable = true)
    private String status_type;

    @Column(name = "status_state", nullable = true)
    private String status_state;

    @Column(name = "first_name", nullable = true)
    private String first_name;

    @Column(name = "last_name", nullable = true)
    private String last_name;

    @Column(name = "external", nullable = true)
    private Boolean external;

    @Column(name = "api_key", nullable = true)
    private String api_key;

    @Column(name = "allow_point_transfer", nullable = true)
    private Boolean allow_point_transfer;

    @ManyToOne(cascade = {CascadeType.ALL})
    @JoinTable(name="ol__users_roles",
            joinColumns={@JoinColumn(name="user_id")},
            inverseJoinColumns={@JoinColumn(name="role_id")})
    private ol__roles role;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public Boolean getIs_active() {
        return is_active;
    }

    public void setIs_active(Boolean is_active) {
        this.is_active = is_active;
    }

    public Timestamp getCreate_at() {
        return create_at;
    }

    public void setCreate_at(Timestamp create_at) {
        this.create_at = create_at;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Timestamp getPassword_requested_at() {
        return password_requested_at;
    }

    public void setPassword_requested_at(Timestamp password_requested_at) {
        this.password_requested_at = password_requested_at;
    }

    public String getConfirmation_token() {
        return confirmation_token;
    }

    public void setConfirmation_token(String confirmation_token) {
        this.confirmation_token = confirmation_token;
    }

    public Timestamp getDeleted_at() {
        return deleted_at;
    }

    public void setDeleted_at(Timestamp deleted_at) {
        this.deleted_at = deleted_at;
    }

    public Timestamp getLast_login_at() {
        return last_login_at;
    }

    public void setLast_login_at(Timestamp last_login_at) {
        this.last_login_at = last_login_at;
    }

    public String getDtype() {
        return dtype;
    }

    public void setDtype(String dtype) {
        this.dtype = dtype;
    }

    public Timestamp getTemporary_password_set_at() {
        return temporary_password_set_at;
    }

    public void setTemporary_password_set_at(Timestamp temporary_password_set_at) {
        this.temporary_password_set_at = temporary_password_set_at;
    }

    public String getAction_token() {
        return action_token;
    }

    public void setAction_token(String action_token) {
        this.action_token = action_token;
    }

    public String getReferral_customer_email() {
        return referral_customer_email;
    }

    public void setReferral_customer_email(String referral_customer_email) {
        this.referral_customer_email = referral_customer_email;
    }

    public Boolean getNewsletter_used_flag() {
        return newsletter_used_flag;
    }

    public void setNewsletter_used_flag(Boolean newsletter_used_flag) {
        this.newsletter_used_flag = newsletter_used_flag;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getStatus_type() {
        return status_type;
    }

    public void setStatus_type(String status_type) {
        this.status_type = status_type;
    }

    public String getStatus_state() {
        return status_state;
    }

    public void setStatus_state(String status_state) {
        this.status_state = status_state;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public Boolean getExternal() {
        return external;
    }

    public void setExternal(Boolean external) {
        this.external = external;
    }

    public String getApi_key() {
        return api_key;
    }

    public void setApi_key(String api_key) {
        this.api_key = api_key;
    }

    public Boolean getAllow_point_transfer() {
        return allow_point_transfer;
    }

    public void setAllow_point_transfer(Boolean allow_point_transfer) {
        this.allow_point_transfer = allow_point_transfer;
    }

    public ol__roles getRoles() {
        return role;
    }

    public void setRoles(ol__roles role) {
        this.role = role;
    }
}

and
package com.Loyalty.OpenLoyalty.Models.User.Projections;
import com.Loyalty.OpenLoyalty.Models.User.ol__user;

import java.util.ArrayList;
import java.util.List;

public class ol__users {
    private List<ol__user> usersList;
    public List<ol__user> getUsersList(){
        if (usersList== null){
            usersList=new ArrayList<>();
        }
        return usersList;
    }
    public void setUsersList(List<ol__user> usersList){
        this.usersList= usersList;
    }

}

my controller:
 @GetMapping("/admin")
    public ol__users getAllAdminUsers(  ){

        return userService.getAllAdminUsers();

    }

My Service:
    @Service
    public class userService   {
        @Autowired
        private userRepository userRepository;

         public ol__users getAllAdminUsers( ){

                ol__users response = new ol__users();
                ArrayList<ol__user> list=new ArrayList<>();
                userRepository.find

Bydtype("admin").forEach(e ->list.add(e));
            response.setUsersList(list);
            return response;

            }
    }

and my repository:
@Repository
public interface userRepository extends JpaRepository<ol__user, String> {

    List<ol__user> findBydtype(String dtype);

    Optional<ol__user> findById(String id);

    Boolean existsByUsername(String username);
    ol__user findByUsername(String username);

    ol__user findByEmail(String username);
    ol__user findByEmailIgnoreCase(String email);

   // @Query(value = "select count(*) as count from ol__user",nativeQuery = true)

}

and finally here is my test code:
ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class Ol_userControllerTest {
    @InjectMocks
    Ol__userController Ol__userController;
    @Mock
    userRepository userRepository;
    @Mock
    userService userService;

    @Test
    @Transactional
    public void testFindAll(){
        ol__roles role=new ol__roles();
        role.setName("tests");
        role.setRole("Admin");
        role.setIs_master(true);
        Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
        ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa@yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
        ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa@yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
        List<ol__user> list = new ArrayList<ol__user>();
        list.addAll(Arrays.asList(user1,user2));

        Mockito.when(userRepository.findBydtype(any())).thenReturn(list);
    //when
        ol__users result = userService.getAllAdminUsers();
   //then
        assertThat(result.getUsersList().size()).isEqualTo(2);
        assertThat(result.getUsersList().get(0).getFirst_name())
                .isEqualTo(user1.getFirst_name());

    }

}

I have debuted my code and I understood that
Mockito.when(userRepository.findBydtype(any())).thenReturn(list);

stores list in it but then in the next line my result object returns null and then the exception happens.
I wonder where my problem is?

A: Yes because you are testing the controller and injected mock to the controller, so the service in the controller is mocked and getAllAdminUsers() returns null.
you should write a test for the controller and another for service
ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class ControllerTest {

    @InjectMocks
    private Ol__userController Ol__userController;
    @Mock
    private userRepository userRepository;
    @Mock
    private userService userService;

    @Test
    public void testFindAll(){
        // Arrange
        ol__roles role=new ol__roles();
        role.setName("tests");
        role.setRole("Admin");
        role.setIs_master(true);
        Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
        ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa@yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
        ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa@yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
        List<ol__user> list = new ArrayList<ol__user>();
        list.addAll(Arrays.asList(user1,user2));

        Mockito.when(ol__users result = userService.getAllAdminUsers()
).thenReturn(list);

        // Act
        List<ol__user> actual = Ol__userController.getAllAdminUsers();

        // Assert
        assertThat(actual.getUsersList().size()).isEqualTo(2);
        assertThat(actual.getUsersList().get(0).getFirst_name())
                .isEqualTo(user1.getFirst_name());
    }
}

, Service test
ExtendWith(MockitoExtension.class)
@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {
    @InjectMocks
    private userService userService;

    @Mock
    private userRepository userRepository;

    @Test
    public void testFindAll(){
        // Arrange
        ol__roles role=new ol__roles();
        role.setName("tests");
        role.setRole("Admin");
        role.setIs_master(true);
        Timestamp currentSqlTimestamp = new Timestamp(System.currentTimeMillis());
        ol__user user1=new ol__user("anteaaa","nejatiaan","anteeaaaa@yahoo.com","anteaaaaa","12345","admin",true,role,"123",currentSqlTimestamp);
        ol__user user2=new ol__user("Nooria","Rajaee","Nooriaaaa@yahoo.com","Nooriaa","12345","admin",true,role,"123",currentSqlTimestamp);
        List<ol__user> list = new ArrayList<ol__user>();
        list.addAll(Arrays.asList(user1,user2));
        when(userRepository.findBydtype(any())).thenReturn(list);

        // Act
        ol__users result = userService.getAllAdminUsers();

        //Assert
        assertThat(result.getUsersList().size()).isEqualTo(2);
        assertThat(result.getUsersList().get(0).getFirst_name())
                .isEqualTo(user1.getFirst_name());
    }
}


text:
Q: Using IdentityServer4/5 without Angular additional libraries Background
I check options to migrate my service authentication system to identityserver4\5. I have two websites:
account.company.com
company.com

My websites are SPA based on .NET core and Angular.
Question
I saw few demo projects identityserver4 demo projects based on SPA that using additional angular libraries (like angular-auth-oidc-client and oidc-client-js). Those libraries are actually client, with id and secret, that exposing this information to the public.

*

*Is it safe to have client id and client secret on the browser?

*I must implement identityserver4\5 with Angular client? maybe a server-side client is enough (all the client requests will be transmitted to server-side, which is a client)?

A: If you run SPA you, your best bet is oidc-client.
But the tutorials you have read are non-sense that suggest client_id/secret auth. No it is not save to have client secret in an SPA app.
For that reason you have the Auth Code + PKCE Flow. AuthCode + PKCE (Proof of Key Code Exchange) works like Auth Code flow (client_id + secret + a code to obtain the token), but the secret is generated per request (see here). This solves the issue of having a static secret and prevents replay attacks.
In the past Hybrid Flow, which would return the token in the redirect request from the Identity Server (after logging in and when being redirected back to your website) but this is the recommended approach anymore as Auth Code + PKCE is the more secure approach.
You can't use a code flow based in the backend in an SPA, because the backend doesn't know the credentials and asking user to directly type in the credentials instead of redirecting them to the identity server is less secure (and less trustworthy since your app has to actually see the credentials) than interactive flows (that redirect you to the Identity Server login page)


text:
Q: How to run multiples contracts functionalities in a single contract Solidity I'm new to Solidity but I can't find much information about my problem.
For example, I want to make different contracts for different functionalities (I see them as classes)
For example
Main contract
// SPDX-License-Identifier: None
pragma solidity >=0.8.6;

import "./AuthContract.sol";

contract Contract {
    string public message;

    constructor() {
      message = "test";
    }

    function getMessage() public view returns(string memory) {
      return message;
    }
}

and second contract
contract Auth {
    struct UserDetail {
        address addr;
        string name;
        string password;
        string CNIC;
        bool isUserLoggedIn;
    }

    mapping(address => UserDetail) user;

    // user registration function
    function register(
        address _address,
        string memory _name,
        string memory _password,
        string memory _cnic
    ) public returns (bool) {
        require(user[_address].addr != msg.sender);
        user[_address].addr = _address;
        user[_address].name = _name;
        user[_address].password = _password;
        user[_address].CNIC = _cnic;
        user[_address].isUserLoggedIn = false;
        return true;
    }

    // user login function
    function login(address _address, string memory _password)
        public
        returns (bool)
    {
        if (
            keccak256(abi.encodePacked(user[_address].password)) ==
            keccak256(abi.encodePacked(_password))
        ) {
            user[_address].isUserLoggedIn = true;
            return user[_address].isUserLoggedIn;
        } else {
            return false;
        }
    }

    // check the user logged In or not
    function checkIsUserLogged(address _address) public view returns (bool) {
        return (user[_address].isUserLoggedIn);
    }

    // logout the user
    function logout(address _address) public {
        user[_address].isUserLoggedIn = false;
    }
}

How could I use the functionalities from that contract in the main contract?
Is such a thing possible in the blockchain?

A: I am quite new here also but i can solve your problem, if not solve i can lead you to a good path .
so firstly you said you want to create multiple contract for different functionalities, this is good but keep in my you are going to exhaust a lot of gas.
so the answer to your problem is easy you can just read it and implement it.
if you want to use a contract in the Another contract (main in your case) you can do it in two ways(according to my knowledge there might be other).

*

*using new keyword

*using address of your previously deployed contract
we will be using the First case as i suppose you havenot deployed the second contract yet
In Order to do it you can use
 Auth myObj=new Auth();
This will create a new instance of the contract Auth in your main contract and now you can use the Auth contract's function in your Main contract.you can create a function copy the above line and you can use the Functions using dot operator.
myObj.register(_address,_name,moreandmore);

I believe this will solve your problem if not you can ask it.
Thank You!


text:
Q: Monitor (mutationobserver)for text change in an element in puppeteer Is it possible to monitor (using mutationobserver) for text change and return the new and the old text, in for example the following situation:
1 changes to 4. What I need is for puppeteer to return the old value of 1 and the new value of 4 when it changes.
Thank you in advance.

A: This script should be enough:
const puppeteer = require('puppeteer');

(async() => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto('https://example.com/');

    // memorize old value
    const oldValue = await page.$eval('.ss1', el => el.textContent);

    // wait until the .ss1 value changes
    while (oldValue == await page.$eval('.ss1', el => el.textContent))
    {
        page.waitFor(1000); // Wait for a second
    }

    // memorize new value
    const newValue = await page.$eval('.ss1', el => el.textContent);

    // output them
    console.log("Old value: " + oldValue);
    console.log("New value: " + newValue);

  await browser.close();
})();


text:
Q: Fast way to parse a string into int in Java
Possible Duplicate:
Read large amount of data from file in Java

I have a string like "2 -56 0 78 0 4568 -89..." end so on. Now I use Scanner.nextInt() to parse it, but it seems to be slow. Platform is Android. Any advices how to implement in for better speed?
Thanks.

A: use myString.split(" "), which split on ' ', then Integer.valuesOf(..)

A: Split the string on the space and parse each entry
for (String s: string.split(" ")) {
  int i = Integer.parseInt(s);
  //do something with i
}

A: You could go for reading the input as normal String and then using Integer.parseInt() on it.

A: You can use String.split("\\s") and then for each string use Integer.valueOf() to parse to an Integer or Integer.parseInt() to parse to an int.

A:   you can use Integer.parseInt(Value of String);


text:
Q: my form is not responmsive on ipad mini 4 view website screen shot on ipad mini4 view
my form is not responsive on this view. i have added all the view port and i also have set my body size to 100%.

                     LOOK UP PROPERTIES
                     The most complete source of properties for buying or renting

                        To Rent
                        For Sale -->

                        For Sale

                         To Rent

</form>


text:
Q: Database schema for separate Stack Exchange accounts 1. I can see here that Stack Exchange sites have separate databases.
But does it have separate users tables for each database? If yes, then how are passwords synchronised across databases?
2. I can see from here that every site's user table has the AccountId of the Stack Exchange Network profile.
An Example:

*

*Here is Nick Craver, network profile with ID 7598.

*His profile in History Site has the account ID linked with the same ID, 7598. Check this query.
I can't see the Accounts table anywhere in the data dumps.
Is the Accounts table with AccountId stored in a separate database?
I would like to know the database structure for accounts.

A: The cross-site-login system is separate from the database.  OpenID passwords (like Google) aren't stored in any case; if you log in using Google, SE asks Google to validate you.  I don't know how SE manages passwords for the email-based accounts you can create, but it's not in the database that contains posts, users, and so on.
There is no publicly-visible table of network IDs.  You can get the network IDs for all current users on a particular site from SEDE or the data dump for that site, and in principle you could run that query on all sites and then collect the results.  You'd still miss some (for example, deleted accounts, or users who only had accounts on deleted sites).  But there's no place where you can get all the network accounts in one place.


text:
Q: Firefox extension for site-maintenance (link checking) Are there any Firefox extensions for site-maintenance, specifically, for checking if all the links on the site are working?
I'm currently using the LinkChecker addon, which works wonderfully, except that it can only do one page at a time.
I'm looking for something more automated, which will check each link, then go down the link and check all links within the page as well. This will continue on to check all the links on the page.
Anything that exists which can do this?

A: For checking links you could try the W3C Link Checker and I do believe it allows recursive checking.
The Web Developer Addon has a link checker that uses the W3C service and also provides several other tools for checking and validating web sites.


text:
Q: Adding tooltips to a complicated SVG file I want to upload my svg to my website, and add tooltips on multiple parts that become visible on hover. Any suggestions for how to approach that?
My SVG was created on Adobe Illustrator, I tried a tutorial that said to paste the xml code into my html file and add in the tooltip libraries and work from there, but that doesnt seem very plausible, since somehow my xml file for my svg is like 250,000 lines :(


text:
Q: Gmail API PHP Get last message of email I'm using the PHP Gmail API to poll for unread emails. When I find one, I'd like to get only the content in the last message of the email thread. So, here is an example thread I built between 2 of my email accounts:
==================================================
MESSAGE ID: 15e9f58a64c41d19
THREAD ID:  15e9f58a64c41d19
DATE:       1505911938000

MESSAGE:

This is an email. Deal with it
==================================================
MESSAGE ID: 15e9f60859f747dd
THREAD ID:  15e9f58a64c41d19
DATE:       1505912456000

MESSAGE:

It's okay. I forgive you

On Wed, Sep 20, 2017 at 8:52 AM, User1 <user1@gmail.com> wrote:

> This is an email. Deal with it
>

==================================================
MESSAGE ID: 15e9f60cdbebde04
THREAD ID:  15e9f58a64c41d19
DATE:       1505912471000

MESSAGE:

I don't care what you think. This is over
On 9/20/2017 9:00:57 AM, User 2 <user2@gmail.com> wrote:
It's okay. I forgive you

On Wed, Sep 20, 2017 at 8:52 AM, User 1 <user1@gmail.com [mailto:user1@gmail.com]> wrote:

This is an email. Deal with it

So, between each ==================== is a single message of a thread. I get this info like this:
function printThreads($service, $thread)
{
    // Print the labels in the user's account.

    $messages = $service->users_threads->get('me', $thread);

    foreach ($messages as $message)
    {
        $params = [];
        $params['format'] = 'full';

        $result = $service->users_messages->get('me', $message->getId(), $params);
        $payload = $result->getPayload();
        $parts = $payload->getParts();

        if (isset($parts[0]))
        {
            $body = $parts[0]['body']->data;
            $san = strtr($body, '-_', '+/');
            $decode = base64_decode($san);

            print "==================================================\n";
            print "MESSAGE ID: " . $message->getId() . "\n";
            print "THREAD ID:  " . $message->getThreadId() . "\n";
            print "DATE:       " . $message->getInternalDate() . "\n\n";
            print "MESSAGE:\n\n";
            print $decode;
            print "\n";
        }
    }
}

but, as can be seen in the print results, each message in the thread is appended by the previous messages in the thread. So, for my polling application to work, I'd like to get back only this from the last message in the thread:
"I don't care what you think. This is over"
Does the API allow me to do that in anyway? I've looked over the messages and threads stuff, but I don't see anything. My other option is to run a regex and split the file at the "On Wed, Sep 20, 2017 at 8:52 AM, User1  wrote:", but I don't think that'd be very reliable.


text:
Q: Transform gradient to reference element Minimal example of the problem

How can you transform the gradient to the reference element?

A: General
The reference and the global basis functions are related by
\begin{equation}
\hat \varphi_i (\hat x) = \varphi_{n_i} (F_K (\hat x)) = \varphi_{n_i} (B_K \hat{x} + b_K), i = 1, 2, 3.
\end{equation}
This yields naturally relation between the gradient too.
Assume gradients are column vectors too.
Then, it holds too
\begin{equation}
\hat \nabla \hat \varphi_i (\hat x) =
\hat \nabla \varphi_{n_i} (F_K (\hat x)) \\ =
\nabla \varphi_{n_i} ( F_K (\hat x) ) \cdot \hat \nabla F_K (\hat x) \\ =
\nabla \varphi_{n_i} ( F_K (\hat x) ) \cdot \hat \nabla (B_K \hat x + b_K) \\ =
\nabla \varphi_{n_i} (x) \cdot B_K \\ =
B_K^T \nabla \varphi_{n_i} (x)
\end{equation}
and so
\begin{equation}
\nabla \varphi_{n_i} (x) = B_K^{-T} \hat \nabla \hat \varphi_i (\hat x).
\end{equation}
Consider $K_1$
\begin{equation}
\varphi_1 (\hat x) = \varphi_2 (B_K \hat x + b_K)
\end{equation}
where
\begin{equation}
B_K = [n_2 - n_1; n_3 - n_1]
\end{equation}
and take
\begin{equation}
b_K = n_2.
\end{equation}
I think we just provided ways how to transform the gradient to the reference element.
Sources

*

*My lecture notes of Course Element methods, page 7 and Equation 13.


text:
Q: How to render uploaded photos with NodeJS and Express? I generally post examples of my best shot at what I'm asking about, but in this case, I have no idea where to start (haven't uploaded photos before in other languages).
So how does one go about rendering uploaded photos.  I'm using Node v0.4.2, Express 1.0.8, and Mongoose 1.0.16 and have uploading of images working (they end up in ~/tmp right now).
Thanks.

A: If you just want to render thumbnail versions of your uploaded images for display, try using the imagemagick wrapper node-imagemagick.
For example, you could store your hires-images in a data-folder on your server (lets say /data/images) and render thumbnail images into a web-accessible folder (on upload).
I do not recommend generating the thumbnails on the fly, as it can massively increase your server's load when a large image (especially vector formats like eps or pdf) is being rendered.
For imagemagick examples, consider reading up the docs for the convert command.


text:
Q: Inactive media session not restarted I've followed the documentation regarding restarting an inactive media session but it's not working for me. According to the documentation as long as you have the proper entry in the AndroidManifest it should just work.
In the logcat, I can see it's connecting to the MediaBrowserService but nothing happens:
2023-02-14 13:23:20.187 11970-11970 MediaBrowserCompat                       D  Connecting to a MediaBrowserService.
2023-02-14 13:23:20.216 11970-11970 ExoPlayerImpl                            I  Init 690e213 [AndroidXMedia3/1.0.0-beta03] [redfin, Pixel 5, Google, 33]
2023-02-14 13:23:20.253 11970-11970 ExoPlayerImpl                            I  Release 690e213 [AndroidXMedia3/1.0.0-beta03] [redfin, Pixel 5, Google, 33] [media3.common, media3.exoplayer, media3.decoder, media3.datasource, media3.extractor]
2023-02-14 13:23:20.760 11970-11970 MediaBrowserCompat                       D  Connecting to a MediaBrowserService.
2023-02-14 13:23:20.783 11970-11970 ExoPlayerImpl                            I  Init 7df60bd [AndroidXMedia3/1.0.0-beta03] [redfin, Pixel 5, Google, 33]
2023-02-14 13:23:20.819 11970-11970 ExoPlayerImpl                            I  Release 7df60bd [AndroidXMedia3/1.0.0-beta03] [redfin, Pixel 5, Google, 33] [media3.common, media3.exoplayer, media3.decoder, media3.datasource, media3.extractor]
2023-02-14 13:23:26.319 11970-11970 MediaBrowserCompat                       D  Connecting to a MediaBrowserService.
2023-02-14 13:23:26.345 11970-11970 ExoPlayerImpl                            I  Init 540e5f3 [AndroidXMedia3/1.0.0-beta03] [redfin, Pixel 5, Google, 33]
2023-02-14 13:23:26.388 11970-11970 ExoPlayerImpl                            I  Release 540e5f3 [AndroidXMedia3/1.0.0-beta03] [redfin, Pixel 5, Google, 33] [media3.common, media3.exoplayer, media3.decoder, media3.datasource, media3.extractor]
2023-02-14 13:23:27.001 11970-11970 MediaBrowserCompat                       D  Connecting to a MediaBrowserService.
2023-02-14 13:23:27.025 11970-11970 ExoPlayerImpl                            I  Init f1d97e0 [AndroidXMedia3/1.0.0-beta03] [redfin, Pixel 5, Google, 33]

I'm know ExoPlayer has a MediaSessionConnector but the documentation doesn't say to use it and there's little code examples on how to implement it.
This is a stripped down version of my MediaBrowserService code:
public class MediaPlayerService extends MediaBrowserServiceCompat {
    private ExoPlayer mPlayer;
    private MediaSessionCompat mMediaSessionCompat;

    @Override
    public void onCreate() {
        super.onCreate();

        mMediaSessionCompat = new MediaSessionCompat(this, MediaPlayerService.class.getSimpleName());
        mMediaSessionCompat.setCallback(mMediaSessionCallback);
        mMediaSessionCompat.setActive(true);

        mPlaybackBuilder = new PlaybackStateCompat.Builder();
        mPlaybackBuilder.setActions(
                        PlaybackStateCompat.ACTION_PLAY_PAUSE |
                                PlaybackStateCompat.ACTION_PLAY |
                                PlaybackStateCompat.ACTION_PAUSE |
                                PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
                                PlaybackStateCompat.ACTION_SKIP_TO_NEXT);

        setSessionToken(mMediaSessionCompat.getSessionToken());

        mPlaybackAttributes = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .build();

        mPlayer = new ExoPlayer.Builder(mContext).build();
        mPlayer.addListener(new PlayerEventListener());
    }

    private final MediaSessionCompat.Callback mMediaSessionCallback = new MediaSessionCompat.Callback() {

        @Override
        public void onStop() {
            super.onStop();

            StopAudio();
        }

        @Override
        public void onPlay() {
            super.onPlay();

            PlayAudio();
        }

        @Override
        public void onPause() {
            super.onPause();

            PauseAudio();
        }
    };

     private class PlayerEventListener implements Player.Listener {

        @Override
        public void onPlaybackStateChanged(int state) {
            if (state == Player.STATE_BUFFERING) {

            } else if (state == Player.STATE_READY) {

            } else if (state == Player.STATE_ENDED)
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mMediaSessionCompat.setMetadata(null);
        mMediaSessionCompat.setActive(false);
        mMediaSessionCompat.release();

        mPlayer.release();
    }

}

A: The clue is this part in the documentation:

If Android can identify the last active media session, it tries to
restart the session by sending an ACTION_MEDIA_BUTTON Intent to a
manifest-registered component (such as a service or
BroadcastReceiver).

This means you need to override onMediaButtonEvent in the MediaSessionCompat.Callback and restart playback there:
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {

KeyEvent keyEvent = (KeyEvent) mediaButtonEvent.getExtras().get(Intent.EXTRA_KEY_EVENT);

    if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_MEDIA_PLAY) {
    //restart playback
    }

    return super.onMediaButtonEvent(mediaButtonEvent);
}


text:
Q: List null when deserializing json in Spring Boot controller I have a problem with a controller in a Spring Boot application. When I make a call on the controller (URI/call), the object list is always null.
{
    "code": "TEST",
    "name": "TEST NAME",
    "groupe": "A1",
    "list": [
        {"type":"web", "link":"https://google.com/"},
        {"type":"web", "link":"https://google2.com/"}
    ]
}

@PostMapping(value="/call")
    public ResponseEntity<Void> ajouterEnvironnement(@RequestBody First first) {
        first.getCode() // value : "TEST"
        first.getList() // value : null
}

public class First {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String code;
    private String name;
    private String groupe;
    @OneToMany(mappedBy = "first", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Second> list;
}

public class Second {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String type;
    private String link;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "first_id", nullable = false)
    private First first;
}

A: By writing this question, I was able to find a solution, so I share it:
Use the @JsonManagedReference and @JsonBackReference annotations.
More information here.
public class First {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String code;
    private String name;
    private String groupe;
    @OneToMany(mappedBy = "first", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JsonManagedReference
    private List<Second> listLiens;
}

public class Second {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String type;
    private String link;
    @ManyToOne(fetch = FetchType.EAGER)
    @JsonBackReference
    @JoinColumn(name = "first_id", nullable = false)
    private First first;
}


text:
Q: Response.WriteFile function fails and gives 504 gateway time-out Environment:
-SharePoint 2010 foundation
-Claim based authentication
-Execution time out in web.config is set to 3600
Overview:
We have an excel export functionality where we connect to AD and SQL databases to fetch Users and their related data for a perticular Organization Unit (OU)in Active Directory.
We have on OU in  AD which has got around 1400 users in it. We are using Open and Closed xml to generate excel file which works fine and takes about 11-14 minutes to generate a file on the server on following path
C:\inetpub\wwwroot\wss\VirtualDirectories\VirtualDirectyrName\Excel\FileName.xlsx
Immediately after generating a file we have following piece of code which would read file from server and dump it on output steam and presents a file ope-save as dialog box in browser to end user.
Problem Description:
When an Organization has less number of users and it does not take more than 5-6 minteus to generate the file on server, following piece of code successfully downloads the file on browser. But when for above mentioned OU where we have 1400 users the reponse.writefile function fails and in browse we get to see 'Browse can not display this web page' (when fiddler was on we found it gives - http 504 error). Surpricingly if we perform this export from the server itself (i.e browse the web site on server) it downloads without issue.
protected void lnkbtnDownloadFile_Click(object sender, EventArgs e)
{

    String fileName = @"C:\inetpub\wwwroot\wss\VirtualDirectories\VirtualDirectyrName\Excel\540KBFileWhichFails.xlsx";
        //File size is hardly ~500 KB
        //Wait for around 12 minutes, to mimic a scenario of file generation which takes time on staging and prod. environment.
        System.Threading.Thread.Sleep(720000);
        try
        {
        if (fileName != "")
                {
                    var file = new FileInfo(fileName);

                    if (file.Exists)
                    {
                        Response.Clear();
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
                        Response.AddHeader("Content-Length", file.Length.ToString());
                        Response.ContentType = "application/octet-stream";
                        Response.WriteFile(file.FullName);
                        Response.End();
                    }
                    else
                        Response.Write("This file does not exist.");
                }
            }
            catch (Exception ex)
            {
                //This would usually give thread aboart exception but thats expected.
            }
}

we dont see any error in ULS logs, event logs specific to this behavior.
Please note , response.TransmitFile also gives same behaviour.
any idea ?

A: What I suspect here is that you have felt on session lock. What I mean is that the download and the generation and all this calls made using the session, and session locks everything until finish.
To solve this issue do two thinks.

*

*When you generate this file, generate it ether with thread ether with handle with out session needed

*Download this file from a handler (that not use session) and not from the page post back.

For example you make a handler, eg download.ashx and you make a link to your page as download.ashx?thisfileId=7723423&SecurityID=82jkj1288123 Inside your handler you read this parameters and you send the file. But if you make this on the page then a way is to disable the session for this page if you not use session, for example you set EnableSessionState="false" on the first line declarations.
Some similar questions and session relative answer.
call aspx page to return an image randomly slow
Replacing ASP.Net's session entirely
How to deliver big files in ASP.NET Response?

A: I figured out the issue, It was an issue with the Idle time out issue in the Hardware load balancer we where using. Default value in load balancer was 0 which meant 11 minutes and my file generation was taking longer than that which caused this issue. Increasing load balancer idle time out issue seems to be solutions.


text:
Q: How to run second function after the first has ended in javaScript? function addItemToCart (id_1, id_2, id_3, id_etc) {
  jQuery.ajax({

  });
}

function clearCart()
{
  jQuery.ajax({
  });
}

function buyButton()
{
    clearCart();
    setTimeout(function()
    {
        redirect to cart;
        addItemToCart(283746 , 1, 1, "Months", "1294");
    }, 500);
}

I'm trying to make it so that instead of using a setTimeout it waits until the clearCart() has finished loading through ajax and then it runs the functions inside the setTimeout and I can't seem to figure this out.. I tried doing a callback but I'd say that it isn't correct..
function FirstFunction(callBack)
{
    clearCart();

    if (callback)
    {
        callback();
    }
}
function SecondFunction()
{
    buyButton();
}

FirstFunction(SecondFunction);

A: If you want to run some code when an Ajax response has arrived, put it in the done or success handler function. That is what those functions are for.
Don't guess how long the request is going to take.

A: Need to use done or success callback to avoid any random waiting time. like below:
function clearCart()
{
  return jQuery.ajax({
  });
}

function buyButton()
{
    clearCart().done(function () {
        addItemToCart(283746 , 1, 1, "Months", "1294");
    });
}