text:
Q: Postfix mail forwarder I just bought a dedicated server and I'm trying to install a webserver on it.
The server is Ubuntu 10.04. I installed ftp, nginx, php, mysql, bind and now I have to install mail server.
For the mail server I'm using Postfix, because it's recomended on ubuntu.
I installed Postfix with apt-get install postfix but mail() function from php wasn't working. After a little debug I found the way to solve this : I created an empty file /etc/postfix/main.cf and it worked good.
I do have a mx record like this
mail                5M IN A     xxx.xxx.xxx.xxx
example.com.        5M IN MX    1 mail.example.com.

After that I wanted to forward all e-mails to my GMail address.
So I googled for it and I found in the official docs Virtual Domain Host Forwarding
I added these lines in main.cf
virtual_alias_domains = example.com
virtual_alias_maps = hash:/etc/postfix/virtual

I created map file and I placed this line in it
@example.com me@gmail.com

I run in terminal
postmap /etc/postfix/virtual
postfix reload

The result: I can send e-mail from php with mail() function, but when I send an email to anything@example.com that e-mail isn't forwarded to my Gmail.
How to solve this?
-Andrew

I also tried this but not working http://rackerhacker.com/2006/12/26/postfix-virtual-mailboxes-forwarding-externally/

It works now! But I don't know what the problem was.
I just installed "Mail Server" from Tasksel and after that it worked fine.
Can anyone tell me what Tasksel installed or that it changed ?

A: To investigate what tasksel has/will load use:
$ tasksel --task-packages mail-server                             ~
dovecot-imapd
procmail
dovecot-common
postfix
libpth20
libmysqlclient16
libgpgme11
mutt
libpq5
dovecot-pop3d
bsd-mailx
ssl-cert
mysql-common

Most of these are security neutral-- except dovecot.  Dovecot is an excellent and very secure IMAP (server-side mail) service.  But, it does not belong on a typical webserver, and has nothing to do with sending mail.
What solved your problem is just that taskel ran the following command for you:
sudo dpkg-reconfigure postfix

Since your mail works now, just uninstall dovecot's packages:
sudo aptitude purge dovecot-common dovecot-imapd dovecot-pop3d

Good luck!

A: When you said "I send mail to anything@example.com", do you mean via another external account?
It sounds to me like your local mail delivery (php scripts calling mail()) is forwarding correctly, but your global internet mail delivery for example.com is not flowing to this box.
For that you'll need to make sure you have a MX record on example.com's DNS config that points to your server.


text:
Q: Loop thru selected directories in a particular order (Powershell) I have this code that creates a sql script that contains a list of filenames from selected directories. It works. However, I am looking for ways to improve it. Instead of repeating Get-ChildItem block for each directory I would like to loop through selected directories in a particular order.
For example, I only want filenames from the following directories:
schemas,
sequences, and
functions
(want to ignore the rest)
I also need filenames in a particular order: first - filenames from "schemas", then from "functions" and then from "sequences".
Is there a way to do it? Or, it is better to keep what I have now?
$suffix = ":r ""$CurrentDir\$DeleteTempTableScript""`r`nGO"

(Get-ChildItem $TFSDirectory"Schemas" -Filter *.sql -Recurse).FullName |
        ForEach-Object {
            "PRINT '$_'"
            "GO"
            ":r ""$_"""
            "GO"
            $suffix
        } | Set-Content -Path $MasterSQLFileName -Encoding UTF8

(Get-ChildItem $TFSDirectory"Functions" -Filter *.sql -Recurse).FullName |
            ForEach-Object {
                "PRINT '$_'"
                "GO"
                ":r ""$_"""
                "GO"
                $suffix
            } | Add-Content -Path $MasterSQLFileName -Encoding UTF8

(Get-ChildItem $TFSDirectory"Sequences" -Filter *.sql -Recurse).FullName |
        ForEach-Object {
            "PRINT '$_'"
            "GO"
            ":r ""$_"""
            "GO"
            $suffix
        } | Add-Content -Path $MasterSQLFileName -Encoding UTF8

A: The Path parameter accepts an array of strings, so you can do:
Get-ChildItem $TFSDirectory"Schemas", $TFSDirectory"Functions", $TFSDirectory"Sequences"

A: You have a couple of options. You could keep it simple and just add another loop. It will run in the order you put them. By making the outer loop a Foreach-Object loop you can still use the pipeline and do one Set-Content. The innerloop being a foreach statement is just preference.
"Schemas","Functions","Sequences" | ForEach-Object {
    Foreach($filepath in (Get-ChildItem $TFSDirectory$_ -Filter *.sql -Recurse).FullName)
    {
        "PRINT ""$filepath"""
        "GO"
        ":r ""$filepath"""
        "GO"
        $suffix
    }
} | Set-Content -Path $MasterSQLFileName -Encoding UTF8

Another option would be turn it into a function
Function New-SQLStatement {
    Param($Folder,$suffix)

    (Get-ChildItem $Folder -Filter *.sql -Recurse).FullName |
        ForEach-Object {
            "PRINT ""$_"""
            "GO"
            ":r ""$_"""
            "GO"
            $suffix
        }
}

"Schemas","Functions","Sequences" |
    ForEach-Object {New-SQLStatement -Folder $TFSDirectory$_ -suffix $suffix} |
        Set-Content -Path $MasterSQLFileName -Encoding UTF8

redpajama_set_name: RedPajamaStackExchange


text:
Q: Variable not accessible when declared in the Page_Load method When i declare a variable, lets say
public string [] companiesArray = {"Google","BBC","CNN","SportsDirect","Microsoft"};

just after public partial class Default : System.Web.UI.Page, the variable is accessible, but when i declare the variable in the Page_Load method, the variable is not accessible.
public void Page_Load(object sender, EventArgs e)
    {
    string [] companiesArray = {"Google","BBC","CNN","SportsDirect","Microsoft"};
    }

What could be the problem? Could some one help me out please.

A: If you declare the variable inside the Page_load it is a local variable for that scope.
If you declare the variable after public partial class Default : System.Web.UI.Page
it is a global variable for all the Page.

A: You need to understand about scope.
When you define the array in the page, you are defining the scope to be the class. You can use the variable anywhere within the class.
public partial class Default : System.Web.UI.Page
{
   string[] companiesArray;

    public void DoFizz()
    {
        companiesArray[0] = "Fizz";
    }

    public void DoBuzz()
    {
        companiesArray[1] = "Buzz";
    }
}

When you define it in page load, then the scope is limited to that method, so you can only use it within that method.
public partial class Default : System.Web.UI.Page
{
    public void Page_Load(object sender, EventArgs e)
    {
        string[] companiesArray;
    }
}

One of the major advantages of this, is if you declare variables within methods, it stops you accidentaly using a variable that may have been defined and used elsewhere. If this were not the case you wouldn't be able to guarantee the state of your variable.

A: Read up on Scope
If a variable is defined within your Page_Load method, then it is local to that method
If you defined it outside of the method, it's visible to the rest of the code, and is typically refered to as a Field, e.g.
public partial class Page : System.Web.UI.Page
{
   private string[] companiesArray = {"Google","BBC","CNN","SportsDirect","Microsoft"};
   public void Page_Load(object sender, EventArgs e)
   {
      //companiesArray  is visible here
   }

   public void SomeOtherMethod()
   {
      //companiesArray is visible here too
   }
}


text:
Q: Error: Cannot find module './server/controllers/meetups-controller' I am having a problem with my mean app i get Error: Cannot find module './server/controllers/meetups-controller'. The file is in the right directory but i get the error please help
here is my server code :
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var mongoose = require('mongoose');
var hash = require('bcrypt-nodejs');
var path = require('path');
var passport = require('passport');
var localStrategy = require('passport-local' ).Strategy;
var meetupsController = require('./server/controllers/meetups-controller.js');
// mongoose
mongoose.connect('mongodb://localhost/mean-auth');

// user schema/model
var User = require('./models/user.js');

// create instance of express
var app = express();

// require routes
var routes = require('./routes/api.js');

// define middleware
app.use(express.static(path.join(__dirname, '../client')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));

// configure passport
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// routes
app.use('/user/', routes);

app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, '../client', 'index.html'));
});

// error hndlers
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function(err, req, res) {
  res.status(err.status || 500);
  res.end(JSON.stringify({
    message: err.message,
    error: {}
  }));
});

app.use(bodyParser());
app.use('/js', express.static(__dirname + '/client/js'));

//REST API
app.get('/api/meetups', meetupsController.list);
app.post('/api/meetups', meetupsController.create);
module.exports = app;

A: Not sure but may be you do not need to explicitly mention the file extension.
Not tested but you can try by removing the js part
var meetupsController = require('./server/controllers/meetups-controller');


text:
Q: Set local font in IntelliJ IDEA I'm running IntelliJ IDEA on Windows 10 20H2, how to add more font to IntelliJ IDEA? I tried to find the entrance to add my font (in my local computer, but I don't know if it is installed), but I couldn't find any.

A: *

*In Windows Explorer select all font files in the folder, right-click any of them, then pick "Install" from the menu.

*Restart Intellij

*Go to Preferences/Settings → Editor → Font, and pick your Font from the Font dropdown.


text:
Q: Need to save log in DB of every login attempt but getting syntax error I'm trying to save log. I have a User table and a Userlog table. The username is my foreign key in Userlog table.One to many relation (one user can have many userlogs). I'm trying to save it but I'm getting syntax error. Also if you can tell me if the code is good or can it be more efficient.
public bool log(string user)
{
    OleDbConnection conn = new OleDbConnection(cs);
    conn.Open();

    string date = DateTime.Now.ToString();
    string query = "insert into UserLog(Username, TimeStamp) Values('"+user+"','"+date+"')";

    OleDbCommand cmd = new OleDbCommand(query, conn);
    //cmd.Parameters.Add("@1", OleDbType.Char, 20).Value = user;
    //cmd.Parameters.Add("@2", OleDbType.Char, 20).Value = DateTime.Now;

    try
    {
        cmd.ExecuteNonQuery();
    }
    catch (Exception)
    {
        throw;
    }

    return true;
}

A: There is an error near the end of your insert statement. Replace it by:
string query = "insert into UserLog(Username, TimeStamp) Values ('"+user+"','"+date+"');";


text:
Q: Redirect to homepage without changing address bar URL I am trying to redirect people that enter the URL domain.com/project/206/9 to domain.com but the URL domain.com/project/206/9 should be displayed. Then I want to extract the numbers 206 and 9 from my URL and use that in my code.
I am using a Wordpress website.

A: Try this.
Write below code in your htaccess file
Redirect domain.com/project/206/9 domain.com

It may help you.


text:
Q: SAPUI5 ODates, dates with GMT +1 I have an issue where I'm providing a to date, then filtering some odata on that date....
  var effectiveTo = moment(oArgs.effectiveDateTo).format('YYYY/MM/DD 00:00:00');

  new Filter("StartDate", FilterOperator.LE, moment(new Date(effectiveTo)).toDate())/

The problem is, if the date falls after the 26th March, +1 is added to the time in the StartDate, so the filter no longer returns the correct data.
Any ideas how I get around this?

A: The problem is that when exchanging data with OData service values of DatTime type automatically converted to and from local browser timezone and also light saving periods. Probably you should pass Dates as strings? I've seen such a technique in standard SAP Fiori applications.
this is how SAP Leave Request app prepares dates before sending to the backend:
sStartDate = hcm.myleaverequest.utils.Formatters.DATE_YYYYMMdd(_oStartEndDates.startDate) + 'T00:00:00';
sEndDate = hcm.myleaverequest.utils.Formatters.DATE_YYYYMMdd(_oStartEndDates.endDate) + 'T00:00:00';


text:
Q: JavaFX ListView duplicate removal error link to imgur
@FXML
ListView queueList;

ObservableList<QueueSong> SongQueueObservableList;

queueList.setCellFactory(new Callback<ListView<QueueSong>,ListCell<QueueSong>>() {
    @Override
    public ListCell<QueueSong> call(ListView<QueueSong> myObjectListView) {
        ListCell<QueueSong> cell = new ListCell<QueueSong>(){
            @Override
            protected void updateItem(QueueSong myObject, boolean b) {
                super.updateItem(myObject, b);
                if(myObject != null) {
                    setText(myObject.getSong());
                }
            }
        };
        return cell;
    }
});

queueList.setItems(SongQueueObservableList);

SongQueueObservableList.add(new QueueSong("song 1", "artist 1"));
SongQueueObservableList.add(new QueueSong("song 2", "artist 2"));
SongQueueObservableList.add(new QueueSong("song 3", "artist 3"));
SongQueueObservableList.add(new QueueSong("song 4", "artist 4"));

I've tried the following implementations of removing
Platform.runLater( () -> {
       // queueList.getItems().remove(0);
        SongQueueObservableList.remove(0);
    });

The rows after the first duplicate are not selectable. And it's only once all the  values are removed from the list, that the ListView updates with an empty list.
If anyone has any tips on how to go about solving this, I'd appreciate it.
When I use the debugger, both the ObservableList and the ListView have the expected values. I guess the real question is, why is it that only when all objects are removed, that the ListView clears itself?

A: The problem is the cell class you use. It only sets the text, but never clears it. Since it's possible that cells become empty, you need to fix this behaviour:
new ListCell<QueueSong>(){
    @Override
    protected void updateItem(QueueSong myObject, boolean empty) {
        super.updateItem(myObject, empty);
        // set text to song or clear (= set to null)
        setText((empty || myObject == null) ? null : myObject.getSong());
    }
}


text:
Q: Are jackson web servlets thread safe? I am wondering how, in concept, the web requests different from threads that I can create in application itself?  Do they suffer from same problems as threads do (locking, have to make state-objects thread - safe)
Are various HTTPRequests in any java - jackson (rest apis) application synchronized by web-server automatically?  Are these requests not like threads and suffer from the possibility of interfering with states of various classes which are handling these web-requests?  Or, is this something that application developers have to manage themselves? i.e. they do need to either synchronize or make these jackson servlets thread-safe otherwise?
Thanks

A: Servlets should be written as if they were single threaded.  Each HTTP request coming in will be handled in a separate thread.
This means no shared mutable state in servlet classes.
If your servlet has no private data members and all operations are performed on parameters that are passed in or local objects, you're thread safe.  No synchronization needed.
Shared state has to be thread safe.

A: see :
How are Threads allocated to handle Servlet request?
It is not specify in Servlet JSR, but usually a J2EE web server use one thread to handle a user request.
So many request are using one instance of your Servlet => many thread are using one instance of your Servlet.
To avoid deadlock or performance issue don't synchronized Servlet code, make them threadsafe and stateless:
See:
How do servlets work? Instantiation, sessions, shared variables and multithreading
JSR Servlet spec 3.0
http://download.oracle.com/otndocs/jcp/servlet-3.0-fr-eval-oth-JSpec/

Request Handling Methods
  The basic Servlet interface defines a service method for handling client requests.
  This method is called for each request that the servlet container routes to an instance
  of a servlet.
  The handling of concurrent requests to a Web application generally requires that the
  Web Developer design servlets that can deal with multiple threads executing within
  the service method at a particular time.
  Generally the Web container handles concurrent requests to the same servlet by
  concurrent execution of the service method on different threads.


text:
Q: How to load data outside Django view? If i have some Django views like 'first', 'second' and so on, and i want to load some data outside this views but use it inside views.
Here is an example to understand my idea.
#function execution time is long, that is why i want to laod it only once when run programm.

fetched_data_from_postgres = some function which load data from postgres and return list with postgres data

def first(request):
    #and the i want to use that previous value in all my views
    fetched_data_from_postgres = do something
    return HttpResponse("first VIEW")

def second(request):
    #and the i want to use that previous value in all my views
    fetched_data_from_postgres = do something
    return HttpResponse("secondVIEW")

def third(request):
    #and the i want to use that previous value in all my views
    fetched_data_from_postgres = do something
    return HttpResponse("third VIEW")

this aproach working well when i run my django project like this python manage.py runserver but when i run with gunicorn or wsgi when i can specify workers count then when worker changes then this variable is lost and need to refresh page to get this previous worker to get that data. It's ridiculous.
Or maybe there is some other aproach to do this job?

A: This approach doesn't work when you start project locally with python manage.py runserver, it only works once, when project starts, and then you need to reload the project every time. This is because everything in any_views.py loads only once, when project starts, except your functions. So you have to restart your project, in order to refresh your fetched_data_from_postgres variable.
The better approach is to create a script fetch_script.py, move your function some function which load data from postgres and return list with postgres data inside it, and call it inside of views.py, not outside.

A: The best solution to avoid loading your data several times and to prevent this function fetched_data_from_postgres to run twice is to use a cache framework alongside Django. Check the documentation for more details:
https://docs.djangoproject.com/en/stable/topics/cache/
It's relatively easy to set up and it should perfectly address your problem. If you feel it like overkill, then the question is do you really need speed? Are you sure you're not trying to prematurely optimize?


text:
Q: python - How to use regex to delimit input Say I'm reading directly from an HTML document in my code. Each line looks something like the following:
field1	field2	field3

I want to write code that can easily pick out the fields field1, field2, and field3. I know that every single line of this table is going to be the exact same format, besides each of these fields.
I'm not that familiar with regex, but in my research I've only ever seen it used for searching for known tokens amongst unknown tokens, rather than isolating unknown tokens among known tokens. Due to my inexperience with regex my example will essentially follow the pattern of a C string formatter (using %s for an input token).
So basically, I want to be able to implement the following method with regex:
(field1, url, field2, field3) = regex_extract('%s	%s	%s	')

Is this a thing that's possible with regex?

A: If you want to use regex, here's yours:
import re

a = "field1	field2	field3	"
REGEX = r'(\w+)	(\w+)	(\w+)	'
print(re.findall(REGEX, a))
>>>> [('field1', 'http://sample.url.com', 'field2', 'field3')]

A: You can do something like:
import re
pattern = re.compile('(?P<field1>.*?)	<A HREF="(?P<url>.*?)">(?P<field2>.*?)	(?P<field3>.*?)	')

html = 'field1	field2	field3	'
match = pattern.search(html)
if match:
    field1, url, field2, field3 = match.groups()
    # or you can do field1 = match.group('field1') and so on....

A: I suggest you the following simple solution, returning fields and optionnaly the url in a list:
import re

s = "field1	field2	field3	"

# If you want to extract the URL
myPattern = re.compile(r'(\w+)	(\w+)	(\w+)	')
listOfMatches = list(myPattern.findall(s)[0])
print(listOfMatches) # ['field1', '"http://sample.url.com"', 'field2', 'field3']

# If you don't want to extract the URL
myPattern = re.compile(r'(\w+)	(\w+)	(\w+)	')
listOfMatches = list(myPattern.findall(s)[0])
print(listOfMatches) # ['field1', 'field2', 'field3']


text:
Q: how to get first object in ng-repeat I am displaying a contact's information using ng-repeat. Each contact has details. I am trying to grab the first object in the list. Here is my code:

{{contact.name}}

{{contact.type}}

contactList() is a function calling services:
$scope.contactList = function () {
    return ContactService.getContactList();
};

How do I get the first contact object in the ng-repeat? I want to save that object for other windows.

A: You could use 'track by $index' and use an 'ng-if' to determine when it's the first object:

 {{contact.name}}

{{contact.type}}

You could then have a function 'someMethod()' in your controller that saves the object to a window object or to local storage:
function someMethod(key, object) {
    window.localStorage.setItem(key, object);
}

I have written an object to use for this exact thing in fact if you want to use it:
var LocalStorageManager = {
setValue: function(key, value) {
    window.localStorage.setItem(key, JSON.stringify(value));
},
getValue: function(key) {
    try {
        return JSON.parse(window.localStorage.getItem(key));
    } catch (e) {

    }
  }
};

So, you would use it with your stuff like this, in your 'someMethod()':
function someMethod(key, object) {
    LocalStorageManager.setValue(key, object);
}

Then, to get the object, you would just use the 'getValue' method calling the 'key' that you gave the object.

A: You can set a new scope property to be a result of filtering and ordering. Note, how you group filters with ():

{{contact.name}}

{{contact.type}}

Then to get the first from this list it will be just [0]:
{{ contacts[0] }}

A: I'm guessing you don't just want to display the one record and you also want the first record from the array after your filters/ordering are applied.  If that is the case I would recommend simply adding an alias after your last condition and then you can reference that alias in your controller.
here is a fiddle to help show:
http://jsfiddle.net/nbavesuo/
I would suggest you not call the function in the ng-repeat instead reference an array that has already been called:

....

Then in your controller:
$scope.contactList = ContactService.getContactList();

$scope.selectedContact = function(contact){
    console.log(contact);
    console.log($scope.filteredArray[0]);
}

You'll see that $scope.filteredArray[0] will have the 1st element in the sorted array.


text:
Q: Ошибка при запуске приложения asp.net
Только начал изучать asp.net и столкнулся c данной проблемой. При запуске веб приложения VisualStudio выдает ошибку. Раньше удавалось запустить приложение с n-ной попытки. Ошибка вылетает на разных проектах, в том числе и не на моих. Текст с изображения:

Не удаётся запустить программу "http://localhost:22952/001_PageEvents/005_PageEvents2.aspx".
   Операция недопустима в текущем состоянии.

A: Переходим в Отладка -> Параметры -> Общие ->
 Снимите галочку с "Включить отладку JavaScript для ASP.NET (Chrome и IE)
Go to Tools > Options > Debugging > General and turn off the setting for Enable JavaScript Debugging for ASP.NET (Chrome and IE).


text:
Q: PWA Automated test with Selenium IDE I'm having trouble automating PWA tests using selenium IDE.
Indeed I fill a form and at the time of saving the button "css=.hover\3Aopacity-90" remains grayed whereas I filled all the obligatory fields.

I also have the same problem when I switch from one page to another with toaster eruption and when I want to select a label in a dropdown list through the search bar "id=headlessui-combobox-input-".
If you can help me to move forward please. Thanks


text:
Q: How to strip the last comma in a string, when I am looping the comma to separate different part of it I am trying to loop every element of a list, and append each element of the list to a string in the format like aa, bb, cc, dd, ee, ....
My loop is like this:
    string = ""

    for num in sorted(list):
       string = "xyz" + "-" + str(list[num])
       string = string + ", "

    return string

The format it output is like xyz - 1, xyz - 3, xyz -6,
How can I end up without last comma in a format like
xyz - 1, xyz - 3, xyz -6 ?

A: Instead of constructing the string yourself, you can use str.join:
string = ', '.join("xyz-"+str(x) for x in sorted(list))

.join is called on a string that acts as a separator: it will be inserted between the elements (but not after the last element). In the join you need to provide an iterable (list, tuple, set, generator,...) that provides strings that should be joined together.
In this case we wrote an iterator that will, for every x in the sorted(list) generate a string "xyz-"+str(x) and these products will be joined together.

ERRORS?
There is furthermore probably an error in your code:

for num in sorted(list):
    string = "xyz" + "-" + str(list[num])

If you use a for over a list, you get the elements, not the indices. So it should be num instead of list[num].

A: use str.join and a list comprehension to avoid doing this:
return ", ".join(["xyz-{}".format(num) for num in sorted(lst)])

(and note that your code has other issues than that: using list as a variable, doing lst[num] where num is needed are 2 examples)
(([ is not a typo: creating a list comprehension and not a generator comprehension allows join to work faster: List vs generator comprehension speed with join function)


text:
Q: Xamarin.forms C# 2 quotation marks How to format this line of code so that in "myusername" you can enter the text typed from the phone keyboard, e.g. instead of "myusername" I would like there to be email.Text. email.text must be in quotation marks. Sorry for my bad english.
string jsonData = @"{""username"" : ""myusername"", ""password"" : ""mypassword""}";

I tried this way but it still doesn't work
 string jsonData = "{ \"Email\" : \"{0}\" ,\"Password\" : \"{1}\"}";

 string jsonMain = String.Format(jsonData, email.Text, password.Text);

A: You can Serializing and Deserializing JSON with follow codes:
public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        testModel model = new testModel();
        model.Email = "abc";
        model.username = "allen";

        string jsonString;
        jsonString = JsonConvert.SerializeObject(model);

        //deserialize
        testModel deserializedmodel = JsonConvert.DeserializeObject<testModel>(jsonString);

    }
}

public class testModel
{
    public string Email { get; set; }
    public string username { get; set; }
}


text:
Q: Java Average of MultiDimensional List I am having problem with calculating average for my multidimensional list. I read most of the questions and answers here and other places as well but I could not find a solution.
My codes generate a list with values as shown below (4 columns). I was trying to calculate the average for each column but I don't know how to. Since the list does not have the length property, I tried to convert the whole thing to an array so I can determine the length, then sum up and take average. The data was place in a hashmap (map) and then dump into a list (mapList). Would please show me how to do this? Really appreciate any inputs. Thank you!
Array  LinkedList ArrayList  Vector
[44, 40, 80, 81]
[43, 56, 61, 42]
[47, 34, 64, 41]
[37, 39, 86, 66]
[31, 30, 55, 43]

Here are the codes.
private void setMap(){
    // print headers
    System.out.printf("%5s%12s%10s%8s\n","Array", "LinkedList",
            "ArrayList", "Vector");
    for (int i = 0; i < numberTimes; i++){

        // put calculated time into hashmap
        map.put("Array", timer.arrayTimes());
        map.put("LinkedList", timer.linkedTimes());
        map.put("ArrayList", timer.listTimes());
        map.put("Vector", timer.vectorTimes());

        // put hashmap values into List
        mapList = new ArrayList(map.values());

        // iterate through mapList list
        Iterator iter = mapList.iterator();

        // print hashmap values
        while (iter.hasNext()){

             // print values in numbers
             System.out.printf("%-10d", iter.next());
         } // end while
        System.out.println();
    } // end for
} // end setMap

A:
Since the list does not have the length property, I tried to convert
  the whole thing to an array so I can determine the length, then sum up
  and take average.

List doesn't has the length property but size property. For example,
List<T> list = new ArrayList<T>();
list.add((T) object1);
list.add((T) object2);
System.out.println(list.size());

Hope, this will set you to the path of getting the size of list.
So, if you put your list in map, iterate over the map, against each item of map, iterate through the size, count it and get the average.

A: You made your code very messy and Complexity arises , so below is my code for finding average using Hashmap Technique.Refer below is my code , Understand this and again try to implement ..Thanks
import java.util.*;

public class QueQue {

public static float getAverage(HashMap<String, ArrayList<Integer>> hm, String name) {
    ArrayList<Integer> scores;
    scores = hm.get(name);
    if (scores == null) {
        System.out.println("NOT found");
    }

    int sum = 0;
    for (int x : scores) {
        sum += x;
    }
    return (float) sum / scores.size();
}
//Find the Best Student from these Key-Value Pair
public static String getBestStudent(HashMap<String, ArrayList<Integer>> hm) {
    double max = 0;
    String beststudent = null;
    for (Map.Entry<String, ArrayList<Integer>> x : hm.entrySet()) {
        String name = x.getKey();
        double average = getAverage(hm, name);
        if (average > max) {
            max = average;
            beststudent = name;
        }
    }
    return beststudent;
}

public static void main(String[] args) {
    HashMap<String, ArrayList<Integer>> hm = new HashMap<>();
    hm.put("Peter", new ArrayList<>());
    hm.get("Peter").add(10);
    hm.get("Peter").add(10);
    hm.get("Peter").add(10);

    hm.put("Nancy", new ArrayList<>());
    hm.get("Nancy").add(7);
    hm.get("Nancy").add(8);
    hm.get("Nancy").add(8);

    hm.put("Lily", new ArrayList<>());
    hm.get("Lily").add(9);
    hm.get("Lily").add(9);
    hm.get("Lily").add(8);

    System.out.println("Find the average of the Peter");
    float num = getAverage(hm, "Peter");
    System.out.println(num);
    String name = getBestStudent(hm);
    System.out.println(name);
}
 }

A: You can use an enhanced for-loop to loop through each element in the hash map, like the following:
private void setMap(){
    // print headers
    System.out.printf("%5s%12s%10s%8s\n","Array", "LinkedList",
            "ArrayList", "Vector");
    for (int i = 0; i < numberTimes; i++){

        // put calculated time into hashmap
        map.put("Array", timer.arrayTimes());
        map.put("LinkedList", timer.linkedTimes());
        map.put("ArrayList", timer.listTimes());
        map.put("Vector", timer.vectorTimes());

        // Loops through each element of map.values() and assigns its value to the val variable
        for(String val : map.values()){
            System.out.printf("%-10d", val);
        }
        System.out.println();
    } // end for
}

Please not that you will need to change "String" in the for loop to the data type held by the HashMap.
You can actually get the size of a hashMap by using the .size() method, for example:
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.size();

A: If you are using ArrayList > stringarray_name = new ArrayList >()
You can use the ouuter array list.size () to find the total row and then process each row adding the values and find the average.


text:
Q: django_rq jobs are not added to the queue I am using:
  django-rq: 0.9.6
  rq_scheduler: 0.6.1
I am fairly new to docker and django_rq.
The issue that I am having is, my jobs are not executing or getting in the queue.
docker-compose.yml
redis:
    container_name: projapi-redis
    restart: always
    image: redis:latest
    ports:
      - '6379:6379'

rq:
    container_name: projapi-rq
    build: .
    command: python manage.py rqworker default
    volumes:
      - .:/src
    links:
      - redis

  rqscheduler:
    container_name: projapi-rqscheduler
    build: .
    command: python manage.py rqscheduler
    volumes:
      - .:/src
    links:
      - redis

settings.py
RQ_QUEUES = {
    'default': {
        'URL': 'redis://redis/0',
    }
}

In the python shell, I ran :do_task.delay() and the RQ Queues' finished jobs jumps up in number by a large amount. When I run: scheduler.schedule(datetime.utcnow(), 'do_task', interval=20), I don't get any response.
tasks.py
from django_rq import job, get_scheduler
from datetime import datetime

scheduler = get_scheduler()

@job
def do_delay_task():
    return 'do_delay_task'

@job
def do_task():
    return 'do a task'

do_delay_task.delay()
scheduler.schedule(datetime.utcnow(), 'do_task', interval=2000)

A: It is periodic task run, you forgot to run it:
scheduler.run()

also consider using of this module:
https://github.com/rq/rq-scheduler


text:
Q: ProtocolException: Invalid header: :: std_case: HASH(0x7ff022faf630) - header starting with colon I'm having a problem with response headers:
org.apache.http.ProtocolException: Invalid header: :: std_case: HASH(0x7ff022faf630)

This is on calling a booking.com URL.  E.g.
http://www.booking.com/hotel/gb/the-rothley-court.html?aid=374908
Again, the problem is in the org.apache.http.message.BufferedHeader where the buffer is

:: std_case: HASH(0x7ff022faf630)

This starts with the colon that causes all the problems!
I'm using httpcore-4.4.6 (latest on Maven)
The offending code in BufferedHeader is:
    public BufferedHeader(CharArrayBuffer buffer) throws ParseException {
    Args.notNull(buffer, "Char array buffer");
    int colon = buffer.indexOf(58);
    if(colon == -1) {
        throw new ParseException("Invalid header: " + buffer.toString());
    } else {
        String s = buffer.substringTrimmed(0, colon);
        if(s.length() == 0) {
            throw new ParseException("Invalid header: " + buffer.toString());
        } else {
            this.buffer = buffer;
            this.name = s;
            this.valuePos = colon + 1;
        }
    }
}

Has anyone found a work around for this yet?


text:
Q: Wrapping a java.nio.ByteBuffer in a new instance, with offset, loses bytes I'm trying to write the contents of a byte buffer to a file, using the offset (position). It works when I convert to an input stream, but not when I wrap in a new ByteBuffer
This works:
new ByteArrayInputStream(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())

This doesn't
ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())

More specifically, when I say it doesn't work, writing the contents of the buffer to a file:
Files.write(path, ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position()).array())
results in bytes written to the file but it is not complete, so the jpeg cannot be viewed, but if I write the same buffer, wrapping in a ByteArrayInputStream, it does work:
val in = new ByteArrayInputStream(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())
Iterator.continually (in.read).takeWhile (-1 != _).foreach (fileOutputStream.write)

So I must be doing something silly and perhaps I don't understand how ByteBuffer works

A: ByteBuffer.wrap(byteBuffer.array(), <ANYTHING>, <ANYTHING>).array() means just byteBuffer.array(), and <ANYTHING> isn't taken into account.
Also, the whole
ByteBuffer.wrap(byteBuffer.array(), byteBuffer.position(), byteBuffer.array().length - byteBuffer.position())

is just a cumbersome way to create a shallow copy of byteBuffer, why do you do it instead of just using the byteBuffer itself?
Looks like what you want is something like
try (FileChannel outCh = new FileOutputStream(filename).getChannel()) {
    outCh.write(byteBuffer);
}


text:
Q: How to initialize the selection for rails-select2 in BackboneForms schema? The project uses marionette-rails, backbone-on-rails, select2-rails and this port to BackboneForms to provide a multiselect form field. The select options are available to the user. They are retrieved from the collection containing the total list of options:

MyApp.module("Products", function(Products, App, Backbone, Marionette, $, _) {

  Products.CustomFormView = Products.CustomView.extend({

    initialize: function(options) {
      this.model.set("type", "Product");
      Products.EntryView.prototype.initialize.apply(this, arguments);
    },

    schemata: function() {
      var products = this.collection.byType("Product");
      var productTypes = products.map(function(product){
        return {
          val: product.id,
          label: product.get("name")
        };
      });

      return {
        productBasics: {
          name: {
            type: "Text",
            title: "Name",
            editorAttrs: {
              maxLength: 60,
            }
          },
          type: {
            type: 'Select2',
            title: "Product type",
            options: {
              values: productTypes,
              value: [3, 5],
              initSelection: function (element, callback) {
                var data = [];
                $(element.val().split(",")).each(function () {
                  data.push({id: this, text: this});
                });
                callback(data);
              }
            },
            editorAttrs: {
              'multiple': 'multiple'
            }
          }
        }
      };
    }

  });
});

Do I initialize the value correctly in options.value? How comes initSelection is never called? I copied the function from the documentation - it might be incomplete for my case. None of the products with the IDs 3 and 5 is displayed as the selection.

A: You can use value function (http://ivaynberg.github.io/select2/#documentation) in setValue. I personally recomend you to use this backbonme-forms plugin: https://gist.github.com/powmedia/5161061
There is a thread about custom editors: https://github.com/powmedia/backbone-forms/issues/144

A: initSelection is only used when data is loaded asynchronously. My understanding is that there is no way of specifying the selection upon initialization if you are using an array as the data source for a Select2 control.
The best way of initializing the selection is by using setValue after the form is created. Here is a simplified example based on the code in your example.
var ProductForm = Backbone.Form.extend({
  schema: {
    type: {
      type: 'Select2',
      title: "Product type",
      options: {
        values: productTypes,
      },
      editorAttrs: {
        'multiple': 'multiple'
      }
    }
  });

var form = new ProductForm({
  model: new Product()
}).render();

form.setValue("type", [3, 5]);


text:
Q: trouble for capture screenshot from determined window handle I'm using a code found on internet for capture screenshot from determined window handle, but he failure in this line:
Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);

So, how I can solved it?
Here is the code that I said above:
        [DllImport("user32.dll")]
        public static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
        [DllImport("user32.dll")]
        public static extern bool PrintWindow(IntPtr hWnd, IntPtr hdcBlt, int nFlags);
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        public static Bitmap PrintWindow(IntPtr hwnd)
        {
            RECT rc;
            GetWindowRect(hwnd, out rc);

            Bitmap bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb);
            Graphics gfxBmp = Graphics.FromImage(bmp);
            IntPtr hdcBitmap = gfxBmp.GetHdc();

            PrintWindow(hwnd, hdcBitmap, 0);

            gfxBmp.ReleaseHdc(hdcBitmap);
            gfxBmp.Dispose();

            return bmp;
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct RECT
        {
            private int _Left;
            private int _Top;
            private int _Right;
            private int _Bottom;

            public RECT(RECT Rectangle)
                : this(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom)
            {
            }
            public RECT(int Left, int Top, int Right, int Bottom)
            {
                _Left = Left;
                _Top = Top;
                _Right = Right;
                _Bottom = Bottom;
            }

            public int X
            {
                get { return _Left; }
                set { _Left = value; }
            }
            public int Y
            {
                get { return _Top; }
                set { _Top = value; }
            }
            public int Left
            {
                get { return _Left; }
                set { _Left = value; }
            }
            public int Top
            {
                get { return _Top; }
                set { _Top = value; }
            }
            public int Right
            {
                get { return _Right; }
                set { _Right = value; }
            }
            public int Bottom
            {
                get { return _Bottom; }
                set { _Bottom = value; }
            }
            public int Height
            {
                get { return _Bottom - _Top; }
                set { _Bottom = value + _Top; }
            }
            public int Width
            {
                get { return _Right - _Left; }
                set { _Right = value + _Left; }
            }
            public Point Location
            {
                get { return new Point(Left, Top); }
                set
                {
                    _Left = value.X;
                    _Top = value.Y;
                }
            }
            public Size Size
            {
                get { return new Size(Width, Height); }
                set
                {
                    _Right = value.Width + _Left;
                    _Bottom = value.Height + _Top;
                }
            }

            public static implicit operator Rectangle(RECT Rectangle)
            {
                return new Rectangle(Rectangle.Left, Rectangle.Top, Rectangle.Width, Rectangle.Height);
            }
            public static implicit operator RECT(Rectangle Rectangle)
            {
                return new RECT(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Bottom);
            }
            public static bool operator ==(RECT Rectangle1, RECT Rectangle2)
            {
                return Rectangle1.Equals(Rectangle2);
            }
            public static bool operator !=(RECT Rectangle1, RECT Rectangle2)
            {
                return !Rectangle1.Equals(Rectangle2);
            }

            public override string ToString()
            {
                return "{Left: " + _Left + "; " + "Top: " + _Top + "; Right: " + _Right + "; Bottom: " + _Bottom + "}";
            }

            public override int GetHashCode()
            {
                return ToString().GetHashCode();
            }

            public bool Equals(RECT Rectangle)
            {
                return Rectangle.Left == _Left && Rectangle.Top == _Top && Rectangle.Right == _Right && Rectangle.Bottom == _Bottom;
            }

            public override bool Equals(object Object)
            {
                if (Object is RECT)
                {
                    return Equals((RECT)Object);
                }
                else if (Object is Rectangle)
                {
                    return Equals(new RECT((Rectangle)Object));
                }

                return false;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IntPtr h = FindWindow("Chrome_WidgetWin_1", "");
            pictureBox1.Image = PrintWindow(h);
        }

Thanks in advance.

A: You should pass both class and window name to FindWindow in order to work properly. An old tool like Spy++ can help you to find the correct class and name.


text:
Q: dividing data frame and transposing in a for loop r Hi I have a csv file that I want to split by every row, then create a new file for that row of data, then transpose that data, and then finally save the dataframe as a new csv file based on the value in the 'full_name column. I can write the straightforward code to do this for the first row, but I am clueless for when it comes to doing this over the 331 iterations or rows of my initial csv
my code (that works fine for the first row) is this:
library(rvest)
library(data.table)
library(readr)
library(readxl)
library(tidyverse)

setwd("~/Desktop/Monthly_Reports")

Reports <- read_csv("~/Desktop/Monthly_Reports/REPORTS MASTER - SEPT.csv")

#takes the first row subsets it and renames it based on the value in the name column
Reports1 <- Reports[1,]
Report1_Name <- Reports1$Full_Name[[1]]

#then transposes the data, and makes it easier to read as a list
Reports1 <- transpose(Reports1)
rownames(Reports1) <- colnames(Reports1)
colnames(Reports1) <- rownames(Reports1)

#then binds the list so that it can be exported as data frame and into and individual csv
Reports1 <- as.data.frame(Reports1)
Reports1 <- do.call("rbind", lapply(Reports1, as.data.frame))
write.csv(Reports1, paste0(Report1_Name,".csv"))

I want to do this 331 times for every row of data, if anybody could show me how to do this it seems so simple but i have read so many threads and website help on for loops, lapply all kinds of stuff and for some reason i'm still struggling
Many thanks

A: I don't have the data, so I can't confirm, but something like this should work:
library(rvest)
library(data.table)
library(readr)
library(readxl)
library(tidyverse)

setwd("~/Desktop/Monthly_Reports")

Reports <- read_csv("~/Desktop/Monthly_Reports/REPORTS MASTER - SEPT.csv")

#takes the first row subsets it and renames it based on the value in the name column
for(i in 1:nrow(Reports)){
  Reports1 <- Reports[i,]
  Report1_Name <- Reports1$Full_Name[[1]]

  #then transposes the data, and makes it easier to read as a list
  Reports1 <- transpose(Reports1)
  rownames(Reports1) <- colnames(Reports1)
  colnames(Reports1) <- rownames(Reports1)

  #then binds the list so that it can be exported as data frame and into and individual csv
  Reports1 <- as.data.frame(Reports1)
  Reports1 <- do.call("rbind", lapply(Reports1, as.data.frame))
  write.csv(Reports1, paste0(Report1_Name,".csv"))
}


text:
Q: Django - Can I use an abstract Model in another Model? I'm new to Django (and it's been a few years since I played with databases), and might be dancing around something simple that I don't know what to google.
Essentially, I want to have a table of "Events" which can contain data of various Types.  Say one event is an "alarm" and another is a "message."  The "alarm" type needs different fields than the "message" so it seems to make sense to not store the data in one big table containing any sort of data that might be needed for any event.  However, I want to be able to get a list of all events for a given "event_block" foreign key.
I have done some reading about abstract models and proxies, etc, but I haven't been able to figure out how one Model can refer to an abstract model (if that is in fact the path to take).
models.py:
class Event(models.Model):
  #id auto-generated primary_key
  event_block = models.ForeignKey(Block, on_delete=models.CASCADE)
  event_data = BaseEvent  # This is wrong, but what is right?

class BaseEvent(Models.model):
  class Meta:
    abstract=True
  ... common event info ...

class AlarmEvent(BaseEvent):
  ... event info for alarms ...

class MessageEvent(BaseEvent):
  ... event info for messages ...

Ideally I would be able to, in my template, create a drop down box with all available event_types and then click a "submit" button the form to create that event (with its necessary event data fields) within my Event model and let Django handle the details of how that is handled in the database tables.
What am I missing?

A: Firstly, This is appropriate with the Event model
class Event(models.Model):
  event_block = models.ForeignKey(Block, on_delete=models.CASCADE)
  event_data = models.ForeignKey(BaseEvent)

However... BaseEvent with abstract=True does not physically exist but its children AlarmEvent and MessageEvent does. So I am not sure you can point BaseEvent as a ForeignKey. This post about generic foreign key may help.
Secondly about the structure of models. IMO, things can be simpler without abstract mother class. How about a model with category field?
CATEGORY = ( ('field1', 'field name 1'), ('field2', 'field name 2'), )
class Event(models.Model):
  category = models.CharField(max_length=10, choices=CATEGORY)
  # SOME OTHER FIELDS...

you can see a form of the model via django admin in default.

A: What is the reason for those separate tables? Are you going to query them directly? Are these events supposed to share data?
If answers to these questions are "I'm not sure" (or even better "no") then how about (instead of creating separate tables) you keep all the data on Event model directly? Something like
class Event(models.Model):
    #id auto-generated primary_key
    event_block = models.ForeignKey(Block, on_delete=models.CASCADE)
    event_data = models.TextField()

and keep the data in event_data field in serialized format (e.g. JSON). Or you can use some plugin, e.g. https://github.com/bradjasper/django-jsonfield for JSONField.
Some common fields can be separated, for example:
class Event(models.Model):
    #id auto-generated primary_key
    event_block = models.ForeignKey(Block, on_delete=models.CASCADE)
    event_type = models.CharField(max_length=2)
    event_data = models.TextField()


text:
Q: Convering CSV to XLS with out consuming to much memory I need to convert a CSV file into a XLSX file with and then upload the XLSX file into a S3 bucket. Currently I am using pandas to convert the CSV file into XLSX.
df.to_excel('query_set.xlsx')

This works fine for small dataset but fails for large dataset. I am executing my code in a server with 2GB of RAM.
So, how can I convert CSV into XLSX format with out consuming too much memory??

A: from openpyxl import Workbook
import csv

wb = Workbook()
ws = wb.active
with open('BIG.csv', 'r') as f:
    for row in csv.reader(f):
        ws.append(row)
wb.save('BIG.xlsx')

Try using this


text:
Q: LWJGL - Rotating the matrix produces an unnecessary roll I am using LWJGL, with VAOs VBOs and GLSL Shaders to create a Block world.
I started work on the FreeFly camera and I have been having trouble.
This is the way I am rotating my camera:
    Matrix4f modelMatrix = new Matrix4f(); //ROTATION
    Matrix4f viewMatrix = new Matrix4f(); //TRANSLATION

     //ROTATE
    Matrix4f.rotate(this.degreesToRadians(game.getGameDisplay().getGameCamera().roll()), new Vector3f(0, 0, 1),
            modelMatrix, modelMatrix); //ROTATE around Z
    Matrix4f.rotate((float) Math.toRadians(game.getGameDisplay().getGameCamera().yaw()), new Vector3f(0, 1, 0),
            modelMatrix, modelMatrix); //ROTATE around Y
    Matrix4f.rotate((float) Math.toRadians(game.getGameDisplay().getGameCamera().pitch()), new Vector3f(1, 0, 0),
            modelMatrix, modelMatrix); //ROTATE around X

    // Translate camera [*-1 because For some reason the world is inverted.. ill fix this later]
    Matrix4f.translate(new Vector3f(game.getGameDisplay().getGameCamera()
            .x()*-1, game.getGameDisplay().getGameCamera()
            .y()*-1, game.getGameDisplay().getGameCamera()
            .z()*-1), viewMatrix, viewMatrix); //TRANSLATE TO X Y Z

In the shaders this is how I am applying the rotation and translation:
#version 150 core

uniform mat4 projectionMatrix; //PROJECTION
uniform mat4 viewMatrix; //TRANSLATION
uniform mat4 modelMatrix; //ROTATION

in vec4 in_Position;
in vec4 in_Color;
in vec3 in_TextureCoord;//NOT USED

out vec4 pass_Color;
out vec3 pass_TextureCoord;//NOT USED

void main(void) {
    gl_Position = in_Position;
    // Override gl_Position with our new calculated position
    gl_Position = projectionMatrix  * modelMatrix * viewMatrix * in_Position;

    pass_Color = in_Color;
    pass_TextureCoord = in_TextureCoord;
}

And this for some reason produces a slight roll when I move my mouse up and down.. the roll intensifies when I start moving around the world.
I tried not rotating around the Z axis yet I am still getting a roll which is weird. It doesn't make sense that when I comment out the rotate of the Mat4f Z axis roll one it still gives me the roll as I am never rotating it around that axis... (This is why I assume that my movement and mouse code works well and the problem lays somewhere else)
Could anyone figure out why I am getting this weird roll issue?

A: The problem was that I was rotating the Matrix in the WRONG ORDER.
First it needs to be PITCH only then you rotate YAW because otherwise PITCH will translate to a ROLL instead of a PITCH when your YAW value is not 0.

A: OpenGl uses premultiplication to apply matrices, not post like you supposed it would. I.e. the last matrix you set is the first that will be applied.
You will have to change the order in which you apply the matrices.


text:
Q: python FileNotFoundError: [Errno 2] with absolute path and file exists I'm running a Python script as a Kubernetes job. But I'm having the next issue. I've already tried with chmod -R 777 /home/vagrant/ but it doesn't make the script run successfully.
Traceback (most recent call last):
  File "app.py", line 39, in <module>
    main()
  File "app.py", line 28, in main
    config.load_kube_config(config_file=kubeconfig)
  File "/usr/local/lib/python3.6/site-packages/kubernetes/config/kube_config.py", line 470, in load_kube_config
    config_persister=config_persister)
  File "/usr/local/lib/python3.6/site-packages/kubernetes/config/kube_config.py", line 427, in _get_kube_config_loader_for_yaml_file
    with open(filename) as f:
FileNotFoundError: [Errno 2] No such file or directory: '/home/vagrant/.kube/config'

As you can see the script fails supousedly because such file doesn't exists, but when I do an ls the file shows that it does exists.
vagrant@vagrant:/vagrant/podsLister$ kubectl delete job pod-lister
job.batch "pod-lister" deleted
vagrant@vagrant:/vagrant/podsLister$ ls /home/vagrant/.kube/
cache  config  http-cache

A: The problem is that the script is running inside a Docker container. That container has its own filesystem, not the filesystem of whatever machine happens to be hosting it. That is, in fact, most of the point of containers: they act like an isolated, separate computer, without you needing an actual separate computer.
The solution is a little less obvious, because it's not clear why you expected this to work, or what you're trying to do. Things that might make sense include:

*

*Changing your docker build script to copy the file into the container.

*Setting up host file sharing, so part of the real machine's filesystem is available to containers, then making the container mount that.

*Setting up "normal" file sharing, so part of the real machine's filesystem is available to anyone on the network, then making the container mount that.

*Using some higher-level feature like Kubernetes ConfigMaps to expose the file to containers.


text:
Q: specflow table.CreateSet mapping column name mismatches I am using specflow and  have a simple table:
FirstName | Surname|
Bob       | Dylan  |

and a class as follows:
public class Person{
  public string FirstName {get;set;}
  public string LastName {get;set;}
}

and the code i want to run is:
var people = table.CreateSet<Person>();

Question:
How do I map surname from the table to LastName in the object?
Cheers

A: Currently (as of SpecFlow 2.2.1) this is not possible.
But we got a PR two weeks ago, that will add the possibility to specific a "mapping" between column name and property.
The code is here: https://github.com/techtalk/SpecFlow/pull/969
It is not fix that we will merge this PR, but currently there are no showstoppers for not doing this.
Feedback to this PR is welcomed!

A: Thanks to Andreas Willich who has said the ability to add the alias will be added in a future release.
Until then, i have looked at the signatures for the methods and it does allow you to specify a function which will allow a hard coded mapping as follows which isn't the clean solution i was looking for but it fixed what i needed it to do:
    var people = table.CreateSet<Person>(ConvertMethod);

..... //return type is the same as you want and method takes a Tablerow as a parameter
    public static Person ConvertMethod(TableRow row)
    {
        return new Person()
        {
            FirstName = row["firstName"],
            LastName = row["surname"]
        };
    }


text:
Q: inverse gaussian glm residual deviance I am currently modelling crash severity data with an inverse gaussian glm with a log link. I read that
model residual deviance ~ $\chi^2_{n-p}$
Would there be an obvious reason why the residual deviance is so low and far from $n-p$?
Call:
glm(formula = cost ~ points + age + metro_area,
    family = inverse.gaussian(link = "log"), data = data[data$cost > 0, ])

Deviance Residuals:
      Min         1Q     Median         3Q        Max
-0.076370  -0.015587  -0.008113  -0.000530   0.023887

Coefficients:
                              Estimate Std. Error t value Pr(>|t|)
(Intercept)                   9.762717   0.091166 107.087  < 2e-16 ***
points                        0.119757   0.022237   5.386 7.48e-08 ***
age                           0.013409   0.001778   7.544 5.21e-14 ***
metro_area noMetro            0.301689   0.050476   5.977 2.40e-09 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(Dispersion parameter for inverse.gaussian family taken to be 8.679275e-05)

    Null deviance: 1.3357  on 6372  degrees of freedom
Residual deviance: 1.3274  on 6369  degrees of freedom
AIC: 143717

Number of Fisher Scoring iterations: 22

```

A: The residual deviance from an inverse Gaussian glm is proportional to a chisquared random variable, not equal to it.
Inverse-Gaussian glms and Gaussian glms share the property that the residual deviance would be exactly distributed as $\sigma^2 \chi^2_n$, where $\sigma^2$ is the dispersion parameter, if the link-linear model is correctly specified and the regression coefficients could be estimated perfectly without any sampling error.
After allowing for estimation uncertainty of the regression coefficients, the fitted residual deviance is approximately distributed as $\sigma^2 \chi^2_{n-p}$ where $p$ is the dimension of the design matrix, in your case the number of covariates plus 1 for the intercept giving $p=4$.
The dispersion $\sigma^2$ is analogous to the variance for a normal linear regression. It can take any positive value at all, and there is no reason why it should be near to 1. For your data, the R output shows that the dispersion is estimated to be
$$\hat\sigma^2 = 0.00008679275.$$
The dispersion value partly just reflects the scale on which your response variable is measured. If you express your cost variable in terms of (i) cents, (ii) dollars, (iii) thousands of dollars or (iv) millions of dollars, then the estimated dispersion will change proportionally. Multiplying all your cost values by a constant will decrease the dispersion and the residual deviance by the same constant (without changing the coefficients or standard errors or p-values for any of your covariates). Your cost values appear to be about 20,000 (=exp(9.76)), so it is no surprise that the dispersion is roughly 1/20,0000.
For more details about inverse-Gaussian glms and examples in R you could consult the two references below.
References
Dunn P.K., Smyth G.K. (2018) Chapter 11: Positive Continuous Data: Gamma and Inverse Gaussian GLMs. In: Generalized Linear Models With Examples in R. Springer Texts in Statistics. Springer, New York, NY.
https://link.springer.com/book/10.1007/978-1-4419-0118-7
Giner, G, and Smyth, GK (2016). statmod: probability calculations for the inverse Gaussian distribution. R Journal 8(1), 339-351.
https://journal.r-project.org/archive/2016/RJ-2016-024/


text:
Q: How do subsequent steps follow? (Divergence and partial derivatives) Let $(x,y)$ evolve to $(X,Y)$ under the velocity field $\vec v=(u,v)$ in time $t$. Thus, $$X=X(x,y,t), Y=Y(x,y,t), t=t$$
Then, $$J(x,y,t)=
\begin{bmatrix}
  \frac{\partial X}{\partial x} &
    \frac{\partial X}{\partial y} &
    \frac{\partial X}{\partial t} \\[1ex] % <-- 1ex more space between rows of matrix
  \frac{\partial Y}{\partial x} &
    \frac{\partial Y}{\partial y} &
    \frac{\partial Y}{\partial t} \\[1ex]
  \frac{\partial t}{\partial x} &
    \frac{\partial t}{\partial y} &
    \frac{\partial t}{\partial t}
\end{bmatrix}$$
$$=\begin{bmatrix}
  \frac{\partial X}{\partial x} &
    \frac{\partial X}{\partial y}\\[1ex]
  \frac{\partial Y}{\partial x} &
    \frac{\partial Y}{\partial y}
\end{bmatrix}$$
Now $\frac{\partial J}{\partial t}=\frac{\partial u}{\partial x}\frac{\partial Y}{\partial y}+\frac{\partial X}{\partial x}\frac{\partial v}{\partial y}-\frac{\partial u}{\partial y}\frac{\partial Y}{\partial x}-\frac{\partial X}{\partial y}\frac{\partial v}{\partial x}$.
Thus,  $\frac{\partial J}{\partial t}$ is the trace of matrix $\begin{bmatrix}
  \frac{\partial u}{\partial x} &
    \frac{\partial u}{\partial y}\\[1ex]
  \frac{\partial v}{\partial x} &
    \frac{\partial v}{\partial y}
\end{bmatrix}.\begin{bmatrix}
  \frac{\partial Y}{\partial y} &
    -\frac{\partial X}{\partial y}\\[1ex]
  -\frac{\partial Y}{\partial x} &
    \frac{\partial X}{\partial x}
\end{bmatrix}=\begin{bmatrix}
  \frac{\partial u}{\partial X} &
    \frac{\partial u}{\partial Y}\\[1ex]
  \frac{\partial v}{\partial X} &
    \frac{\partial v}{\partial Y}
\end{bmatrix}.J(x,y,t)$
Therefore, $\frac{\partial J}{\partial t}=(\nabla.\vec v)J$.
Now how did the steps after "trace of matrix" conclude? Also, why are we taking gradient with respect to $X,Y$ and not $x,y$ in the last step?


text:
Q: Knockout: objects and foreach Say if I have the following object (for example, pulled from a JSON file):
{
   "groups": [
       {
           "name":"groupa",
           "shirts":[
               {
                   "name":"foo1", "color": "blue",  "size": "small"
               },
               {
                   "name":"foo2", "color": "green",  "size": "large"
               },
               {
                   "name":"foo3", "color": "red",  "size": "medium"
               }
           ]
       },

       {
           "name":"groupb",
           "shirts":[
               {
                   "name":"foo1", "color": "blue",  "size": "x-large"
               },
               {
                   "name":"foo2", "color": "purple",  "size": "large"
               },
               {
                   "name":"foo3", "color": "pink",  "size": "xx-large"
               }
           ]
       }
   ]
}

I understand how to use observableArrays, which contain correctly mapped data from a single object. But what if i need an observableArray to contain data from more than one object?
Output could be similar to below:

groupa

foo1 - large blue

foo2 - small red

groupb

bar1 - medium purple

bar2 - x-large white

groupc

foobar1 - large black

foobar2 - small green

What I don't understand, is how to create this using one observable array?
I've tried assigning each of the groups to their own observableArray, and then the group names to another array, and then foreach the group names and then manually go through them - but that seems a mess.
What's the cleanest, most logical way?

A: So there was a blatantly obvious way to do this, simply map an observableArray against each group which contains the shirts. Like this:
function shirt_group_assign(item) {
    this.name = item.name;
    this.shirts = ko.observableArray([]);

    shirts_mapped = $.map(item.shirts, function(item) {
        return new shirt_assign(item);
    });

    this.shirts = shirts_mapped;
}

There's a working example here.


text:
Q: How do I call a different function for each TextField in a UITableView (Swift)? I have a UITableView and my prototype cell consists of a label and a TextField. I also have a class MyClass that contains functions func1, func2, fun3, ... I have several ViewControllers that use the same tableViewCell prototype. Each viewController will have an instance of MyClass, called inst1, inst2, and inst3. When I enter text into FirstViewController's TableView I want each row to call a function from the instance of MyClass that corresponds to the row.
So when I enter text into row 1 on the FirstViewController I want to pass the data entered into the textField into func1 of inst1. When data is entered into row 2 of FirstViewController I want the data in the textfield to be passed into func2 of inst1. And so on and so forth down the rows.
I am very new to this and would really appreciate some help figuring out how to do this. Let me know if that doesn't make sense and I can try to rephrase it. I really need help with this. Thanks in advance!
*Updated question to show my code
Below is my Code:
FirstViewController.swift
extension FirstViewController: MyCellDelegate {
    func MyCell(_ cell: UITableViewCell, didEnterText text: String) {
        if let indexPath = tableView.indexPath(for: cell) {
            if (indexPath.hashValue == 0) {
                inst1.func1(one: text)
            }
            if (indexPath.hashValue == 1) {
                inst1.func2(two: text)
            }
        }
        totalText.text = inst1.getMyTotal()
    }
}

import UIKit

class FirstViewController: UIViewController,  UITableViewDataSource, UITableViewDelegate {
    let inst1 = MyClass()
    @IBOutlet weak var totalText: UILabel!
    @IBOutlet weak var tableView: UITableView!

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 11
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myTableCell") as! TableViewCell
        let text = cell.cellData[indexPath.row]
        cell.myTextField.tag = indexPath.row
        cell.delegate = self
        cell.myLabel.text = text
        cell.myTextField.placeholder = text
        return cell
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.dataSource = self
        tableView.delegate = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

TableViewCell.swift
import UIKit
protocol MyCellDelegate: class {
    func MyCell(_ cell: UITableViewCell, didEnterText text: String)
}

class TableViewCell: UITableViewCell {
    weak var delegate: MyCellDelegate?

    public var cellData: [String] = ["1","2","3","4","5","6","7","8","9","10","11"]

    @IBOutlet weak var myLabel: UILabel!

    @IBOutlet weak var myTextField: UITextField!

    override func awakeFromNib() {
        super.awakeFromNib()
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
    }
}

When I set a breakpoint in the FirstViewController extension it never runs that code.

A: In WillDisplayCell add the tag to the UITextField. Also create a protocol to notify the Corrosponding viewController and set itself as the delegate here.
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
 let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier")
 cell.textField.tag = indexPath.row
 cell.delegate = self
 }

The protocol in your cell class will look something like this
protocol MyCellDelegate: class {
func MyCell(_ cell: UITableViewCell, didEnterText text: String)
}

class MyCell: UITableViewCell, UITextFieldDelegate {
weak var delegate: MyCellDelegate?
override fun awakeFromNib() {
 super.awakeFromNib()
 textField.delegate = self
 }
//All the remaining code goes here

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
textField.resignFirstResponder()
delegate?.MyCell(self, didEnterText: textField.text! )
return true
}
}

Now again in your FirstViewController which has conformed to be its delegate do this
extension FirstViewController: MyCellDelegate {
 func MyCell(_ cell: UITableViewCell, didEnterText text: String) {
 if let indexPath = tableView.indexPathForCell(cell) {
   // call whichever method you want to call based on index path
  }
 }


text:
Q: Probability of selecting 1 of n-i elements in a set of size n when choosing k elements Given a set of $n$ elements, I will choose uniformly at random $k$ distinct elements.
First: Given a set $S$ of $i$ distinct elements from $n$, what is the probability that at least one of the $k$ elements will not be in $S$?

A: $1-$the probability that all of them are in $S$ so $1-\frac{\left({i\atop k}\right)}{\left({n\atop k}\right)}$. Here
$\left({i\atop k}\right)=0$ if $i<k$.


text:
Q: TSQL - Split and Concat string Code:
DECLARE @ColumnNames NVARCHAR(MAX) = N'[Id],[FirstName],[LastName]' ;

Desired Output:
[T1].[Id] = [T2].[Id] AND [T1].[FirstName] = [T2].[FirstName] AND [T1].[LastName] = [T2].[LastName]

Goal:
To split the string at the comma and turn it into a JOIN ON clause. So "[Id]" would turn into "[T1].[Id] = [T2].[Id]" - and if there are more tha one columns (comma delimted), it would append those fields in the original order. Please refer to the "Desired Output" for better understanding. I can use STRING_SPLIT to split the values, but not sure how to stuff them the way I need..

A: This is just an answer to your question. If I understand you correctly and you want to generate a JOIN clause for your dynamic statement, you have at least two options:

*

*use STRING_SPLIT(), but if you want to "... append those fields in the original order ...", this is not an option, because the order of the substrings is not guaranteed

*transform input string into a valid JSON and use OPENJSON().

T-SQL using STRING_SPLIT():
DECLARE @ColumnNames NVARCHAR(MAX) = N'[Id],[FirstName],[LastName]'
DECLARE @join nvarchar(max) = N''
SELECT @join = STUFF(
   (
   SELECT
      CONCAT(
         N' AND [t1].',
         s.[value],
         N'=[t2].',
         s.[value]
      )
   FROM STRING_SPLIT(@ColumnNames, N',') s
   FOR XML PATH('')
   ),
   1, 5, N'')
PRINT @join

T-SQL using OPENJSON():
DECLARE @ColumnNames NVARCHAR(MAX) = N'[Id],[FirstName],[LastName]'
DECLARE @join nvarchar(max) = N''
SELECT @join = STUFF(
   (
   SELECT
      CONCAT(
         N' AND [t1].',
         j.[value],
         N'=[t2].',
         j.[value]
      )
   FROM OPENJSON(CONCAT(N'["', REPLACE(STRING_ESCAPE(@ColumnNames, 'json'), N',', N'","'), N'"]')) j
   ORDER BY [key]
   FOR XML PATH('')
   ),
   1, 5, N'')
PRINT @join

Output:
[t1].[Id]=[t2].[Id] AND [t1].[FirstName]=[t2].[FirstName] AND [t1].[LastName]=[t2].[LastName]


text:
Q: IO::Pipe - close() does not set $? My understanding is that closing the handle for an IO::Pipe object should be done with the method ($fh->close) and not the built-in (close($fh)).
The other day I goofed and used the built-in out of habit on a IO::Pipe object that was opened to a command that I expected to fail. I was surprised when $? was zero, and my error checking wasn't triggered.
I realized my mistake. If I use the built-in, IO:Pipe can't perform the waitpid() and can't set $?. But what I was surprised by was that perl seemed to still close the pipe without setting $? via the core.
I worked up a little test script to show what I mean:
use 5.012;
use warnings;

use IO::Pipe;

say 'init pipes:';
pipes();
my $fh = IO::Pipe->reader(q(false));
say 'post open pipes:';
pipes();

say 'return: ' . $fh->close;
#say 'return: ' . close($fh);
say 'status: ' . $?;
say q();

say 'post close pipes:';
pipes();

sub pipes
   {
   for my $fd ( glob("/proc/self/fd/*") )
      {
      say readlink($fd) if -p $fd;
      }
   say q();
   }

When using the method it shows the pipe being gone after the close and $? is set as I expected:
init pipes:

post open pipes:
pipe:[992006]

return: 1
status: 256

post close pipes:

And, when using the built-in it also appears to close the pipe, but does not set $?:
init pipes:

post open pipes:
pipe:[952618]

return: 1
status: 0

post close pipes:

It seems odd to me that the built-in results in the pipe closure, but doesn't set $?. Can anyone help explain the discrepancy?
Thanks!

A: If you look at the code for IO::Handle (of which IO::Pipe::End is a sub-class), you will see the following:
sub close {
    @_ == 1 or croak 'usage: $io->close()';
    my($io) = @_;

    close($io);
}

It looks like $fh->close just calls close $fh. Of course, we should not be peeking behind the curtain.
We can see after IO::Pipe does a close $fh (behind the scenes), it then does a waitpid:
package IO::Pipe::End;

our(@ISA);

@ISA = qw(IO::Handle);

sub close {
    my $fh = shift;
    my $r = $fh->SUPER::close(@_);   # <-- This just calls a CORE::close

    waitpid(${*$fh}{'io_pipe_pid'},0)
        if(defined ${*$fh}{'io_pipe_pid'});

    $r;
}

Also  interesting is this from the close Perldoc:

If the filehandle came from a piped open, close returns false if one of the other syscalls involved fails or if its program exits with non-zero status. If the only problem was that the program exited non-zero, $! will be set to 0 .
Closing a pipe also waits for the process executing on the pipe to exit --in case you wish to look at the output of the pipe
afterwards--and implicitly puts the exit status value of that command
  into $? and ${^CHILD_ERROR_NATIVE} .

That answers your question right there.

A:
But what I was surprised by was that perl seemed to still close the pipe without setting $? via the core.

Why would it? It has no way to know the process at the other end is a child, much less one for which the program should wait. Since it has no reason to call waitpid, $? isn't going to get set.
In fact, I doubt it wait for the process at the other end of the pipe even if it wanted to, because I doubt there's a way of obtaining the pid of the process at the other end of the pipe, because it's actually possible for there to be multiple processes at the other end of the pipe.
IO::Pipe::close only calls waitpid when IO::Pipe is used to "open a process".
Similarly, close only calls waitpid when open is used to "open a process".
A process "opened" using one method cannot be closed by the other.

A: It turns out that my confusion stems from a flawed assumption that the disappearing pipe coincided with a complete process termination. That appears to not be the case, as the process is still available for a wait().
> perl -MIO::Pipe -le 'my $io = IO::Pipe->reader(q(false)); close($io); print $?; print wait(); print $?'
0
8857
256


text:
Q: break long characters by "-" and identify the unique components by group Suppose you have a transaction data set with products purchased by customers. You know the total skus (which unique product they buy for each order). But you want to know the unique sku for the lifetime of the user. Say, I buy "apple" for the first time ever today, then apple is a NEW sku. But when I buy "apple" amd "banana" again. Then apple is not a new sku but banana is (if first time purchase).
data
user_id<-c(1,1,1,2,3,4,4)
          order_date<-c("2/9/2016",
                    "11/19/2015",
                     "12/30/2016",
                     "9/27/2016",
                    "12/10/2016",
                     "11/5/2016",
                     "1/1/2017")
sku<-c("262-264-280","280-123","510","6251-16990","9227-14572","9227-14572","280")
dt<-data.frame(user_id,order_date,sku)

Output

update: I typed "user_id" as "order_id"

A: A data.table possibility, using the strings split by -, and checking for new unique values in each row via a set union and Reduce(..., accumulate=TRUE). The count of new values is then a difference between each successive row:
library(data.table)
setDT(dt)
dt[, sku := as.character(sku)]
dt[,
   total := lengths(Reduce(union, strsplit(sku, "\\-"), accumulate=TRUE)),
   by=user_id
  ]
dt[, new := c(total[1], diff(total)), by=user_id]

dt
#   user_id order_date         sku total new
#1:       1   2/9/2016 262-264-280     3   3
#2:       1 11/19/2015     280-123     4   1
#3:       1 12/30/2016         510     5   1
#4:       2  9/27/2016  6251-16990     2   2
#5:       3 12/10/2016  9227-14572     2   2
#6:       4  11/5/2016  9227-14572     2   2
#7:       4   1/1/2017         280     3   1

A: A possible tidyverse way:
library(dplyr)
library(tidyr)

dt %>%
  separate_rows(sku, sep = "-") %>%
  mutate(order_date = as.Date(as.character(order_date), "%m/%d/%Y")) %>%
  group_by(order_id, sku) %>%
  arrange(order_id, order_date) %>%
  mutate(idx = row_number() * (row_number() == 1)) %>%
  group_by(order_id, order_date) %>%
  summarise(sku = paste(sku, collapse = "-"),
            `number of new sku purchase` = sum(idx)) %>%
  group_by(order_id) %>%
  mutate(`total number of sku` = cumsum(`number of new sku purchase`))

A: Here is one option based on unlist(strsplit(dt$sku,'-')) the current sku then compare it with the previous skus
library(dplyr)
library(purrr)
library(tidyr)
dt %>%
  nest(-user_id) %>%
  mutate(NNSP = map(data, ~map_dbl(1:length(.x$sku), function(y) {
                                   #browser()
                                   ynow <- unlist(strsplit(as.character(.x$sku)[y],'-'))
                                   yprev <- unique(unlist(strsplit(as.character(.x$sku[1:y-1]),'-')))
                                   length(ynow[!ynow %in% yprev])
                                   })),
         TotNNSP = map(NNSP, ~cumsum(.x))) %>%
  unnest()

# A tibble: 7 x 5
   user_id  NNSP TotNNSP order_date sku
      <dbl> <dbl>   <dbl> <fct>      <fct>
1        1     3       3 2/9/2016   262-264-280
2        1     1       4 11/19/2015 280-123
3        1     1       5 12/30/2016 510
4        2     2       2 9/27/2016  6251-16990
5        3     2       2 12/10/2016 9227-14572
6        4     2       2 11/5/2016  9227-14572
7        4     1       3 1/1/2017   280

Using @thelatemail's Reduce and lengths combination, we can do:
library(dplyr)
setdiff2 <- function(x, y) y[!y %in% x]

dt %>%
   group_by(user_id) %>%
   mutate(sku = as.character(sku),
          NNSP = lengths(Reduce(setdiff2, strsplit(sku,'-'), accumulate = TRUE)),
          Tot_NNSP = cumsum(NNSP))

A: Here's a base solution that is similar to @thelatemail:

dt$sku <- as.character(dt$sku)
dt$n_skus <- ave(dt$sku
                 , dt$user_id
                 , FUN = function (sku_f) {
                   sapply(
                     Reduce(union, strsplit(sku_f, '-', fixed = T),  accumulate = T)
                     , length)
                   })

dt$n_skus <- as.integer(dt$n_skus)

dt$n_new <- ave(dt$n_skus
                , dt$user_id
                , FUN = function(n) c(n[1], diff(n)))

dt

  user_id order_date         sku n_skus n_new
1       1   2/9/2016 262-264-280      3     3
2       1 11/19/2015     280-123      4     1
3       1 12/30/2016         510      5     1
4       2  9/27/2016  6251-16990      2     2
5       3 12/10/2016  9227-14572      2     2
6       4  11/5/2016  9227-14572      2     2
7       4   1/1/2017         280      3     1

And here's a crazy, inefficient data.table solution that doesn't include the original sku field:
library(data.table)
setDT(dt)
dt[, strsplit(as.character(sku), '-'), by = .(user_id, order_date)
    ][, .SD[!duplicated(V1), .(n_new = .N), by = order_date], by = .(user_id)
      ][, n_total := cumsum(n_new), by = .(user_id)][]

Performance
@thelatemail's should scale up the best.
Unit: microseconds
           expr       min        lq       mean    median        uq     max neval
 argonaut_dplyr 10020.601 10247.851 10720.0709 10474.451 10770.751 16021.3   100
 thelatemail_dt  1954.501  2072.101  2385.8019  2303.001  2436.202  5807.0   100
#base is always fastest with 7 rows, it would be outstripped by @thelatemail very quickly
      cole_base   651.501   751.601   834.0299   772.201   794.752  6309.2   100
    cole_bad_dt  7006.400  7355.200  7757.9991  7668.401  7958.651 12708.0   100
    purrr_A_sul 14575.501 14862.552 15566.4809 15033.201 15401.601 33263.3   100


text:
Q: Algorithm to Authenticate Online Operations I need an idea to develop a secure algorithm to authenticate online operations using PHP in the server and an Android app in the user's device.
What is the idea?
The user try to login in the system.
The server sends a confirmation request to user's device (Android).
The user sees the country, city, IP, browser and OS in the app, all about the login try, and if all this informations match he can clicks on confirm. The app will generate an 8 digit token based in this informations and send to server, the server will try to generate a token with the same informations and if both tokens match, the server accept the login try.
This is just one possible operation.
What do I need?
An universal algorithm to authenticate any online operation.
e.g.:
function generateRandonTokenUsingNParameters(){
    $args = func_num_args();
    $token = 12345678; //Start token

    for($i=0; $i < $args; $i++){
        $token = CRAZY_MATH_USING_ALL_PARAMETERS_TO_GENERATE_8_DIGITS_TOKEN($token, func_get_arg($i));
    }

    return $token; //Final token based in the informations of the operation

}

//LOGIN INFORMATION
$ip = "192.168.0.1";
$browser = "Chrome";
$city = "Los Angeles";
$country = "USA";
$os = "Windows";
$android_app_local_seed = "ab0982deb79a9d73b2e820";

//PRINTING LOGIN TOKEN
echo generateRandonTokenUsingNParameters($ip, $browser, $city, $country, $os, $android_app_local_seed);

What would you use in the CRAZY_MATH_USING_ALL_PARAMETERS_TO_GENERATE_8_DIGITS_TOKEN() function?
Thanks.

A: you can concatenate all information as string and then compute sha1 hash on this string. After it you can just get 8 characters from it.


text:
Q: How to apply filter on a dropdownbottom I have the following code that populates a DropdownButton, but I am not able to filter content when I am editing.
I need help because I could not understand the error and how to correct the problem to make the filter.
I tried several filters without success. The filter applied below has the following error:

Failed assertion: line 609 pos 15: 'items == null || items.isEmpty ||
  value == null || items.where ((DropdownMenuItem  item) =>
  item.value == value) .length == 1 ': is not true.

This error comes from the filter below:
if (widget.filialID != 0) {
  _select = FilialModel(key: widget.filialID);
}

I could not find a solution to the problem. Please help. Thank you.
import 'package:flutter/material.dart';
import 'package:onex_qa/data/database.dart';
import 'package:onex_qa/models/filial_model.dart';

class DropFilialDb extends StatefulWidget {
  int filialID;
  DropFilialDb({Key key, this.filialID}) : super(key: key);
  @override
  _DropFilialDbState createState() => _DropFilialDbState();
}

class _DropFilialDbState extends State<DropFilialDb> {
  final String _tipo = 'Filial';
  FilialModel _select;
  final _listDb = DatabaseDb().getAllFilialList();

  @override
  void initState() {
    super.initState();

    if (widget.filialID != 0) {
      _select = FilialModel(key: widget.filialID);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.fromLTRB(4, 0, 2, 0),
      child: Theme(
        data: Theme.of(context).copyWith(
          canvasColor: Theme.of(context).dialogBackgroundColor,
        ),
        child: FutureBuilder<List<FilialModel>>(
          future: _listDb,
          builder: (BuildContext context,
              AsyncSnapshot<List<FilialModel>> snapshot) {
            if (!snapshot.hasData) return CircularProgressIndicator();
            return DropdownButton<FilialModel>(
              items: snapshot.data.map((FilialModel value) {
                return new DropdownMenuItem<FilialModel>(
                  value: value,
                  child: new Text(value.filial),
                );
              }).toList(),
              style: TextStyle(color: Theme.of(context).primaryColorDark),
              elevation: 3,
              isExpanded: true,
              hint: Text("Selecione ${_tipo}",
                  style: TextStyle(
                      color: Theme.of(context).primaryColorDark, fontSize: 17)),
              value: _select == null ? null : _select,
              onChanged: (FilialModel value) {
                if (value == null) {
                  _select = null;
                } else {
                  setState(() {
                    _select = value;
                    widget.filialID = _select.key;
                  });
                }
              },
            );
          },
        ),
      ),
    );
  }
}

A: My logical assumption is that FilialModel does not have equality operator defined, hence comparing two models always returns false. Even if they are the same models.
Try defining equality operator in your FilialModel class. That might fix the items.where part of the assertion that throws the error.
e.g.
class FilialModel /* extends ... */ {
  // ...,

  // Compares `key` property of current object (this) and the other object (obj)
  bool operator ==(obj) => obj is FilialModel && obj.key == this.key;

  @override
  int get hashCode => key.hashCode; // This has to be overridden too. You might want to define more complex logic here.
}

Let me know if this helped.


text:
Q: How can I "touch" a file from within an InnoSetup script? How can I "touch" a file, i.e. update its' last modified time to the current time, from within an InnoSetup (Pascal) script?

A: Here's the code snippet for the TouchFile function:
[Code]
function CreateFile(
    lpFileName             : String;
    dwDesiredAccess        : Cardinal;
    dwShareMode            : Cardinal;
    lpSecurityAttributes   : Cardinal;
    dwCreationDisposition  : Cardinal;
    dwFlagsAndAttributes   : Cardinal;
    hTemplateFile          : Integer
): THandle;
#ifdef UNICODE
 external 'CreateFileW@kernel32.dll stdcall';
#else
 external 'CreateFileA@kernel32.dll stdcall';
#endif

procedure GetSystemTimeAsFileTime(var lpSystemTimeAsFileTime: TFileTime);
 external 'GetSystemTimeAsFileTime@kernel32.dll';

function SetFileModifyTime(hFile:THandle; CreationTimeNil:Cardinal; LastAccessTimeNil:Cardinal; LastWriteTime:TFileTime): BOOL;
external 'SetFileTime@kernel32.dll';

function CloseHandle(hHandle: THandle): BOOL;
external 'CloseHandle@kernel32.dll stdcall';

function TouchFile(FileName: String): Boolean;
const
  { Win32 constants }
  GENERIC_WRITE        = $40000000;
  OPEN_EXISTING        = 3;
  INVALID_HANDLE_VALUE = -1;
var
  FileTime: TFileTime;
  FileHandle: THandle;
begin
  Result := False;
  FileHandle := CreateFile(FileName, GENERIC_WRITE, 0, 0, OPEN_EXISTING, $80, 0);
  if FileHandle <> INVALID_HANDLE_VALUE then
  try
    GetSystemTimeAsFileTime(FileTime);
    Result := SetFileModifyTime(FileHandle, 0, 0, FileTime);
  finally
    CloseHandle(FileHandle);
  end;
end;


text:
Q: Cookie creating URL behaves different inside PHP CURL code i have used the below url to set cookies in my browser
http://localhost/setc.php?userid=123&panelid=1

now i have used php curl to do it(writing the code inside another script), but it does not work(doesnot set a cookie) at the moment
can any expert of this, spot what is the error with my code using curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://localhost/setc.php?userid=123&panelid=1');
curl_setopt($curl, CURLOPT_COOKIE, "Cookie saved");
curl_exec($curl);
curl_close($curl);

and let me know where to edit in this


text:
Q: Android Facebook SDK with fragment I'm trying to follow the facebook tutorial here https://developers.facebook.com/docs/getting-started/facebook-sdk-for-android/3.0/ but i'm getting an error with onActivityResult any ideas? The only difference between mine and theirs is mine is a fragment instead.
    package com.projectcaruso.naturalfamilyplaning;

    import com.facebook.*;
    import com.facebook.model.*;
    import com.projectcaruso.naturalfamilyplanning.R;

    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.content.Context;
    import android.content.Intent;

    public class facebooklogin  extends Fragment{

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
             View view = inflater.inflate(R.layout.fragment_login, container, false);

            // start Facebook Login
            Session.openActiveSession(getActivity(), this, true, new Session.StatusCallback() {

              // callback when session changes state
              @Override
              public void call(Session session, SessionState state, Exception exception) {
                if (session.isOpened()) {

                  // make request to the /me API
                  Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                    // callback after Graph API response with user object
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                      if (user != null) {
                          Context context = getActivity();
                          Toast.makeText(context, "Hello " + user.getName() + "!", Toast.LENGTH_LONG).show();
                      }
                    }
                  });
                }
              }
            });

            return view;
          }

          @Override
          public void onActivityResult(int requestCode, int resultCode, Intent data) {
              super.onActivityResult(requestCode, resultCode, data);
              Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
          }

    }

EDIT:
I changed this to getActivity() but now i get this
05-14 17:10:23.904: E/AndroidRuntime(791): FATAL EXCEPTION: main
05-14 17:10:23.904: E/AndroidRuntime(791): java.lang.NullPointerException: Argument 'applicationId' cannot be null
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.facebook.internal.Validate.notNull(Validate.java:29)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.facebook.Session.<init>(Session.java:224)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.facebook.Session.<init>(Session.java:213)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.facebook.Session$Builder.build(Session.java:1454)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.facebook.Session.openActiveSession(Session.java:863)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.facebook.Session.openActiveSession(Session.java:828)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.projectcaruso.naturalfamilyplaning.facebookFragment.onCreateView(facebookFragment.java:29)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
05-14 17:10:23.904: E/AndroidRuntime(791):  at     android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.os.Handler.handleCallback(Handler.java:725)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.os.Looper.loop(Looper.java:137)
05-14 17:10:23.904: E/AndroidRuntime(791):  at android.app.ActivityThread.main(ActivityThread.java:5041)
05-14 17:10:23.904: E/AndroidRuntime(791):  at java.lang.reflect.Method.invokeNative(Native Method)
05-14 17:10:23.904: E/AndroidRuntime(791):  at java.lang.reflect.Method.invoke(Method.java:511)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-14 17:10:23.904: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-14 17:10:23.904: E/AndroidRuntime(791):  at dalvik.system.NativeStart.main(Native Method)

FYI this is in my manifest and so is the app_id in my string file.
meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"

manifest:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.projectcaruso.naturalfamilyplanning"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="14"
            android:targetSdkVersion="17" />

        <uses-permission android:name="android.permission.INTERNET"/>
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/app_id"/>

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.projectcaruso.naturalfamilyplaning.FragmentChange"
                android:configChanges="orientation|screenSize|screenLayout"
                android:theme="@style/Theme.Sherlock.Light.DarkActionBar"
                android:uiOptions="splitActionBarWhenNarrow" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name="com.projectcaruso.naturalfamilyplaning.UserSettingActivity" >
            </activity>
            <activity
                android:name="com.projectcaruso.naturalfamilyplaning.HistoryFragment"
                android:label="@string/title_activity_history_fragment" >
            </activity>
        </application>

    </manifest>

A: You have the  tag in the wrong place in your manifest.
It should be within the <Application> element but you have it outside of that element.
It should be:
<application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
   <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/app_id"/>
   ....
 </application>


text:
Q: Ubuntu upgrade left me with a blinking cursor after reboot I had the blinking cursor and no login after an upgrade from 18.04 to 19.04.
My 18.04 was working fine and I had wifi connected and working and all drivers installed. I remembered my username and password as well.
After the upgrade, I rebooted to find a blinking cursor and nothing else...

A: I fixed it though.
First, I used the CTRL+ALT+F2 key combination (Press the 3 together at the same time) to enter tty2
I logged in by typing my username without the computer name (just your username, not 'username@computername') and then my password.
Next, I updated my computer with 'sudo apt update' then 'sudo apt dist-upgrade'.
Last I entered 'sudo startx' and I logged in fine. I restarted and it started fine. I hope this helps!