text:
Q: Securing Node + Postgres + Passport I'm currently learning node, postgres, and passport but I am not sure on how to secure my application and best practices. I'm not sure on how to sanitize data from client and server or if it's needed but I've parameterized my queries. Any help would be greatly appreciated! Apologies for my newbieness.

var express = require('express');
var helmet = require('helmet')

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');

var passport = require('passport');
var passportLocal = require('passport-local');
var pg = require ('pg');
var bcrypt = require('bcryptjs');

var app = express();
app.use(helmet());
var server = require('http').createServer(app);
var io = require('socket.io')(server);

var config = {
  user: 'REDACTED',
  database: 'REDACTED',
  password: 'REDACTED',
  host: 'REDACTED',
  port: 5432,
  max: 10,
  idleTimeoutMillis: 30000,
};

var pool = new pg.Pool(config);
pool.on('error', function (err, client) {
  console.error('idle client error', err.message, err.stack)
})

app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(expressSession( {
  secret: process.env.SESSION_SECRET || 'secret',
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new passportLocal.Strategy(function(username, password, done) {
  pool.connect(function(poolErr, poolClient, poolDone) {
    if(poolErr) {
      return console.error('pool client fetch error', poolErr);
    }

    poolClient.query('SELECT id, password FROM users WHERE username = $1', [username], function(queryErr, queryRes) {
      if(queryErr) {
        return console.error('query error', queryErr);
      }

      if(queryRes.rows[0] != undefined)
      {
          bcrypt.compare(password, queryRes.rows[0].password, function(compareErr, compareRes) {
            if(compareErr) {
              return console.error('bcrypt error', compareErr);
            }

            if(compareRes) {
                done(null, { id: queryRes.rows[0].id });
            } else {
                done(null, null);
            }

            poolDone();
          });
      } else {
        //user not found
        poolDone();
        done(null, null);
      }
    });
  });

}));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  pool.connect(function(err, poolClient, poolDone) {
    if(err) {
      return console.error('pool client fetch error', err);
    }

    poolClient.query('SELECT * FROM users WHERE id = $1', [id], function(queryErr, queryRes) {
      if(queryErr) {
        return console.error('query error', queryErr);
      }

      if(queryRes.rows[0] != undefined)
      {
        done(null, { id: id, username: queryRes.rows[0].username, firstname: queryRes.rows[0].firstname, lastname: queryRes.rows[0].lastname });
      } else {
        //user not found
 done(null, null);
      }

      poolDone();
    });
  });

});

app.set('view engine', 'ejs');

app.get('/', function(req, res) {
  res.render('index', {
    isAuthenticated: req.isAuthenticated(),
    user: req.user
  })
});

app.get('/login', function(req, res) {
  res.render('login');
});

app.post('/login', passport.authenticate('local'), function(req, res) {
  res.redirect('/');
});

app.get('/logout', function(req, res) {
  req.logout();
  res.redirect('/');
});

server.listen(8080);
console.log('Server is running...');

A: I don't see much problem but here is my 2 cent to improve it.
Use compression to reduce network size
app.use(require('compression'));

Use serve-static for static file like images or pdf
app.use(require('serve-static')('./public'))

Use middleware to control end point that need Authentication like view/edit profile, change password and etc
function authenticated(req, res, next) {
  if (req.isAuthenticated()) next();
  else {
    res.status(401).send('User not authenticated.');
    // or redirect to login
  }
}

app.get('/profile', authenticated, function(req, res) {
  res.render('profile', {
    req.user
  })
})

Include session destroy when logout
app.get('/logout', function(req, res) {
  req.session.destroy();
  req.logout();
  res.redirect('/');
});

A: for sanitizing queries you can use ORM like sequelise


text:
Q: Update database with multiple reference database issues I am fairly new to mongoose/express. What I am struggling with is trying to update new data from html form and save it to database that has references. I have a business model with location reference to location model. Here's the codes.
edit.ejs

        <form action="/<%= bus._id %>?_method=PUT" method="POST">

Business Information

            <input class="form-input" type="input" name="bus[logo]" value="<%= bus.logo %>">
            <input class="form-input" type="input" name="bus[name]" value="<%= bus.name %>">
            <% bus.location.forEach(function(location) { %>
            <input class="form-input" type="input" name="bus.location[street]" value="<%= location.street %>">
            <input class="form-input" type="input" name="bus.location[city]" value="<%= location.city %>">

                <select class="form-inline" name="bus.location[state]">
                    <option value="" disabled selected><%= location.state %></option>
                    <option value="AL">Alabama</option>
                    ...
                    <option value="WY">Wyoming</option>
                </select>

            <input class="form-inline" type="input" name="bus.location[zipcode]" value="<%= location.zipcode %>">
            <% }) %>

Contact Information

            <% bus.contact.forEach(function(contact) { %>
            <input class="form-input" type="url" name="bus[url]" value="<%= bus.url %>">
            <input class="form-input" type="email" name="bus.contact[email]" value="<%= contact.email %>">
            <input class="form-input" type="tel" name="bus.contact[phone]" value="<%= contact.phone %>">
            <input class="form-input" type="input" name="bus.contact[twitter]" value= "<%= contact.twitter %>">
            <input class="form-input" type="input" name="bus.contact[facebook]" value="<%= contact.facebook %>">
            <input class="form-input" type="input" name="bus.contact[instagram]" value="<%= contact.instagram %>">
            <% }) %>

index.js - edit routes
//(edit.ejs) Edit Route
app.get('/:id/edit', function(req, res) {
    Business.findById(req.params.id)
    .populate('location')
    .populate('contact')
    .populate('images')
    .exec(function(err, bus) {
        if(err) {
            console.log(err);
        } else {
            res.render('edit', {bus:bus});
        }
    });
});
app.put('/:id', function(req, res) {
    Business.findByIdAndUpdate(req.params.id, req.body.bus, function(err, bus) {
        if(err) {
            console.log(err);
            res.redirect('/' + req.params.id + '/edit');
        } else {
            res.redirect('/' + req.params.id);
        }
    });
});

The business (bus) updates nicely but bus.location doesn't update.
Business model
//----------------------------------------------------------------------------\\
var mongoose = require('mongoose');
//----------------------------------------------------------------------------\\
var busSchema = new mongoose.Schema({
    name: String,
    type: String,
    logo: String,
    desc: String,
    subs: Number,
    video: String,
    url: String,
    firstRun: Boolean,
    location:[
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Location'
      }
    ],
    contact:[
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Contact'
      }
    ],
    images:[
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Image'
      }
    ],
    comments:[
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: 'Comment'
      }
    ],
    created: {
       type: Date, default: Date.now
    }
});
//----------------------------------------------------------------------------\\
module.exports = mongoose.model('Business', busSchema);

Location Model
//----------------------------------------------------------------------------\\
var mongoose = require('mongoose');
//----------------------------------------------------------------------------\\
var locSchema = new mongoose.Schema(
    {
        street: String,
        city: String,
        state: String,
        zipcode: Number
    }
);
//----------------------------------------------------------------------------\\
module.exports = mongoose.model('Location', locSchema);

A: Business, Location and Contact are different collections.
findByIdAndUpdate only updates one collection, which yours in particular is Business. In order to update the other collections, you need to perform operations on those collections.
If you are trying to update "existing" locations and contacts, then you'll need to provide also their IDs. Also, you have an "array" of locations and contacts, so you need additional [] to your names.
<% bus.location.forEach(function(location, i) { %>
    <input type="hidden" name="location[<?= i ?>][id]" value="<%= location.id %>">
    <input class="form-input" type="input" name="location[<?= i ?>][street]" value="<%= location.street %>">

<% }) %>

<% bus.contact.forEach(function(contact, i) { %>
    <input type="hidden" name="contact[<?= i ?>][id]" value="<%= contact.id %>">
    <input class="form-input" type="email" name="contact[<?= i ?>][email]" value="<%= contact.email %>">

<% }) %>

From my (and others) experience, I do not think it is possible to update multiple documents at once. This means, in your route handler, you will need to iterate over each item in the arrays that you are given and update them one by one. The answer in the other post though is not quite right IMO as you shouldn't be using synchronous forEach to do asynchronous mongoose operations as it will lead to unexpected behaviour.
You have three main tasks to do: update the business, update their existing locations, and update their existing contacts.
I like to use async.js to perform multiple asynchronous operations. In your particular case, I would use async.series to do each task and async.eachSeries to do an operation on each element of your arrays.
Warning This is untested but it would look something like this:
app.put('/:id', function(req, res) {

    console.log(req.body.bus);
    console.log(req.body.location); // should be an array of objects
    console.log(req.body.contact); // should be an array of objects

    // perform each task one by one
    async.series([
        function updateBusiness (done) {
            // you need to always call the callback i.e. done to indicate the task is "done"
            // - if you pass an error as an argument, it means the task failed and stop everything
            // - otherwise, move onto the next task

            /*Business.findByIdAndUpdate(req.params.id, req.body.bus, function (err) {
                if (err) {
                    return done(err); // task failed and stop everything
                }
                done(); // task went well and proceed to the next task
            });*/

            // simplified
            Business.findByIdAndUpdate(req.params.id, req.body.bus, done);
        },
        function updateLocations (done) {
            // find and update each location
            async.eachSeries(req.body.location || [], function (location, done2) {
                Location.findByIdAndUpdate(location.id, location, done2);
            }, done);
        },
        function updateContacts (done) {
            // find and update each contact
            async.eachSeries(req.body.contact || [], function (contact, done2) {
                Contact.findByIdAndUpdate(contact.id, contact, done2);
            }, done);
        }
    ], function allDone (err) {
        // a task failed somewhere
        if (err) {
            console.log(err);
            res.redirect('/' + req.params.id + '/edit');
        // all tasks were completed
        } else {
            res.redirect('/' + req.params.id);
        }
    });
});

If there is an error, look at the console logs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python/Pyspark : Remove postalcode from the address column I have a column which has the addresses like below -
Address

5 HARBOURplace st. HARBOURFRONT T 98899
PULAV AYTR CHAIWAN 98644
4500 BAYTOWN DRIVE, ROOM 2466 77555
77210
22567 SPRINGlane VILLAGE drive 77355-1445
PO BOX 2422 F2K 6L2
FERKERN 30 4044
ATTN : PALACE SHIP 7654

I want to separate postalcode out of it to another column like below
Address                                postalcode
PULAV AYTR CHAIWAN                       98644
4500 BAYTOWN DRIVE, ROOM 2466            77555
                                         77210
22567 SPRINGlane VILLAGE drive        77355-1445
PO BOX 2422 F2K 6L2
FERKERN 30                               4044
ATTN : PALACE SHIP                       7654

I am trying this -
df['zip'] = df['address'].str.extract(r'(\d{5}\-?\d{0,4})')

but it splits only 5 digits and also pick up house number if it is of 5 digit like 5th record below. Also it does not remove postalcode from address column
Address                                         postalcode
5 HARBOURplace st. HARBOURFRONT T 98899            98899
PULAV AYTR CHAIWAN 98644                           98644
4500 BAYTOWN DRIVE, ROOM 2466 77555                77555
77210                                              77210
22567 SPRINGlane VILLAGE drive 77355-1445          22567
PO BOX 2422 F2K 6L2
FERKERN 30 4044
ATTN : PALACE SHIP 7654

How can I achieve it?

A: Assuming that the postal code is always at the end of the address text and is always a numeric value, you may try this -
df['zip'] = df['address'].apply(lambda x: str(x.split(" ")[-1]) if str(x.split(" ")[-1]).replace("-", "").isnumeric() else "")

Otherwise, you would need a better pattern matching regex.
Edit: Removing postal code from original address value
Once the postal code is extracted into a separate column, concatenate the remaining list elements in the split
df['address'] = df['address'].apply(lambda x: " ".join(x.split(" ")[:-1]) if str(x.split(" ")[-1]).replace("-","").isnumeric() else " ".join(x.split(" ")))


text:
Q: Javascript window.open file download callback I am using the window.open(downloadUrl, '_self') to download a tar.gz file from server. I want to delete the same file form the server once either the download successful (by using the save button in file save dialog) or download was cancelled (by using the cancel button in file save dialog) by the user.
Are there any callback mechanism which I can use to get notify as soon as file written to client pc successfully or client cancelled the download?

A: The problem is that the browser is handling the download once it starts and you don't have a hook into the success of that download. You might consider something like jQuery to download the file. Maybe something like the following. Here is a working jsFiddle.
NOTE: this is considered experimental technology and doesn't have support in all browsers.
var loc = 'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js';
var url = '';

$('#output > a').on('click', function() {
    URL.revokeObjectURL(url);
    $('#output').empty();
    console.log('Revoked URL.');
});

$('#download').click(function () {
    $.get(loc, function (data) {
        var data = [data];
        var blob = new Blob(data, {
            type: 'application/javascript'
        });
        url = URL.createObjectURL(blob);
        $('#output').append('Save it!');
    })
        .fail(function () {
            // delete the file - probably a $.ajax
            //$.ajax({
            //    url: 'url',
            //    type: 'DELETE'
            //});
        });
});


text:
Q: How can I use a curly brace together with subequations? The code
\begin{equation}
\begin{cases}
x+y=2 \\
x-y=0
\end{cases}
\end{equation}

produces two aligned equations, with a curly brace to the left. I want to refer to the individual equations, and the subequations environment looks right. However when I try using it, I can't find a way to leave that curly brace on the left.
Is there a way to do so?


text:
Q: CSS3 background-image transition In this website I am making there is an arrow link that when you hover over it it becomes a new image with a cool addition to the image.  I had this working completely fine with this code below and I did not edit the code at all but it seems that when I woke up the "all" transition no longer works for this.  I can't find what is wrong. I am also using this to fade a background-image that is a solid color to fade to another background image that is a different solid color.
a.visitarrow
{
-webkit-transition:all 1.0s ease-in-out;
-moz-transition:all 1.0s ease-in-out;
-o-transition:all 1.0s ease-in-out;
-ms-transition:all 1.0s ease-in-out;
transition:all 1.0s ease-in-out;
display:block;
width:130;
height:121;
background-image:url('pictures/visit.png');
}

a.visitarrow:hover
{
-webkit-transition:all 0.5s ease-in-out;
-moz-transition:all 0.5s ease-in-out;
-o-transition:all 0.5s ease-in-out;
-ms-transition:all 0.5s ease-in-out;
transition:all 0.5s ease-in-out;
display:block;
width:130;
height:121;
background-image:url('pictures/visithover.png');
}

A: I believe this should work:
a.visitarrow {
    display: block;
    width: 130;
    height: 121;
    -webkit-transition: 1.0s ease-in-out;
    -moz-transition: 1.0s ease-in-out;
    -o-transition: 1.0s ease-in-out;
    -ms-transition: 1.0s ease-in-out;
    transition: 1.0s ease-in-out;
    background-image: url('pictures/visit.png');
}

a.visitarrow:hover {
    background-image: url('pictures/visithover.png');
}


text:
Q: EXCEL: Return Unique Values from Two Different Columns in Two Different Sheets in One Column in Another Sheet I want to return all unique values from TWO separate columns in TWO different sheets into ONE column in another sheet. For example, I have three sheets: IN, OUT, and UNIQUE.

*

*Sheet "IN" has a table called "IN_TABLE" with the following columns: PRODUCT ID, QTY, SUPPLIER ID, DATE, and TIME.

*Sheet "OUT" has a table called "OUT_TABLE" with the following columns: PRODUCT ID, QTY, CUSTOMER ID, DATE, and TIME.

*Sheet "UNIQUE" is where I want to return all UNIQUE Product ID from both Sheets "IN" and "OUT".

Hence, if my "IN" Sheet looks like the following:

And my "OUT" Sheet looks like the following:

I want my "UNIQUE" Sheet to look something like this:

In Google Sheets, you can return the unique values for each sheets in Column C and D of Sheet "UNIQUE" and then use the =UNIQUE(FLATTEN()) function to do something like this, but I don't know how I will achieve this using Excel 365.

A: Interesting question, you can't put two column arrays together with a semicolon like you can in Google sheets. Here is a possible workaround:
=LET(count1,COUNTA(In!A:A)-1,count2,COUNTA(Out!A:A)-1,seq,SEQUENCE(count1+count2),
UNIQUE(IF(seq<=count1,INDEX(In!A:A,seq+1),INDEX(Out!A:A,seq-count1+1))))

IN

OUT

Shake it all about:

Explanation
In my example, there are four rows of data in the first sheet and five in the second sheet, with two entries (C & D) that appear in both sheets. The method is to count the number of rows in the first sheet, excluding the header (count1) and in the second sheet (count2). Then create a single-column array using Sequence, containing numbers 1-9:
1
2
3
4
5
6
7
8
9

Then feed this into Index to pick out the four entries in the first sheet (where the sequence = 1 to 4, i.e. less than or equal to count1) and the five entries in the second sheet (where sequence = 5 to 9, i.e. greater than count 1), subtracting count1 so that the values 1 to 5 are used, but now applying to the second sheet. The +1 is just to exclude the header rows in both sheets. Fortunately, in Excel 365, Index behaves nicely and gives you an array of values for a range of indices, unlike in previous versions where you had to use the 'if ({1} n(indices))' syntax to coerce it into producing an array. Then finally use Unique to exclude the duplicate values from the array.

A: A slight modification to this answer by @BigBen:

Formula in F2:
=UNIQUE(FILTERXML("<t><s>"&TEXTJOIN("</s><s>",,Table1[PRODUCT_IN],Table2[PRODUCT_OUT])&"</s></t>","//s"))

Or, if TEXTJOIN()'s limits are too narrow, based on my own answer here, you could use LET():
=LET(X,CHOOSE({1,2},Table1[PRODUCT_IN],Table2[PRODUCT_OUT]),Y,SEQUENCE(ROWS(X)*2),Z,INDEX(IF(ISERROR(X),"",X),1+MOD(Y,ROWS(X)),ROUNDUP(Y/ROWS(X),0)),UNIQUE(FILTER(Z,Z<>"")))


text:
Q: MySQL - how to handle some data shared by all users some unique to this user? I tried searching but couldn't find anything similar.
Let's say I have a system that lets users manage cars. Cars can have any number of attributes - one of which is color. When a user enters the car manager screen they can select which color this car would be. By default the system is populated with any number of colors. However the user can add their own unique colors in addition to using the system defaults. They could also choose to not use any of the system defaults and remove those from their color options (say they never have blue cars and blue is a system default color).
Once a user enters a unique color it is always in their list of color options. Likewise if they remove a default color that is now removed from their list of colors.
What's the best way to handle this? Two tables - one of default colors, one of colors unique to that user's account? Would I just use one table that is seeded with the default colors and tied to the user's account ID?
Am I overthinking this? Underthinking this??


text:
Q: How to get module working in both Node and browser without transpiler? Now that Chrome supports import/export I thought we could share some code between Node.js and browser without the need for Babel, but because export can't be wrapped in a conditional, I'm not sure how we can do this.
e.g. is there some way to write something like this
if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
    module.exports = BigInt;
} else {
    export default BigInt;
}

and trick both the Chrome and Node into parsing it?


text:
Q: Already an open DataReader with this connection So basically I have two connections in my application:
conn = new MySqlConnection("server=" + ip + ";uid=" + user +";pwd=" + pass + ";database=" + db);
readconn = new MySqlConnection("server=" + ip + ";uid=" + user + ";pwd=" + pass + ";database=" + db);

I use conn only for execution statements, such as UPDATE and INSERT. Then I use readconn only whenever someone joins the server which deals with a SELECT statement.
Then this error occurs with seemingly no pattern to it, other than it's being caused by the same function every time (which does an INSERT query on a transaction on the conn connection).
There is already an open DataReader associated with this Connection which must be closed first.

What I don't understand is, this stack trace shows that this error occurred in a function that uses conn, not readconn. On conn there is never, ever a DataReader being associated with it. It's almost as if there is only one connection, but this is why I specifically open two different connections, one for reading and one for inserting.
Any help or suggestions would be appreciated, maybe I'm just missing out on something obvious here.

A: You need to close the connection with conn.Close().
Or better, use something like:
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
//Your code
}

using (MySqlConnection readConn = new MySqlConnection(connectionString))
{
//Your code
}

it will close automatically the connection ;)


text:
Q: DataGridView: Add Data Programatically on Specific Cells I'm currently trying to add data programatically onto a DataGridView, but it doesn't seem to be working.
What I have is an Array, which I fill from a text file:
public static string PathList = @"C:\Users\gbbb\Desktop\Pfade.txt";
_PathRows = System.IO.File.ReadAllLines(@PathList);

and I have a DataGridView with 4 Columns on which I add as many Rows as I have paths, so:
 public void InitPathsTable()
{
TabelleBib.Rows.Add(_PathRows.Length);
//And here is where i want to add the Paths on Column Nr.4
}

Next what I need is a way to add all paths that I get (24) into the Column Nr.4,
one Path per Row.
But it seems to be nearly impossible for a beginner like me, so I am asking you.

A: This is method that will do that for you. Read comments (especially make sure you have added 4 columns to you DataGridView):
public void InitPathsTable()
{
       int rowindex;
       DataGridViewRow row;

       foreach (var line in _PathRows)
       {
               rowindex = TabelleBib.Rows.Add(); //retrieve row index of newly added row
               row = TabelleBib.Rows[rowindex];  //reference to new row

               row.Cells[3].Value = line; //set value of 4th column to line. WARNING: TabelleBib has to have 4 columns added either from code or designer othwerwise here you will get exception
       }
}

if you get any more problems, write a comment and I will come back to you :)


text:
Q: How to sort two firebase streams Flutter How can I retrieve two streams from firebase and merge into one stream sorted by time?
I have seen various uses of Rx and StreamGroup and StreamZip however I am not sure how to sort the resultant stream.

A: I solved this using Rx.combineLatest([stream1,stream2], (values) => values); then sorted the list after combining the stream lists inside the streambuilder:
List list1 = snapshot.data[0];
List list2 = snapshot.data[1];
streams.addAll(list1);
streams.addAll(list2);
streams.sort(etc...)


text:
Q: Coordinates of imageview I have an imageview (lets say imageview) and green square imageview(greenimageView) and both are added on a self.view.
Assumption: greenimageView never moves.
On scroll, imageview  moves and I need to find out the coordinates of greenimageView on imageView(overlaping region)

In my example below it would be nose and eyes area.

A: You can use the convertRect:toView method:
CGRect rect = [self.view convertRect:y.frame toView:x];

A: Simply convert the box position to UIIImageView coordinates.
CGPoint greenPosAccordingToImageView = [self.imageView convertPoint:self.greenBox.frame.origin fromView:self.greenBox.superView];


text:
Q: django "only()" method seems not to work properly Models.py
class Post(models.Model):
    id = models.IntegerField(default=0)
    name = models.CharField(max_length=200, default='', blank=True)
    click = models.IntegerField(default=0)
    content = models.CharField(max_length=200, default='', blank=True)

Below, what I coded
post = Post.objects.filter(id=3).only('name')
print(post.values())

Result what I expected
<QuerySet [{'name': 'Micheal'}]>

But the actual result was
<QuerySet [{'id': 3, 'name': 'Micheal', 'click': 2, 'content': 'asdf'}]>

How can I fix the problem?

A: Looks like you've misunderstood the usage of only():

The only() method is more or less the opposite of defer(). You call it
  with the fields that should not be deferred when retrieving a model.
  If you have a model where almost all the fields need to be deferred,
  using only() to specify the complementary set of fields can result in
  simpler code.

What is you're looking for is values() and values_list():
Post.objects.filter(id=3).values('name')

A: post = Post.objects.filter(id=3).only('name')
print(post.values())

We can write your query in one line like:
post = Post.objects.filter(id=3).only('name').values()
print(post)

In values(), if you don't specify the fields, each dictionary will contain a key and value for every field in the database table.

The values() method takes optional positional arguments, *fields, which specify field names to which the SELECT should be limited. If you specify the fields, each dictionary will contain only the field keys/values for the fields you specify. If you don't specify the fields, each dictionary will contain a key and value for every field in the database table.

So, that is why:
<QuerySet [{'id': 3, 'name': 'Micheal', 'click': 2, 'content': 'asdf'}]>

Is the expected output.

How can I fix the problem?

*

*Just user values() or values_list().

*You might be interested in using the flat=True argument of values_list() as you want only one field (name).


text:
Q: How to convert a few lines of code from vb.net to its c# equivalent I'm tasked with converting some older VB.net code to C#. Been slowly chipping away at the errors -went from about 100, down now to ~10. The first vb.net code that needs to be converted is:
Try
    My.Computer.FileSystem.CopyFile(strFile, strExportPath + "\" + strFileName(0), FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)
    intFilesCopied += 1

    My.Computer.FileSystem.MoveFile(strFile, _strPath + "Data\Backup\" + strFileName(0), FileIO.UIOption.OnlyErrorDialogs, FileIO.UICancelOption.DoNothing)
    intFilesMoved += 1

Catch ex As Exception
    My.Application.Log.WriteException(ex, TraceEventType.Error, "ExportDataToolStripMenuItem_Click")

End Try

My C# attempt is as follows:
try
{
    File.Copy(strFile, strExportPath + @"\" + strFileName[0], UIOption.OnlyErrorDialogs,
    FileIO.UICancelOption.DoNothing);
    intFilesCopied += 1;

    File.Move(strFile, _strPath + @"Data\Backup\" + strFileName[0],
    UIOption.OnlyErrorDialogs, UICancelOption.DoNothing);
    intFilesMoved += 1;
}
catch (Exception ex)
{
    Application.Log.WriteException(ex, TraceEventType.Error, "ExportDataToolStripMenuItem_Click");
}

The next piece of VB.NET is the catch portion of the try-catch clauses.
My.Application.Log.WriteException(ex, TraceEventType.Error, "Could not write record to data file " + _strActiveFileName + Environment.NewLine + "Record Data: " + strRecordText);

And for the life of me, cannot find the C#-equivalent for this.
I've tried adding the Microsoft.VisualBasic dll/reference/namespace, but that doesn't work either. Tried to google the C#-equivalent, but couldn't find anything.

A:
The next piece of VB.NET is the catch portion of the try-catch
  clauses.
My.Application.Log.WriteException(ex, TraceEventType.Error, "Could not
  write record to data file " + _strActiveFileName + Environment.NewLine
  + "Record Data: " + strRecordText);
And for the life of me, cannot find the C#-equivalent for this.

This can be converted by (with reference to Microsoft.VisualBasic.dll):
 Microsoft.VisualBasic.ApplicationServices.ApplicationBase MyApplication = new Microsoft.VisualBasic.ApplicationServices.ApplicationBase();

then :
 MyApplication.Log.WriteException(ex, TraceEventType.Error, "ExportDataToolStripMenuItem_Click");

And you can check the log file with  :
System.Windows.Forms.MessageBox.Show(MyApplication.Log.DefaultFileLogWriter.FullLogFileName);

(just tested on Windows 10)


text:
Q: opencart email not working I'm using OPENCART and mail has suddenly stopped working all over the site
Has goddadys server settings changed again for email? no matter what settings I use SSL/Mail no emails coming through
not working on anything, registration, lost password, with admin
tried mail
mail.mysite.com
------------------
smtp
ssl://mysite.com
username
password
post 465

etc
nothing is working

Email to required is back on line 61 mail.php
EHLO error is back if you try SSL
  2016-10-05 6:54:12 - PHP Notice:  Error: EHLO not accepted from server! in /public_html/system/library/mail.php on line 201
without SSL
  2016-10-04 16:43:31 - PHP Notice:  Error: E-Mail to required! in /public_html/system/library/mail.php on line 60

No code has changed on the site... help please

A: fixed it.... catalog/model/account/customer.php
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($this->config->get('config_name'),ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode($this->language->get('text_new_customer'), ENT_QUOTES, 'UTF-8'));

and I may be wrong but think this should be
$mail->setTo($this->config->get('email'));


text:
Q: jQuery/Javascript: set border of iframe from inside iframe I have an iframe and I want to set it's border to zero.
But I want to do this from inside the iframe, using javascript or jQuery.
How to do this? Many thanks in advance,

A: You can do it by $(parent.document).find('#myIframe').css('border', 'xxxx'); - But as pointed out by the comment above, both the pages (main one as well as the one shown in the iframe) should be in the same domain - otherwise you'll end up with a security exception because of same origin policy.

A: If the parent is on a different origin, you can't do it, because access to the parent's content is forbidden by the Same Origin Policy.
If the parent document is on the same origin, this should do it:
(function() {
  var frames = window.parent.document.getElementsByTagName("iframe"),
      index,
      frame;

  for (index = 0; index < frames.length; ++index) {
    frame = frames[index];
    if (frame.contentWindow == window) {
      frame.frameBorder = "none";
    }
  }
})();

Live example | source of parent | source of frame
Note that it's important to use == rather than === when comparing the window properties (unusually, window is special).

A: Alternatively you can use parent.$
parent.$("iframe").prop("frameborder", 0); // This will change all iframes
parent.$("#IframeID").prop("frameborder", 0); // This will change single iframe


text:
Q: Method to return an array In my android project, I have a countdown that randomizes a boolean for an array. The problem is, every time it ticks it always creates the array and the for loop. Can someone help me how to import my codes on a seperate class and method? I just want to call the returned value of an array in my countdown while it loops on a separate class. Please help me, TIA! :)
This is my countdown inside my onCreate():
new CountDownTimer(300000, 1000) {
  public void onTick(long msUntilFinished) {
    txtCounter.setText("" + msUntilFinished/1000);
    ImageView[] pic= {img1, img2, img3, img4, img5};
    Random aRandom = new Random();

    for (int i=0;i<12;i++){
      arrays[i] = aRandom.nextBoolean();

      if(arrays[i]){
        pic[i].setImageResource(R.drawable.show);
        appear = true;
      } else {
        pic[i].setImageResource(R.drawable.hide);
        appear = false;
      }
    }
  } // end of onTick

  public void onFinish() {
    txtCounter.setText("done!");
  }
}.start();

A: If you don't want the array to be created each time it ticks just place the array initialization outside of the thread like this:
for (int i=0;i<12;i++){ arrays[i] = aRandom.nextBoolean();}
new CountDownTimer(300000, 1000)
{
...
}.start();

Important: "arrays" has to be final. If you cannot do this then you have to do:
for (int i=0;i<12;i++){ arrays[i] = aRandom.nextBoolean();}
final SomeClass[] finalArray = arrays;
new CountDownTimer(300000, 1000)
{
...
 if(finalArray[i]) ...
...
}.start();


text:
Q: Улучшить скорость работы программы С++ #include <iostream>

using namespace std;

int sum_of_dil(int n)
{
    int sum = 0;
    if (n%2==0)
    {
        for(int i=1;i<=n/2;++i)
            if (n%i ==0) sum += i;
    }
    else
    {
        for(int i=1;i<=n/2;i+=2)
            if (n%i ==0) sum += i;
    }

    return sum;
}

int main()
{
    int a, b;

    int count = 0;
    cin >> a >> b;

    for(int i=a;i<=b;++i)
    {
        for(int j=i+1;j<=b;++j)
        {
            if (sum_of_dil(i) == j && sum_of_dil(j) == i)
            {
                cout << i << " " << j << endl;
                count++;
            }
        }
    }

    if (count ==0) cout << "Absent" << endl;
    return 0;
}

Задача отсюда -> Тык

Два различных натуральных числа называются дружественными, если первое
  из них равна сумме делителей второго числа, за исключением самого
  второго числа, а второе равно сумме делителей первого числа, за
  исключением самого первого числа. Нужно найти все пары дружественных
  чисел, оба из которых принадлежат промежутку от M до N.

Не проходит по времени.

A: Просвистело за 2мс: :)
#include <iostream>
#include <iomanip>

using namespace std;

struct Frd
{
    int a, b;
} f[] =
{
    { 220,284 },
    { 1184,1210 },
    { 2620,2924 },
    { 5020,5564 },
    { 6232,6368 },
    { 10744,10856 },
    { 12285,14595 },
    { 17296,18416 },
    { 63020,76084 },
    { 66928,66992 },
    { 67095,71145 },
    { 69615,87633 },
    { 79750,88730 },
    { 100485,124155 },
    { 122265,139815 },
    { 122368,123152 },
    { 141664,153176 },
    { 142310,168730 },
    { 171856,176336 },
    { 176272,180848 },
    { 185368,203432 },
    { 196724,202444 },
    { 280540,365084 },
    { 308620,389924 },
    { 319550,430402 },
    { 356408,399592 },
    { 437456,455344 },
    { 469028,486178 },
    { 503056,514736 },
    { 522405,525915 },
    { 600392,669688 },
    { 609928,686072 },
    { 624184,691256 },
    { 635624,712216 },
    { 643336,652664 },
    { 667964,783556 },
    { 726104,796696 },
    { 802725,863835 },
    { 879712,901424 },
    { 898216,980984 }
};

int main(int argc, const char * argv[])
{
    int M, N;
    cin >> M >> N;
    int count = 0;
    for(unsigned int i = M>>15; i < sizeof(f)/sizeof(f[0]); ++i)
    {
        Frd x = f[i];
        if (x.a >= M && x.b <= N)
        {
            ++count;
            cout << x.a << " " << x.b << endl;
        };
    }
    if (count == 0) cout << "Absent\n";
}

A: int sum=1, i;

for (i=3; i*i<n; ++i)
  if (!(n % i))
    sum += i + n/i;

if (!(n % i))
  sum += i;


text:
Q: OAuth 2.0, how to properly handle browser back button that navigates to an exchange endpoint? I am implementing OAuth 2.0 protocol within my MVC application. Everything seem to working as expected except for one thing.
How do I handle a scenario with a browser back button when user is been redirected to their application after exchange end point has been completed? Problem is that browser caches state and code parameter and obviously code has already been exchanged.
I can always but some guard code to see if exception is thrown to send user back into original sign in flow that will redirect them to the default pages since there will be already SSO session. Not sure if this is a proper solution.
For information I am using Identity Server and mix of react, angular, mvc applications.

A: After doing more research I discovered that you can use 303 instead of 302 status code, in that case browsers should not not cache the first redirect per specification.
However based on the note in 302 section, most modern browsers implement 302 as if was 303 redirect and not caching the response.
The solution was, I started adding cache control header with no-cache value to my 302 redirects and browser does not take me back to the previous redirects.
Here is the documentation I took this from: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
I used 302 instead of 303 because I have multiple redirects and documentation states that in 303 first redirect should not be cached meaning all the other it will ignore.


text:
Q: How to insert postgresql data with single quotes - Ask it again @a_horse_with_no_name -
Before you close it again !
I know this post - but it does not solve !
Insert text with single quotes in PostgreSQL (7 answers)

I want to insert text with singles quotes into Postgresql 12 database.
repmondb=# insert into TEST ("vorname#") values ('\'hans\'');
ungültige Anweisung \'');
Versuchen Sie \? für Hilfe.

or
repmondb-# insert into TEST ("vorname#") values (''hans'');
ERROR:  syntax error at or near "hans"
ZEILE 1: insert into TEST ("vorname#") values ('\'hans

The escaping with \ and with extra ' does not work.

A: Double quotes:
insert into TEST ("vorname#") values ('''hans''');

Dollar quoted string:
insert into TEST ("vorname#") values ($$'hans'$$);

db<>fiddle demo


text:
Q: Dapper returns different column name I'm using Dapper to make a select in the database and the return shows the name of the columns differently.
Does anyone know why this occurs?
Image below, left(JSON returns from API), right(SQL Server Table)
JSON result:

C# code:
Controller Method
IEnumerable<Romaneio> romaneios;
string query = "SELECT * FROM TB_ROMANEIOS";
romaneios = await connection.QueryAsync<Romaneio>(query)

The Class used by Dapper
public class Romaneio
{
    public string ROMANEIO_ID { get; set; }
    public string PRODUTO_ID { get; set; }
    public string DESCRICAO { get; set; }
    public string QTD_PALLET { get; set; }
    public string QTD_CX { get; set; }
    public string QTD_TOTAL { get; set; }
    public string QTD_CX_PL { get; set; }
    public string QTD_UN_CX { get; set; }
    public int STATUS_ROMANEIO { get; set; }
    public DateTime DATA_ROMANEIO { get; set; }
}

A: Could you post the CLR object you're asking Dapper to map to?
Does using ADO.NET directly yield the same result?
For example:
using(var conn = new SqlConnection("your connection string")
{
   await conn.OpenAsync();

   using(var cmd = new SqlCommand("select * from TB_ROMANEIS", conn)
   using(var rd = await cmd.ExecuteReaderAsync())
   {
       while(await rd.ReadAsync()){
          var test = rd.GetValue(rd.GetOrdinal("STATUS_ROMANEIO"));
          //what does test == here?
       }
   }
}

It's also worth asking, because I think we've all made this mistake at some point. But are you absolutely sure the database shown in the picture is the one you're querying?

A: I had the same problem and I solved it by rewriting the attributes name, in your class you're using like this: ROMANEIO_ID. Try rewrite to romaneio_id.


text:
Q: Statistical terminology for the "difficulty" of an estimation task I am looking for the proper statistical terminology to express the fact that one estimation task maybe intrinsically harder to solve than another task. Intuitively, I would characterize this property by the discriminative performance that can be achieved by an optimal classifier trained on infinitely many training data points, and evaluated on an infinitely large hold-out test dataset. In other words: how good can a classifier possibly get on this task?
See, e.g., the following very simple example, in which blue and red are two groups and crosses and circles the two outcomes. The gray line shows the optimal decision threshold for both groups, but model performance will be higher in the blue group compared to the red group.

Does this property of the estimation task have a name? (Notice that I am not interested in a property of a particular estimator (e.g., sharpness) - instead, I am looking for something that characterizes a property of the estimation task.)
Candidates I considered:

*

*Aleatoric uncertainty, i.e., one could say that aleatoric uncertainty is higher in one task. This is, however, not what I want to say, because it implies a judgement that it is impossible to get a better separable estimation problem, by, say choosing another measurement.

*Intrinsic or inherent uncertainty is a term, e.g., in Brier score decompositions. However, this term purely depends on the base rate and is fully independent of how well positive and negative classes can be separated.

*Separability sounds like a term that means what I want, but the standard definition seems to be as a binary property, i.e., it only captures the extreme case of the classes being fully separable.

*Input noise, label noise, etc. are possible causes of the property I am interested in.

Is there a technical term for this property of an estimation problem? How would you phrase the fact that one task is "more difficult" than another task?

A: After some more investigation (prompted by Richard Hardy's addition of the "forecastability" tag, thanks!), I believe one way to phrase this precisely would be that the statistical dependence / mutual information between inputs and outputs is higher in one group compared to the other.


text:
Q: Drawing a subimage of drawings in MonoGame So I understand that the title may be a bit vague, so I'll try to explain what I mean.
Basically what I'm trying to accomplish is to draw lots of different objects and images, but in a sort of buffer, so that I can then later on use the drawing function to only draw a part of this buffer.
I am trying to make a Scrolling functionality in MonoGame, much like the Horizontal/Vertical slider control in WinForms, and I got a slider working. What I want is for the slider to accurately cut off other controls inside this slider window.
Now I understand that what I'm trying to accomplish is what RenderTarget2D is there for, and while I've tried working with it, I find it extremely difficult to make it do what i want. My main problem right now is that when I draw something in the RenderTarget, it clears everything else once I set the SetRenderTarget(null) (so that I draw on the game window once more).
Long story short, the following code draws everything AFTER I've performed the RenderTarget2D code, but clears everything prior to it.
protected override void Draw(GameTime gameTime)
{
    _spriteBatch.Begin();
    _spriteBatch.DrawString(font, "Prior", Vector2.Zero, Color.White);
    _spriteBatch.End();

    RenderTarget2D target = new RenderTarget2D(GraphicsDevice, 320, 110, false, SurfaceFormat.Color, DepthFormat.None, 0, RenderTargetUsage.PreserveContents);
    GraphicsDevice.SetRenderTarget(target);

    _spriteBatch.Begin();
    _spriteBatch.DrawString(font, "Middle", new Vector2(0, 120), Color.White);
    _spriteBatch.End();

    GraphicsDevice.SetRenderTarget(null);

    _spriteBatch.Begin();
    _spriteBatch.Draw(target, new Vector2(0, 120), Color.White);
    _spriteBatch.DrawString(font, "Past", new Vector2(0, 240), Color.White);
    _spriteBatch.End();

    base.Draw(gameTime);
}

Also, I have these:
public Game1()
    : base()
{
    _graphics = new GraphicsDeviceManager(this);
    _graphics.PreparingDeviceSettings += OnPreparingDeviceSettings;

    Content.RootDirectory = "Content";
}

private void OnPreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
{
    e.GraphicsDeviceInformation.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;
}

I can't imagine how the last bit matters, but I figured I might as well add a little too much rather a little too little.
Right, so if anyone has any idea of what might be wrong, I'd really like to know, cause now I've been looking at this code and trying to make head and tail of it for about 5 hours or so, and I seem to have made no progress at all.
Thanks

A: So as it turns out, I figured out a replacement for the buffer, which works in my particular case.
I use the GraphicsDevice.ScissorRectangle to make it draw on particular rectangles, which suited my need, seeing as I wanted to accomplish a sort of Slider container control.
More info: MSDN - GraphicsDevice.ScissorRectangle Property
Thanks


text:
Q: iTunes Music Store Link Maker — how to search from within my app? I'm writing a music reference app and for each album (pulled from last.fm) would like to link to the ITMS (if the album is in the store).
iTunes link maker web tool http://apple.com/itunes/linkmaker/ is great for getting links for a known album but I need to access it programatically from within my app.
This NSLog blogpost which is from 2003 but was referenced more recently in another question here seems to offer the only solution I've come across so far, suggesting to submit a query to:

phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults?
Put "itms://" before it and the link will work in iTunes, put "http://" before it and the link will work in Camino (Safari sometimes spits back a malformed XML error).
The tags that are of importance are as follows:

*

*songTerm - song title

*artistTerm - artist name

*albumTerm - album name

*composerTerm - composer name

*term - all fields

The suggestion is that would using http:// rather than itms:// the server will return an XML document of results instead of opening iTunes but either way I am sent directly to iTunes.
Is it possible to get back a list of results?

A: I am using LinkMaker to get iTunes details about song I am playing.
For that, I found that LinkMaker is able to return json data and also 1 result at a time.
I am using this url to perfom my query :

http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/itmsSearch?lang=1&output=json&country=%@&term=%@&media=%@&limit=1"

Here are parameters you need to give :
> country : store country term : could
> contains artist name, song name, album
> media : music

For exemple, if you want to have details for a song called "One" by "U2" here is the correct URL :
http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/itmsSearch?lang=1&output=json&country=US&term=U2%20one&media=music&limit=1
Then you will receive json data like this :
{
 "resultCount":1,
 "results": [
{"wrapperType":"track", "mediaType":"song", "artistName":"U2", "itemParentName":"Achtung Baby", "itemParentCensoredName":"Achtung Baby", "itemCensoredName":"One", "itemName":"One", "artistLinkUrl":"http://itunes.apple.com/us/artist/u2/id78500?uo=4", "artworkUrl60":"http://a1.phobos.apple.com/us/r1000/009/Features/32/9a/60/dj.mfynlttx.60x60-50.jpg", "artworkUrl100":"http://a1.phobos.apple.com/us/r1000/009/Features/32/9a/60/dj.mfynlttx.100x100-75.jpg", "country":"USA", "currency":"USD", "discCount":1, "discNumber":1, "itemExplicitness":"notExplicit", "itemLinkUrl":"http://itunes.apple.com/us/album/one/id368713?i=368617&uo=4", "itemPrice":"1.29000", "itemParentExplicitness":"notExplicit", "itemParentLinkUrl":"http://itunes.apple.com/us/album/one/id368713?i=368617&uo=4", "itemParentPrice":"9.99000", "previewUrl":"http://a1.phobos.apple.com/us/r1000/019/Music/b6/8c/c5/mzm.epegonxg.aac.p.m4a", "primaryGenreName":"Rock", "trackCount":12, "trackNumber":3, "trackTime":276042}]
}

You need then to decode these JSON data.
NSDictionary *jsonResultsParsed = [jsonResults JSONValue];

And finally get what you want :
NSDictionary *songDetailsDict = [[jsonResultsParsed objectForKey:@"results"] objectAtIndex:0];

If you want to determine user's country you will need to determine its country using its locale, here is the code I am using :
- (NSString *)getUserCountry
{
    NSLocale *locale = [NSLocale currentLocale];
    return [locale objectForKey: NSLocaleCountryCode];
}

Hope this helps.
Thierry
Edit: Finally a doc is available:
http://www.apple.com/itunes/affiliates/resources/documentation/itunes-store-web-service-search-api.html

A: This document for iTunes Store Web Service Search API (pdf), although old and incomplete, seems to be the way to accomplish this.
It's a painful experience setting this up though, as has been every other part of the affiliate programme.


text:
Q: Fresco image not visible in Recyler View on Android Jellybean devices While loading image a thin line appears and the image is not visible while using fresco in a RecyclerView on Android Jellybean devices but the same works on KitKat+ devices.

Samsung - 4.1.1 - API 16 - 768 X 1280

SamsungGalaxyNote2 - 4.3 - API 18 - 720 X 1280

NOTE : Have tested in multiple devices and the scenario is the same

This is the way we are using it in the library
            if (newsModelStoreList.get(position-1).getImageUrl() != null) {
            String imageUrl = newsModelStoreList.get(position-1).getImageUrl();
            String extension=".jpg";
            try {
                extension = imageUrl.substring(imageUrl.lastIndexOf("."));
            }
            catch (Exception e)
            {

            }

            Log.d("extension: ",extension);
            if(extension.equals(".gif")) {
                Log.d("Detected Gif: ", "Starting gif controller");
                DraweeController controller = Fresco.newDraweeControllerBuilder()
                        .setUri(Uri.parse(imageUrl))
                        .setAutoPlayAnimations(true)
                .build();
                myHolder.newsImage.setController(controller);

            }
            else
            {
                myHolder.newsImage.setImageURI(Uri.parse(imageUrl));
            }

        }

I AM 100% SURE THAT URL IS AVAILABLE AND IS WORKING ON 4.4+ DEVICES

This is the news_layout.xml which gets inflated
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/feed_bg"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/bg_parent_rounded_corner"
        android:layout_marginTop="@dimen/feed_item_margin"
        android:orientation="vertical"
        android:paddingBottom="@dimen/feed_item_padding_top_bottom"
        android:paddingTop="@dimen/feed_item_padding_top_bottom" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:gravity="right"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/timestamp"
                android:gravity="right"
                android:paddingRight="10dp"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="posted 5 min ago"
                android:textColor="@color/timestamp"
                android:textSize="@dimen/feed_item_timestamp" />

        </LinearLayout>

        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/newsTitle"
            android:textSize="22dp"
            android:clickable="false"
            android:textStyle="bold"
            android:paddingLeft="@dimen/feed_item_status_pad_left_right"
            android:paddingRight="@dimen/feed_item_status_pad_left_right"
            android:textColor="@color/black"
            android:textColorLink="@color/com_facebook_blue"
            android:layout_marginBottom="5dp"
            android:paddingBottom="5dp"
            />

       <TextView
            android:id="@+id/newsInformation"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="5dp"

            android:textColor="@color/black"
            android:textColorLink="@color/com_facebook_blue"
            android:paddingLeft="@dimen/feed_item_status_pad_left_right"
            android:paddingRight="@dimen/feed_item_status_pad_left_right"
            android:paddingTop="@dimen/feed_item_status_pad_top" >

           </TextView>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/viewMore" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_gravity="right"
            android:layout_height="wrap_content">

        </LinearLayout>

SimpleDraweeView is used here ...

        <com.facebook.drawee.view.SimpleDraweeView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="fitXY"
            android:visibility="visible"
            android:adjustViewBounds="true"
            android:id="@+id/newsImage"/>

The rest of the xml is just for reference just in case it would help

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/pad_5dp">

            <TextView
                android:id="@+id/awesomeness"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="@color/timestamp"
                android:text="Awesomeness: "
                android:textSize="@dimen/feed_item_timestamp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/awesomenessCountNumber"
                android:text="0"
                android:textColor="@color/timestamp"
                android:textSize="@dimen/feed_item_timestamp"/>

        </LinearLayout>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:paddingTop="@dimen/pad_5dp"
            android:layout_marginLeft="@dimen/pad_5dp"
            android:layout_marginRight="@dimen/pad_5dp">

            <Button
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:id="@+id/awesomeButton"
                android:layout_marginRight="8dp"
                android:background="@drawable/awesome_button_2"/>

            <Button
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:id="@+id/facebookSharePost"
                android:layout_marginRight="8dp"
                android:background="@drawable/facebook_icon"
                />

            <Button
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:id="@+id/whatsApp"
                android:background="@drawable/whats_app_icon"/>

            <View
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_weight="1"
                />

            <TextView
                android:layout_marginRight="8dp"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Report"/>

            <Button
                android:layout_marginRight="6dp"
                android:layout_width="30dp"
                android:layout_height="30dp"
                android:id="@+id/report"
                android:background="@drawable/report_empty" />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>

A: Guesses as to what you are doing wrong:

*

*You are using wrap_content. Fresco does not support this unless you also supply a fresco:viewAspectRatio. See the guide to Drawees and the longer explanation about wrap_content.

*You are using android:scaleType. This has no effect on SimpleDraweeViews. You need to use fresco:actualImageScaleType. Also be sure that fitXY is really what you want; this does not preserve the aspect ratio. See the documentation on scale types.


text:
Q: Can JavaFX ComboBox fire events when selection not changed? I'm new to JavaFX. Unlike Swing, JavaFX's combo box's action event seems to be fired when the selection actually changed. In Swing, you can add an ActionListener on a JComboBox and it will fire an event whenever you make a selction (by clicking on one of the choices in the combo box), regardless of if the selected value actually changed. Can we achieve the same behavior in JavaFX? Some code below. What I want is to select "Hello" and have it printed, and select "Hello" again and have it printed again.
public class ComboBoxSelection extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        VBox layout = new VBox();
        ComboBox<String> comboBox = new ComboBox<>();
        comboBox.getItems().addAll("Hello", "World");
        comboBox.setOnAction(event -> System.out.println("Selected " + comboBox.getValue()));
        layout.getChildren().addAll(comboBox);

        Scene scene = new Scene(layout);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

I noticed a thread here: ComboBox SAME item selected action listener. This almost gives me what I want, except this fires when the selection cancels (press Esc) as well. Is there any other solution? Thanks in advance.


text:
Q: How css grid computes row auto height? In the below snippet, I can not understand how .cell1(orange) height has been computed. Why it is so high? Why it is higher than right column content? How left cells height depends on right column and it's contains height?

header {
  display: grid;
  grid-template-columns: 70% 30%;
  grid-template-rows: 62px auto;
  background: beige;
}

.cell1 {
  grid-column: 1/2;
  grid-row: 1/2;
  background: salmon;
}

.cell2 {
  grid-column: 1/2;
  grid-row: 2/3;
  background: MediumSpringGreen;
}

.cell3 {
  grid-row: 1/3;
  grid-column: 2/3;
  background: PeachPuff;
}

.cell3-1 {
  background: MediumPurple;
  height: 5px;
}

.cell3-2 {
  background: LightSkyBlue;
  height: 10px;
}

.cell3-3 {
  background: Navy;
  height: 30px;
}

1

2

A: Let's start with your title.

How css grid computes row auto height?

auto just means it adapts to the height of the content within it. If the content in an auto row, is 100px tall, the row will be 100px tall.

I can not understand how .cell1(orange) height has been computed. Why it is so high?

Because you have told the first row to be 62px tall here:
  grid-template-rows: 62px auto;

Why it is higher than right column content?

It isn't...but I can see that you might think that.

How left cells height depends on right column and it's contains height?

The right content in the context of the grid is only the .cell-3 div but you have told div to span 2 rows. So it assumes the combined height of .cell- and .cell-2.
The content inside cell-3 does not inherit any of the grid properties and so flows as normal.


text:
Q: Perform onload() in ionic I want to load a function when a page loads.So how to use native javascript onload function in ionic.Here is sample html page.
<ion-view title="Account" >
  <ion-content class="has-header padding">

Account

    <button id="bt">test</button>

  </ion-content>
</ion-view>

here is my javascript file
function testload(){

  alert("page loaded");
 }

I want to load the this when page is loaded.How it possible in ionicframework?

A: What about using the controller associated with that view?
.controller('YourCtrl', function($scope, $stateParams, Something) {
    alert("page loaded");
})

A: Please give this a try.
$ionicView.enter

$ionicView.loaded

http://ionicframework.com/docs/api/directive/ionView/

A: do you mean on page load, or on view loaded?
pageload is simple, you could do a

A: probably you should check out $ionicPlatform
if you want to execute some function upon device ready
$ionicPlatform.ready([callback])

Or just a page load...in your controller, inject $scope and listen to $ionicView.loaded
app.controller('controller', function($scope) {
  $scope.$on('$ionicView.loaded', function(event) {
  });
});


text:
Q: Replace inner double quotes in a string in an array I have strings in an array:
["foo","bar","foo"bar"baz"]

I am using eval method to form an array with this string, but the inner double quotes are not escaped:
eval('["foo","bar","foo"bar"baz"]') # => SyntaxError

Is there a way to escape only the ones inside an array element?

A: I think you can try something like
eval('["foo","bar","foo"bar"baz"]'.gsub(/(\w)\"(\w)/, '\1\"\2'))

if I got what you have meant

A: This might work for all possible variants. This would fix all quotes except of appearing near commas and brackets
.gsub(/(?<!\,)(?<!\[)(?<!\])\"(?!\,)(?!\[)(?!\])/, '\"')


text:
Q: Nonlinear Differential Equation with Log How would one go about solving a higher order ODE that is non linear that is equal to a natural log? Is the Undetermined Coefficients method possible or must Variation of Parameters be used? For example, this:
$$y''=ln(y)$$
Thanks so much!

A: Try this
$w = \frac{dy}{dx} = \frac{dy}{dw}\frac{dw}{dx} = \frac{dy}{dw} y''$
$y'' = w \frac{dw}{dy}$
$w \frac{dw}{dy} = \ln(y)$
Solve this diff eq.,  then substitute back again for w. And, solve the next diff eq.


text:
Q: Calculus 2: Integration by Parts Stuck on Integral of Product With ArcTan Inside I'm stuck on the following problem:
$$\int_0^{1/3} y \tan^{-1}(3y)\,dy$$
I think my last line in my work below is correct but I don't know what to do beyond that.
A step through of the problem would be appreciated.

A: Let $x = 3y$ then  $ 3dy = dx $,
$$\displaystyle \int_0 ^{\frac {1}{3}} y \ \tan^{-1}(3y) dy = \frac {1}{9} \int_0 ^1 x\ \tan^{-1}(x) dx$$
Use ILATE
$\displaystyle \Rightarrow  \frac {1}{18} [x^2 \tan^{-1}(x) |_0 ^1  - \int_0 ^1 \frac {x^2}{1+x^2} dx ]   $
$\displaystyle \Rightarrow  \frac {1}{18} [x^2 \tan^{-1}(x) |_0 ^1  - \int_0 ^1 \frac {x^2}{1+ x^2} dx ]   $
$\displaystyle \Rightarrow  \frac {1}{18} [x^2 \tan^{-1}(x) |_0 ^1  - ( \int_0 ^1 dx - \int_0 ^1  \frac {1}{1+ x^2} dx )] $
$\displaystyle \Rightarrow  \frac {1}{18} [x^2 \tan^{-1}(x) - x + \tan^{-1}(x) ]_0 ^1   $
$\displaystyle \Rightarrow  \frac {1}{18} [(x^2 + 1) \tan^{-1}(x) - x  ]_0 ^1
 = \frac {\pi}{36} - \frac {1}{18}$
Please tell if there are errors in this, because I haven't studied calculus yet.

A: Integrate by parts $\left(f = \tan^{-1}3y, g' = y \Rightarrow f' = \frac{3}{9y^2 + 1}, g = \frac{y^2}{2}\right)$:
$$\int y \tan^{-1}(3y) dy$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \int \frac{3y^2}{2(9y^2 + 1)} dy$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{3}{2} \int \frac{y^2}{9y^2 + 1} dy$$
Write $y^2$ as $\frac{1}{9}(9y^2+1) - \frac{1}{9}$ then we get:
$$\frac{y^2 \tan^{-1}(3y)}{2} - \frac{3}{2} \int \frac{\frac{1}{9}(9y^2+1) - \frac{1}{9}}{9y^2 + 1} dy$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{3}{2} \int \frac{\frac{1}{9}(9y^2+1)}{9y^2 + 1} - \frac{\frac{1}{9}}{9y^2 + 1}dy$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{3}{2} \int \frac{1}{9} - \frac{1}{9} \frac{1}{9y^2 + 1}dy$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{1}{6} \int 1 - \frac{1}{9y^2 + 1}dy$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{1}{6} \left(\int 1\,dy - \int \frac{1}{9y^2 + 1}dy\right)$$
Using substitution $u=3y$, we get:
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{1}{6} \left(\int 1\,dy - \frac{1}{3} \int \frac{1}{u^2 + 1}du\right)$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{1}{6} \left(y - \frac{1}{3} \tan^{-1}u + C\right)$$
$$= \frac{y^2 \tan^{-1}(3y)}{2} - \frac{1}{6} y + \frac{1}{18} \tan^{-1}3y + C$$
$$= \frac{(9y^2 + 1) \tan^{-1}(3y) - 3y}{18} + C$$
Now you can evaluate the integral:
$$\int_{0}^{\frac{1}{3}} y \tan^{-1}(3y) \, dy = \frac{\pi - 2}{36}$$

A: Intrgrate by parts taking $y$ as first function:
$$I=\int_{0}^{1/3} y \tan^{-1}(3y) ~dy=\tan^{-1}(3y) (y^2/2)|_{0}^{1/3}-\int_{0}^{1/3} \frac{3}{1+9y^2} \frac{y^2}{2} dy=\frac{\pi}{72}--\frac{1}{18}+\frac{1}{6} \int_{0}^{1/3} \frac{dy}{1+9y^2}= \frac{\pi}{72}-\frac{1}{18}+\frac{\pi}{72}$$
$$\implies I=\frac{\pi}{36}-\frac{1}{18}$$


text:
Q: Is it possible to create an iframe-based payment method in Magento? To give a context for my question, we are actually migrating to Magento from Interspire Shopping Cart. In Interspire, the payment form would be displayed after everything else, especially the Order Review/Summary. At this last step of the checkout, we just display an iframe, which displays a payment form hosted on our payment gateway's server (since we're not PCI compliant). In Magento, however, the last part isn't the payment form, but the Order Review.
So my question is, would it be possible at all to create a payment method that uses an iframe (instead of redirecting to a payment page after "Place Order" is clicked)? This iframe would display the payment form hosted on our payment gateway's server.
I ask this because based on what I've read, and after playing with my code, it seems that it is not possible in Magento. Displaying this iframe, for example, on Step 4 (Payment Information) would mean that when the form is filled out and submitted by the user, the page would redirect to a success page, thereby bypassing Step 5 (Order Review). And even this won't work because it is actually in Step 5 (after Place Order is clicked) where the success page is even defined. So after submitting the payment form (in an iframe) in Step 4, it wouldn't know what to do next.
I also tried to research how to put this iframe in Step 5 instead of Step 4, having it appear after "Place Order" is clicked, but couldn't find anything.
So, is it possible to create an iframe-based payment method in Magento? If so could you point me to some resources, because I've googled a lot and haven't found anything useful.

A: Good news:
This is actually already available. It's called Magento Payment Bridge which integrates an iFrame into the payment process so that the payment doesn't take place on your own server.
Here is some more information about Payment Bridge:
http://www.magentocommerce.com/company/pci-compliance
http://www.magentocommerce.com/images/uploads/Magento_Secure_Payment_Bridge.pdf
Bad news:
It's not available standalone. It used to be available via Magento Professional, which was a smaller version of Magento Enterprise (limited features, less cost, no online support). Now it seems it is exclusively an Enterprise feature.
If you're not in the market for EE, you're probably left to roll your own. Some payment providers do this already:

*

*Paypal Payments Advanced

*Authorize Server Integrated Payments (hosted payments)

Other options
Look into some of the newer companies that are doing payments like Stripe. Stripe has an amazing payments API that is dead-simple and will not require iframing. They even have a javascript include API.
Other competitors of Stripe include Authorize.net (who have a Javacript API now) and Braintree.

A: Magento CE 1.7 has this out of the box. It's the payment method labeled "Authorize.net Direct Post" in the admin, and is an alternate form of integrating with Authorize.net which I believe was introduced in 1.7.
Essentially, the way it works is as you describe, and the payment information is posted directly to the gateway server, in this case the Authorize.net gateway. Authorize.net provides a little diagram showing how this integration method works…

The AIM integration with Authorize.net, and the one you are likely looking at, actually still does not store the card information on your server, even though it is accepted prior to the review step. Given a stock installation, i.e. it is unmodified, the card info is submitted to the server over HTTPS (I'm assuming an SSL has been configured) in order to be validated, but it is not stored there. When the customer clicks the final place order button, that same card info in the payment form is submitted all over again so that Magento has it to process the payment transaction. So essentially, it does get sent to the server (over an SSL secured connection, again, assuming it's been setup with SSL) but is not held or stored beyond the time it takes to authorize the transaction with the payment gateway. It can be confusing since it's not immediately obvious that it is done this way, and it didn't do it this way in older versions of Magento.
As @philwinkle points out, Magento EE has the Payment Bridge, but that still requires that you run on a fully compliant environment since the bridge is merely taking the responsibility of payments off of the application nodes and putting it on an isolated server, using code which has been PCI-DSS certified. It also enables certain additional payment methods such as authorize.net stored credit cards.
In addition to on-site payment methods, there are also options such as PayPal which can take the customer off-site to process the card via the Payments Standard payment method.

A: If you or your client is in a country which support it, SagePay offer an iframe based payment method – the server-server method.  There is the free approved Sagepay Suite by ebizmarts which really is excellent, well supported and kept up to date.
http://www.magentocommerce.com/magento-connect/ebizmarts-sage-pay-suite-ce-sage-pay-approved.html
You can upgrade to the premium edition for £150. The benefits of that are additional payment methods, in addition to standard 'Authorise and Capture' you also have Defer and Authenticate  And you can also refund directly out of the Magento backend.
Pros

*

*Very secure (arguably more secure than the direct method) as of
course it's essentially an off-site payment method taking place on
your site.  As such you don't technically need an SSL for this as
there is no transport on the credentials, although good practice
would dictate that you apply one anyway given users expect it and
have been trained to look for it. Well some of them have anyway.

Cons

*

*jQuery in the checkout.   As we all know jQuery doesn't play too well
with Prototype at the best of times, this module's js is all written
using Prototype and really doesn't play well with jQuery in
server-server mode.  Ebizmarts recommend having no jQuery at all in
the checkout, and I know from experience that in server-server mode
if there is a conflict it will result in the payment form not being
displayed (everything else seems fine). This happens whether the form
is set in the config to appear under the order review or as a modal
window.
This is a problem as often you'd want to retain things like jQuery
based masthead mini carts in the checkout.

*Styling the form.  The form itself is hosted on the Sagepay server
and for  obvious security reasons they don't allow you to serve up
your own CSS by linking it to external files.  When you are styling
the form you need to use XLST and run it through Saxon/Kernow
(http://kernowforsaxon.sourceforge.net/ ) to process/render it. So
more time consuming to style.
There are guidelines you need to follow, when you are happy with it
you submit a whole zip file of css, images and templates back to
Sagepay who review it and then apply it to your checkout.  Pros here
are that the documentation they provide is very good and they are
very fast at reviewing and approving checkouts which have followed
the guidelines.

A: Time has passed and technology has advanced.
Braintree Payments have gone leaps and bounds in the last few months, both commercially and technologically. They now offer two solutions that offer out-of-the-box PCI compliance. Both are based on iframes.
The first one, their "v.zero drop-in", is the easiest to implement, looks very slick and has great UX, but is less customisable. The second one, "Hosted Fields" takes a little more programming effort, but allows more control in terms of CSS styling and layout.
Luckily, for seamless integration into Magento without you having to do any coding, there are now extensions on Magento Connect to make implementation effortless, see for instance http://www.magentocommerce.com/magento-connect/developer/f+r+i+s
Here's a comparison to help you choose the best one for your store: https://fris.technology/blog/braintree-drop-in-or-hosted-fields
These extensions work in Mage core's multi-step checkout as as well as in combination with almost any one-page/one-step checkout extension on the Magento Marketplace.


text:
Q: Avoid Close Editor when no unsaved changes Eclipse RCP Is there anyway to stop the editor from closing even though there are no unsaved changes?
Whenever there are some unsaved changes, then using the ISaveablePart interface can trap the event before editor close - but I'm looking for a way to trap the event before the editor closes, even if there are no unsaved changes.

A: A possible way to do this is to maintain two 'dirty' flags in your ISaveablePart implementation - one so that the Eclipse saving framework will think your editor is dirty and call your hooks preventing the editor to close.
To avoid Eclipse incorrectly displaying messages about your editor having unsaved changes, you'll probably want to actually implement ISaveablePart2 (docs here) and implement promptToSaveOnClose() - this can check whether the editor is really dirty, and only prompt to save (or whatever else you want) in that case.
You may want to re-examine the underlying reason you want to keep the editor open though - the framework doesn't normally work like this (so issues might creep in), and it seems like it would be a confusing experience to users who really really want to close the editor (and decide your application is buggy).


text:
Q: Converting T-SQL's date functions to MySQL I am trying to convert this MS SQL Server code to MySQL but I am not getting the same date I would get in MS SQL Server. Does anyone know how to change this code to make it work in MySQL? The '2021-08-03 00:00:00' is a timestamp example being used.
SELECT
    FORMAT( DATEADD( DAY, 0, DATEDIFF( DAY, 0, '2021-08-03 00:00:00')), 'd', 'en-us' ) AS 'day'

The MYSQL Code so far.
SELECT FORMAT (adddate(datediff(NOW(), ma.Timestamp), INTERVAL 0 DAY), 'd', 'en-us') AS day,

A: Here's how to present dates in m/d/y format in MySQL:
CREATE TABLE `dates` (d datetime);

INSERT `dates`(d) VALUES('2021-08-31 03:00'),('2021-11-13 05:40');

SELECT DATE_FORMAT(d, '%c/%e/%Y') AS day FROM `dates`;

Results:
day
----------
8/31/2021
11/13/2021

*

*Example db<>fiddle
I knew nothing about this since I can barely spell MySQL, but looking up DATE_FORMAT() took about two minutes.
As an aside, the existing expression you got from your co-workers is both needlessly complex and a real drag on performance due to the FORMAT() function. Try:
DECLARE @d date = '2021-08-03T00:00:00.000';
SELECT CONVERT(char(10), @d, 101);

If you have a datetime already, that's fine, you can still strip time from it without all the dateadd and datediff noise:
DECLARE @d datetime = '2021-08-03T00:00:00.000';
SELECT CONVERT(char(10), @d, 101);

Not that I believe m/d/y is a sensible format in the first place, or that you should go out of your way to remove those leading zeroes...


text:
Q: Maven enforce plugin ignore in tests I have a maven project that has the enforcer plugin enabled for validation phase, but i want to disable the execution of the plugin in test phase, just apply it in no tests.
Why? Because i'm using the DependencyConvergence rules and in i need to add for example jetty server which has his own implementation about servlet-api and it's needed..
Is there any way to handle it?
Thanks in advance


text:
Q: class Not Found Error when I extending my class with java.awt.Frame I can't understand why this error is coming
class Temp extends java.awt.Frame
{
Frame f = new Frame(); // error is coming in this line
// code//
}

I know this is silly one but can't getting reason

A: I don't know why you're creating a Frame if you're extending Frame. But in any case, are you  importing java.awt.* or java.awt.Frame?
jcomeau@intrepid:/tmp$ cat Temp.java; java Temp
import java.awt.*;
class Temp extends java.awt.Frame
{
Frame f = new Frame(); // error is coming in this line
// code//
public static void main(String[] args) {
 System.out.println("this is a " + new Temp());
}
}
this is a Temp[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=,resizable,normal]


text:
Q: ASN.1 sequence with missing tag/length field I'm implementing a specification that, as the outermost data type, specifies a sequence
LogMessage ::= SEQUENCE {
   version INTEGER (4),
   ...
}

When encoded, I would expect the messages to always start with 30, but this is not the case. Indeed what I see when  I look at the messages is that the inner part of the SEQUENCE is encoded, but the outer definition (30 and length field of payload) is omitted.
I cannot find why this is happening (the ASN.1 looks just "normal"). Is there a special mode in which this behavior can be seen? Of course I can "manually" trucate that leading data, but I would like to build a robust solution and if this is somehow defined in ASN.1, I'm sure my library (pyasn1) would have an option to set it.


text:
Q: JBoss RESTEasy Unable to scan WEB-INF for JAX-RS annotations I just added JAX-RS web services to my project in MyEclipse and did my export/deploy to jboss 6/jdk 1.6, but I keep getting this error and I have no clue why it comes up.  Here's the first few lines of this stack trace:
2011-05-03 21:33:46,716 INFO  [org.jboss.resteasy.integration.deployers.ResteasyIntegrationDeployer] (HDScanner) *** Adding JAX-RS resource classes: com.mycompany.CategoriesResource
2011-05-03 21:33:47,180 INFO  [org.jboss.web.tomcat.service.deployers.TomcatDeployment] (HDScanner) deploy, ctxPath=/mypath
2011-05-03 21:33:47,330 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[localhost].[/mypath]] (HDScanner) Exception sending context initialized event to listener instance of class org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap: java.lang.RuntimeException: Unable to scan WEB-INF for JAX-RS annotations, you must manually register your classes/resources

Has anyone had trouble with this before?  The project was created in MyEclipse with Struts and Web Service Capabilities if that helps.  I honestly don't know what else I can try considering I just recently deployed a similar configuration without any problems.
Thanks!
Here is my web.xml
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

        action
        org.apache.struts.action.ActionServlet

            config
            /WEB-INF/struts-config.xml

            debug
            3

            detail
            3

        0

<listener>
    <listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
    <display-name>API</display-name>
    <servlet-name>API</servlet-name>
    <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>API</servlet-name>
    <url-pattern>/api/*</url-pattern>
</servlet-mapping>
<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>true</param-value>
</context-param>
<context-param>
    <param-name>resteasy.servlet.mapping.prefix</param-name>
    <param-value>/api</param-value>
</context-param>
<servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<jsp-config>
    <taglib>
        <taglib-uri>http://struts.apache.org/tags-bean</taglib-uri>
        <taglib-location>/WEB-INF/struts-bean.tld</taglib-location>
    </taglib>
    <taglib>
        <taglib-uri>http://struts.apache.org/tags-html</taglib-uri>
        <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
    </taglib>
    <taglib>
        <taglib-uri>http://struts.apache.org/tags-logic</taglib-uri>
        <taglib-location>/WEB-INF/struts-logic.tld</taglib-location>
    </taglib>
    <taglib>
        <taglib-uri>http://struts.apache.org/tags-tiles</taglib-uri>
        <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
    </taglib>
    <taglib>
        <taglib-uri>http://struts.apache.org/tags-nested</taglib-uri>
        <taglib-location>/WEB-INF/struts-nested.tld</taglib-location>
    </taglib>
</jsp-config>

A: This means that RESTEasy received an IOException when trying to scan the WEB-INF directory. The first thing I would check is your file system permisions - can the user running the JBoss process read WEB-INF and all the files within it?
EDIT:
In response to your comment: Your classpath includes an entry that Scannotation doesn't understand. It looks like jndi://. Can you check the classpath and find out what this entry is?

A: Resteasy should be the victim, too. The problem is at scannotation-1.0.3.jar.
DirectoryIteratorFactory factory = registry.get(url.getProtocol());
if (factory == null) throw new IOException("Unable to scan directory of protocol: " + url.getProtocol());
return factory.create(url, filter);

It seems when the url.getProtocol() returns "jdni", this problem happens. I'm still investigating what url will return protocol as jndi.
I deleted the scannotation-1.0.3.jar from my lib folder, and downloaded the source code, printed the bad url. It turned out to be: jndi:/localhost/Enoch2/WEB-INF/lib/.svn/
Then I tried to remove all .svn folders from the deployment. It works.

find . -name .svn | xargs rm -Rf

A: I faced the same issue when I moved my maven project from java 6 to java 8. The cause was some dependancy in my project was holding on to javassit 3.12 and it was not compatible with java 8. After I upgraded javassist to 3.20 it started working fine.
So if you face this issue please check the javassist jar used and upgrade if needed.

A: I have faced this issue recently.
javassist version was not supported with Java 8 changes. So I have excluded this jar from that dependency and added externally javassist dependency(with higer version).
LOG:
SEVERE: Exception sending context initialized event to listener instance of class [org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap]

java.lang.RuntimeException: Unable to scan WEB-INF for JAX-RS annotations, you must manually register your classes/resources

    at org.jboss.resteasy.plugins.server.servlet.ConfigurationBootstrap.createDeployment(ConfigurationBootstrap.java:177)

    at org.jboss.resteasy.plugins.server.servlet.ListenerBootstrap.createDeployment(ListenerBootstrap.java:32)

    at org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap.contextInitialized(ResteasyBootstrap.java:27)

My Solution:
Updated my pom.xml file
<dependency>
    <groupId>com.xyz</groupId>
    <artifactId>abc</artifactId>
    <version>${abc.version}</version>
    <exclusions>
        <exclusion>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
        </exclusion>
    </exclusions>
</dependency>

and added dependency
<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.18.2-GA</version>
</dependency>


text:
Q: Dynamic Input Selector Based on Uploaded Data Thanks in advance for your help. I understand how to manipulate dynamic inputs based off of other inputs for pre-defined datasets.
i.e. Load a car dataset. User selects Radio button to say they only want to look at blue cars. This changes the options in some Input Selector on the UI.
However, if I want to allow a user to upload a csv file, how do I dynamically update all of the relevant widgets.
i.e. User uploads their data, an Input Selector displays all variables in the dataset for plots and regressions.
The italicized part is my trouble.
ui.r
library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(

  titlePanel("My R Shiny App"),

  sidebarPanel(
    fileInput('file', 'Choose file to upload.'),
    #Select Box: y
    selectInput("y_input", label = h5("Select Time Series/Response Variable"),
                choices = names(myData),
                selected = NULL)

  )
)
)

server.r
library(shiny)

#Run once when app is launched
#Load data

shinyServer(function(input, output) {

  #Run once each time a user visits the app
  #Put code to build a distinct set of reactive objects for user

  output$Variable_Selector <- renderUI({
    if(is.null(input$file))
      return(NULL)
    inFile <- input$file
    myData <- read.csv(inFile$datapath)
    if (is.null(myData))
      return(NULL)
  })
})

global.r
myData = NULL

Thanks!

A: Here's one solution using the functions observe and updateSelectInput - with some other minor modifications to your code. To demonstrate I made the following two csv files with different column names:
Df1 <- data.frame(
  x=1:5,
  y=2*(1:5),
  z=3*(1:5))
##
Df2 <- data.frame(
  a=6:10,
  b=2*(6:10),
  c=3*(6:10),
  d=letters[1:5],
  stringsAsFactors=F)
##
write.csv(Df1,file="~/tempfiles/Df1.csv",row.names=F)
##
write.csv(Df2,file="~/tempfiles/Df2.csv",row.names=F)

ui.R:
library(shiny)

shinyUI(fluidPage(

  titlePanel("My R Shiny App"),

  sidebarPanel(

    fileInput(
      'file',
      'Choose file to upload.'
    ),

    selectInput(
      "y_input",
      label = h5("Select Time Series/Response Variable"),
      ""
    )

  )

))

server.R:
library(shiny)

shinyServer(function(input, output, session) {

  inFile <- reactive({
    if (is.null(input$file)) {
      return(NULL)
    } else {
      input$file
    }
  })

  myData <- reactive({
    if (is.null(inFile())) {
      return(NULL)
    } else {
      read.csv(inFile()$datapath)
    }
  })

  observe({
    updateSelectInput(
      session,
      "y_input",
      choices=names(myData()))

  })

})

global.R:
myData <- NULL

And here are a couple of screenshots showing how the UI changes based on the uploaded file:


text:
Q: array.every() works on only first element I have an array
errorPriority: string[] = ['shippingError', 'paymentInfoError', 'generalError'];

I need a function call to be looped on every element of array, but somehow after executing function for first element 'shippingError', the loop stops. Below is the function call
this.errorPriority.every(this.getErrorData);

And the function that is executed
getErrorData = (value: string): void => {
    if (eval(this.objectPath[value as keyof ObjectPath]) && eval(this.objectPath[value as keyof ObjectPath]).length)
      this.checkoutState.errors[value] = eval(this.objectPath[value as keyof ObjectPath]);
  }

It sometimes, works on array element, but mostly stops after first element, Am I missing something, please help
I expect function should be looped on every array element

A:
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.

Source
this means Array#every() checks if every item in array meets the criteria tested by given function, and that means the given function should return a boolean value. Since your function does return void or in javascript undefined, this will be interpreted as false. And because every returns true only if all elements return a truthy value, the iteration can be aborted after the first falsy value.
to run your code on every item you need to use forEach

A: You are using every function, it will just test if ALL elements of your array successfully pass your function.
So the given function MUST return a boolean (true or false) but you are returning void. try to return "true" if your condition is successfull
getErrorData = (value) => {
    if (eval(this.objectPath[value]) && eval(this.objectPath[value]).length) {
      this.checkoutState.errors[value] = eval(this.objectPath[value]);
      return true;
    }
  }

A: from the MDN documentation the definition of array.every() is

every() method tests whether all elements in the array pass the test
implemented by the provided function. It returns a Boolean value.

so array.every returns a boolean. in your code you don't return anything. if the condition is true, you only assign a new property.
the following should work:

   getErrorData = (value) => {
    if (eval(this.objectPath[value]) && eval(this.objectPath[value]).length) {
      this.checkoutState.errors[value] = eval(this.objectPath[value]);
      return true;
    }
      return false
    }


text:
Q: UWP MediaElement mini player with SystemMediaTransportControls I am trying to implement a toasted audio player when windows is locked. To achieve this i am using Toasted notificationUI. It's working fine but when user has disabled the notification then it doesn't show up.
I saw this https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BackgroundMediaPlayback example of MediaElement to play the audio and show the mini player when user locks the machine.
I can not use UWP's MediaElement to play the audio because i have different proprietary format which can be understand by my own player only.
So is there any way to show the UWP's media element mini player when the screen is lock and handle the button click events without playing actual media with it.
Currently i am using the SystemMediaTransportControls to show the player on volume change.
var systemMediaTransportControls = SystemMediaTransportControls.GetForCurrentView();
systemMediaTransportControls.IsPlayEnabled = true;
systemMediaTransportControls.IsPauseEnabled = true;
systemMediaTransportControls.IsNextEnabled = true;
systemMediaTransportControls.IsPreviousEnabled = true;
systemMediaTransportControls.ButtonPressed += OnMediaButtonPressed;

Thanks in advance


text:
Q: Get most recent records from deeply nested model Say I have 3 models:
ModelA has many ModelB
ModelB has many ModelC
I'm querying ModelA, but in ModelC I have multiple ones of the same type, let's say I have 3 but I only need the most recently one.
I tried to do something like this...
records = ModelA.where(some query).includes ModelB includes ModelC

// convert activerecord collection to array
records = records.to_a

records.each do |record|

  record.modelBs.each do |modelB|
    filter the modelCs i don't need

    modelB.modelCs = filteredModelCs

  end

end

return records

but instead of merely returning the array of records, an UPDATE sql query is run and the db records are modified. this is a surprise because i never used the .save method and i thought i had converted the collection from an active record collection to an array
How can I filter deeply nested records without modifying the db records? then i can return the filtered result

A: Assigning a list of instances to a has_many collection with = will immediately persist the changes to the database.
Instead, I would try to solve this with more specific associations like this:
class A
  has_many :bs
  has_many(:cs, through: :bs)
  has_one :recent_c, -> { order(created_at: :desc).limit(1) }, source: :cs

class B
  has_many :cs

With those associations, I would expect the following to work:
as = A.where(some query).includes(:recent_c)

as.each do |a|
  a.recent_c # returns the most recent c for this a
end

A: If I got you right, you want to get a collection of latest Cs, which are connected to Bs, which are connected to certain A-relation? If so, you can do something like that (considering you have tables as, bs and cs):
class A < ApplicationRecord
  has_many :bs
end

class B < ApplicationRecord
  belongs_to :a

  has_many :cs
end

class C < ApplicationRecord
  belongs_to :b

  scope :recent_for_bs, -> { joins(
    <<-sql
      INNER JOIN (SELECT b_id, MAX(id) AS max_id FROM cs GROUP BY b_id) recent_cs
      ON cs.b_id = recent_cs.b_id AND cs.id = recent_cs.max_id
    sql
  ) }
end

And then you would query Cs like that:
C.recent_for_bs.joins(b: :a).merge(A.where(some_query))

You get recent Cs, inner join them with Bs and As and then get records connected to your A-relation by merging it.


text:
Q: Bundler with rbenv version pathfile issue So I am using rbenv to set my ruby version (for the specific project I'm working on this is 2.1.1).  The issue is that bundler is unable to detect this change.  I even tried to set the version in my gemfile:
source "https://my-proxy-address"
ruby "2.1.1"
gem 'fileutils'
gem 'json'
gem 'chef-api'

However this then causes the exact error message as seen here at the end of the tutorial:
username@hostname:~/Desktop/working-bundler-env$ rbenv version
2.1.1 (set by /Users/username/.rbenv/version)
username@hostname:~/Desktop/working-bundler-env$ ruby -v
ruby 2.1.1p76 (2014-02-24 revision 45161) [x86_64-darwin15.0]
username@hostname:~/Desktop/working-bundler-env$ bundle install
Your Ruby version is 2.0.0, but your Gemfile specified 2.1.1

The tutorial has the solution to the issue (edit a pathfile), however they dont say what file to change. What file do I change?
$ rbenv
rbenv 1.0.0
Usage: rbenv <command> [<args>]

Some useful rbenv commands are:
   commands    List all available rbenv commands
   local       Set or show the local application-specific Ruby version
   global      Set or show the global Ruby version
   shell       Set or show the shell-specific Ruby version
   install     Install a Ruby version using ruby-build
   uninstall   Uninstall a specific Ruby version
   rehash      Rehash rbenv shims (run this after installing executables)
   version     Show the current Ruby version and its origin
   versions    List all Ruby versions available to rbenv
   which       Display the full path to an executable
   whence      List all Ruby versions that contain the given executable

See `rbenv help <command>' for information on a specific command.
For full documentation, see: https://github.com/rbenv/rbenv#readme

$ which bundle
/usr/local/bin/bundle

A: So I noticed that when I ran gem bundle install the version was 1.13.3.  After running sudo find / -name bundle I found two file locations that included that version number.
/Users/myusername/.gems/gems/bundler-1.13.3/exe/bundle
/Users/myusername/.gems/gems/bundler-1.13.3/lib/bundler/man/bundle

After attempting to run /Users/myusername/.gems/gems/bundler-1.13.3/exe/bundle install it works perfectly.  So I just made an alias in my ~/.bash_profile that overwrote the incorrect bundle command.
alias bundle=/Users/alexcohen/.gems/gems/bundler-1.13.3/exe/bundle

The only side effect of this gem (for better or worse) is that it creates .bundle and path directories in the directory where I run bundle install where the gems are downloaded into.
I still have to investigate why this is happening, but I think that the bundle command in my macs terminal was referencing some type of broken bundler gem or file somewhere in my system.


text:
Q: Variable is not assigned C# Unity i have a problem with a variable:
private ScriptCorredor objetivo = null;
public List<ScriptCorredor> corredores2;

I'm adding a series of ScriptCorridor to the list
I edit and add the full Enter method
public void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.tag == "enemigo")
    {
        corredores2.Add(collision.GetComponent<ScriptCorredor>());
        if (objetivo=null)
        {
            objetivo = corredores2.ElementAt(0);
        }
    }
}

then i try asign the first objeto in the objetivo variable with:
objetivo = corredores2.ElementAt(0);

but cannot be assigned, when I read the objetivo variable, it is always empty.
any idea what I'm failing at?

A: You need to check (and maybe provide to this question post) your OnCollisionEnter() code and check that the object you collide with has the ScriptCorredor component attached. Also I think you should not access the component in the collision object directly, but through the collision.gameObject.
For example:
if (collision.gameObject.name == "MyGameObjectName")
{
    //If the GameObject's name matches the one you suggest, output this
    message in the console
    Debug.Log("Do something here");
}

So I would suggest to try:
collision.gameObject.GetComponent<ScriptCorredor>()

You can check:
https://docs.unity3d.com/ScriptReference/Collision-gameObject.html
Ánimo Ivan ;). Hope that helps
Edit: Full method with my suggestion:
public void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "enemigo")
    {
        corredores2.Add(collision.gameObject.GetComponent<ScriptCorredor>());
        if (objetivo == null)
        {
            objetivo = corredores2[0];
        }
    }
}

A: When you create the list at the top change it to:
public List<ScriptCorredor> corredores2 = new List<ScriptCorredor>();

You might be having an issue of trying to set index 0 of the list that hasn't been initialized yet. When you create the list variable its an empty variable. Adding new List<ScriptCorredor>(); to it, creates the list and puts it into that variable. Now it should work.