text:
Q: Create new Application User After Submitting Form in ASP.NET MVC I have gone through my code several times and still cannot figure what I might be doing wrong.
In my ASP.NET MVC Application, I want to be able to create a new user after a form has being submitted through the View Model. Part of the information submitted through the view model will be used to Populate the ApplicationUser Model.
Here is my View Model
[Column(TypeName = "decimal(18,2)")]
    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "LoanAmount", ResourceType = typeof(Resources))]
    public decimal LoanAmount { get; set; }

    [Display(Name = "LoanPurpose", ResourceType = typeof(Resources))]
    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    public LoanPurpose LoanPurpose { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "FirstName", ResourceType = typeof(Resources))]
    public string FirstName { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "LastName", ResourceType = typeof(Resources))]
    public string LastName { get; set; }

    [Display(Name = "DateOfBirth", ResourceType = typeof(Resources))]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    public DateTime? DateOfBirth { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "StreetAddress", ResourceType = typeof(Resources))]
    public string Street { get; set; }

    [MaxLength(15)]
    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "City", ResourceType = typeof(Resources))]
    public string City { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "State", ResourceType = typeof(Resources))]
    public string State { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "ZIP", ResourceType = typeof(Resources))]
    public string ZipCode { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "Country", ResourceType = typeof(Resources))]
    public string Country { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "Phone", ResourceType = typeof(Resources))]
    public string Phone { get; set; }

    [Column(TypeName = "decimal(18,2)")]
    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "MonthlyHousingPayment", ResourceType = typeof(Resources))]
    public decimal MonthlyHousingPayment { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [Display(Name = "EmploymentStatus", ResourceType = typeof(Resources))]
    public EmploymentStatus EmploymentStatus { get; set; }

    [Column(TypeName = "decimal(18,2)")]
    [Display(Name = "IndividualYearlyIncome", ResourceType = typeof(Resources))]
    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    public decimal IndividualYearlyIncome { get; set; }

    [Column(TypeName = "decimal(18,2)")]
    [Display(Name = "AdditionalYearlyIncome", ResourceType = typeof(Resources))]
    public decimal? AdditionalYearlyIncome { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [EmailAddress(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "EmailInvalid")]
    [Display(Name = "Email", ResourceType = typeof(Resources))]
    public string Email { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [DataType(DataType.Password)]
    [StringLength(100, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "StringLength", MinimumLength = 4)]
    [Display(Name = "Password", ResourceType = typeof(Resources))]
    public string Password { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    [StringLength(20, ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "StringLength", MinimumLength = 4)]
    [Display(Name = "Username", ResourceType = typeof(Resources))]
    public string UserName { get; set; }

    [Required(ErrorMessageResourceType = typeof(ValidationResources), ErrorMessageResourceName = "PropertyValueRequired")]
    public bool AcceptCreditReportTerms { get; set; }

    public Guid ApplicationUserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }

Here is my Controller (CheckRateController)
// POST: CheckRate/Index
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Index(CheckYourRateViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser
            {
                FirstName = model.FirstName,
                LastName = model.LastName,
                UserName = model.UserName,
                PhoneNumber = model.Phone,
                DateOfBirth = model.DateOfBirth,
                State = model.State,
                Street = model.Street,
                City = model.City,
                Country = model.Country
            };

            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                // Add registered users to Customer role
                await _userManager.AddToRoleAsync(user.Id, "Customer");
            }

            var loanApplication = new Loan
            {
                LoanPurpose = model.LoanPurpose,
                LoanAmount = model.LoanAmount,
                EmploymentStatus = model.EmploymentStatus,
                MonthlyHousingPayment = model.MonthlyHousingPayment,
                IndividualYearlyIncome = model.IndividualYearlyIncome,
                AdditionalYearlyIncome = model.AdditionalYearlyIncome,
                ApplicationUserId = Guid.Parse(user.Id)
            };

            db.Loans.Add(loanApplication);
            db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }

        return View(model);
    }

And this is How my View Starts (Index.cshtml)

    @using (Html.BeginForm("Index", "CheckRate", FormMethod.Post))
    {
        @Html.AntiForgeryToken()

            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

@Resources.CheckYourRate

How much would you like to borrow?

                                    @Html.LabelFor(m => m.LoanAmount)

                                    @Html.TextBoxFor(m => m.LoanAmount, new { placeholder = @Resources.LoanAmount })
                                    $

                                @Html.ValidationMessageFor(model => model.LoanAmount, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.LoanPurpose)

                                    @Html.EnumDropDownListFor(model => model.LoanPurpose)

                                @Html.ValidationMessageFor(model => model.LoanPurpose, "", new { @class = "text-danger" })

Tell Us About Yourself

                                    Full Name

                                            @Html.TextBoxFor(m => m.FirstName, new { placeholder = @Resources.FirstName })

                                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })

                                            @Html.TextBoxFor(m => m.LastName, new { placeholder = @Resources.LastName })

                                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.DateOfBirth)

                                    @Html.TextBoxFor(m => m.DateOfBirth, new { placeholder = "Date of Birth (MM/DD/YYYY)" })

                                @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.Street)

                                    @Html.TextBoxFor(m => m.Street, new { placeholder = @Resources.StreetAddress })

                                @Html.ValidationMessageFor(model => model.Street, "", new { @class = "text-danger" })

                                    City & State

                                            @Html.TextBoxFor(m => m.City, new { placeholder = @Resources.City })

                                        @Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })

                                                @Html.TextBoxFor(m => m.State, new { placeholder = @Resources.State })

                                            @Html.ValidationMessageFor(model => model.State, "", new { @class = "text-danger" })

                                    Zip & Phone

                                            @Html.TextBoxFor(m => m.ZipCode, new { placeholder = @Resources.ZIP })

                                        @Html.ValidationMessageFor(model => model.ZipCode, "", new { @class = "text-danger" })

                                            @Html.TextBoxFor(m => m.Phone, new { placeholder = @Resources.PhoneNumber })

                                        @Html.ValidationMessageFor(model => model.Phone, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.MonthlyHousingPayment)

                                    @Html.TextBoxFor(m => m.MonthlyHousingPayment, new { placeholder = @Resources.MonthlyHousingPayment })

                                @Html.ValidationMessageFor(model => model.MonthlyHousingPayment, "", new { @class = "text-danger" })

What is your income?

                                    @Html.LabelFor(m => m.EmploymentStatus)

                                    @Html.EnumDropDownListFor(model => model.EmploymentStatus)

                                @Html.ValidationMessageFor(model => model.EmploymentStatus, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.IndividualYearlyIncome)

                                    @Html.TextBoxFor(m => m.IndividualYearlyIncome, new { placeholder = @Resources.IndividualYearlyIncome })
                                    $

                                @Html.ValidationMessageFor(model => model.IndividualYearlyIncome, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.AdditionalYearlyIncome)

                                    @Html.TextBoxFor(m => m.AdditionalYearlyIncome, new { placeholder = @Resources.AdditionalYearlyIncome })
                                    $

                                @Html.ValidationMessageFor(model => model.AdditionalYearlyIncome, "", new { @class = "text-danger" })

Save your information

                                    @Html.LabelFor(m => m.Email)

                                    @Html.TextBoxFor(m => m.Email, new { placeholder = @Resources.Email })

                                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.UserName)

                                    @Html.TextBoxFor(m => m.UserName, new { placeholder = @Resources.Username })

                                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })

                                    @Html.LabelFor(m => m.Password)

                                    @Html.PasswordFor(m => m.Password, new { placeholder = @Resources.Password })

                                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })

Check your rate in
 5 minutes

Get lower rates

Single monthly payments

Fixed terms—3 or 5 years*

The following documents contain important information, including your agreement to do business with
 Lendy electronically. By clicking the box below, you confirm that you agree by electronic signature to:

                the Credit Report Authorization, Terms of Use and Electronic Consent, Data Terms of Use & Prosper privacy policies.

                @Html.CheckBoxFor(m => m.AcceptCreditReportTerms)

            @Html.ValidationMessageFor(model => model.AcceptCreditReportTerms, "", new { @class = "text-danger" })

            <input type="submit" class="btncus" value="Check your rates" />

    }

A: Try updating BeginForm to look something like this...
Html.BeginForm("Index", "Home", FormMethod.Post)

A: I have noticed that you are checking whether the model state is valid or not in the controller method using 'ModelState.IsValid' property with if condition and all your code inside that if condition.
Check by adding a breakpoint to this location to check whether your submitted form model is valid or not at this point if it's false then your data will not be saved according to your logic.
Another thing is to make sure while using 'ModelState.IsValid' is that you are not posting invalid data for the particular field like if you have added validation for a decimal field in your view model and in form you are using 'TextBoxFor' tag helper for that particular field which accepts any characters and same for other data types also so make sure you are posting right data to controller otherwise 'ModelState.IsValid' will be false.


text:
Q: Relative to absolute image src in JavaScript I need to convert all src attributes of all images on the page from relative url to absolute, so basically just to add the base url on the current src.
I know how to do that using jQuery, but I need to do it with pure JS.
Any example or idea how to do that?
In jQuery I'll do it like:
$('img').each(function() {
  var urlRelative = $(this).attr("src");
  var urlAbsolute = 'https://example.com' + urlRelative;
  $(this).attr("src", urlAbsolute);
});

A: You can get all images tag using  document.getElementsByTagName(), then just iterate through each one of them and append your base url.

var images = document.getElementsByTagName('img');
const baseUrl = "https://myurl.com/"
Array.from(images).forEach(function(ele){
  ele.src = baseUrl + ele.getAttribute("src");
});

A: Does this help you?
const BASE_URL = "http://example.com";    //define your new base url
var elements =    document.getElementsByTagName("img");    //create an array with the tag selector

for (var i = 0; i < elements.length; i++) {    //loop through all elments in the array and change the src
   var oldSrc = elements[i].src;
   elements[i].src=BASE_URL + oldSrc;
}

A: Hope this helps you
var base_url = 'your_site/path_to_images'
var images = document.getElementsByTagName( 'img' );

function toArray(obj) {
  var array = [];
  // iterate backwards ensuring that length is an UInt32
  for (var i = obj.length >>> 0; i--;) {
    array[i] = obj[i];
  }
  return array;
}

images = toArray( images );
var src, last;

for ( var i = 0, len = images.length; i < len; i += 1  ) {
    src = images[i].getAttribute( 'src' );
    last = src.lastIndexOf('/');
    src = src.substr( last + 1 );
    images[i].setAttribute( 'src', base_url + src );
}

The toArray function was gotten from here.

redpajama_set_name: RedPajamaStackExchange


text:
Q: can ng-change and ng-click be used along side with a single button? I have a button in my application which works for ng-click for now..... I need to insert a functionality to the button as such it should be notified when the content of the table is changed by inputting some values while editing the table
Can I use ng-click along with ng-change.... How can I relate the ng-change of the table with the button?
 <button type="button" ng-disabled="vm.currentYear === vm.endYear"
         ng-attr-title="{{vm.currentYear === vm.endYear ? 'You\'ve reached the ending year for '+ vm.selectedProjectName : 'Load baselines for ' + (vm.currentYear+1)}}"
         class="btn btn-outlined  " ng-click="vm.changeYear(vm.currentYear+1)"
         ng-model="baseline.data[$index]"
         ng-change="vm.enableSaveButton($parent.$parent.$index, $parent.$index, $index, baseline)">
           <i class="fa fa-caret-right"></i>
 </button>

A: ng-change work with input tag only.  And ng-change require ng-model.
 <input type="text" ng-model="test" ng-change="seeChange()" />

Evaluate the given expression when the user changes the input. The
  expression is evaluated immediately, unlike the JavaScript onchange
  event which only triggers at the end of a change (usually, when the
  user leaves the form element or presses the return key).

https://docs.angularjs.org/api/ng/directive/ngChange


text:
Q: Are python lists row-major ordered or column-major ordered? I read on wikipedia that python is a language that implements Row-major order. But I am trying to multiply 2 matrices where I access using a row-major approach and a column-major approach. But when I execute the code, the column-major approach is allways faster.
I'll post here a snippet of my code:
class Matrix:

#flag indicates the type of matrix
def __init__(self, num_lines, num_cols, flag):
    self.num_lines = num_lines
    self.num_cols = num_cols
    if flag == 0:
        # First Matrix
        self.matrix = [1]*num_lines*num_cols
    elif flag == 1:
        # Second Matrix
        self.matrix = [0]*num_lines*num_cols
        for i in range(num_lines):
            for j in range(num_cols):
                self.matrix[i*num_cols+j] = i+1
    elif flag == 2:
        # Result Matrix
        self.matrix = self.matrix = [0]*num_lines*num_cols

def setMatrixValue(self, line, column, value):
    self.matrix[line*self.num_cols + column] = value

def getMatrixValue(self, line, column):
    return self.matrix[line*self.num_cols + column]

def multiplyMatrices(num_lines, num_cols, flag):
    matrix_a = Matrix(num_lines, num_cols, 0)
    matrix_b = Matrix(num_cols, num_lines, 1)
    matrix_result = Matrix(num_lines, num_lines, 2)

    # Column-major approach
    if flag == 0:
        start_time = time.time()
        for i in range(matrix_result.num_lines):
            for j in range(matrix_result.num_cols):
                temp = 0
                for k in range(matrix_a.num_cols):
                    temp += matrix_a.getMatrixValue(i, k) * matrix_b.getMatrixValue(k, j)
                matrix_result.setMatrixValue(i,j,temp)
    # Row-major approach
    elif flag == 1:
         start_time = time.time()
         for i in range(matrix_result.num_lines):
            for k in range(matrix_result.num_cols):
                for j in range(matrix_a.num_lines):
                    matrix_result.setMatrixValue(i,j, matrix_result.getMatrixValue(i,j) + (matrix_a.getMatrixValue(i,k) * matrix_b.getMatrixValue(k,i)))

    end_time = time.time()
    print matrix_result.matrix
    diffTime(start_time, end_time)

And I just realised that matrices multiplication in python is so much slower than Java or C++. Is there any reason for that?

A: Python is slow because it checks the types of all objects at runtime to decide what operations to perform (e.g. which mult should it use when it sees '*').  Not only that but most abstractions on simple data types have a runtime cost as you marshall data in and out of the object.
You can mitigate some of these speed problems by using numpy. e.g.
import numpy
numpy.matrix([0, 1]) * numpy.matrix([[0], [1]])

A: The behaviour you are expecting is caused by the advantage of accessing sequential memory addresses. So here
self.matrix[line*self.num_cols + column]

You would want to be incrementing column in the inner loop.
There are a few problems with this concept in pure Python. Since all the ints are objects - to access them, you are first getting a reference from the list sequentially (good), but then you need to access the memory of the reference (non sequential) to get the int object (bad).
Fortunately there are alternatives, such as numpy. Which additionally has  well tested matrix routines you can use.


text:
Q: AWS Elastic IP Network vpc is not attached to any internet gateway I have given a limited access to a AWS account.
I already created an EC2 instance but when I try to associate an elastic ip, I got the error below:
An error occurred while attempting to associate the address
Network vpc-(security id) is not attached to any internet gateway

A: This error occurs because the VPC is not associated with an Internet Gateway. To solve this: Go to VPC, then click on Internet Gateway. If none exists, Create one(probably will need admin permission) and then attach it to the target VPC-id. And try again associating the Elastic IP address to the EC2 instance. Hope it helps :)

A: You are using the new Amazon Virtual Private Cloud instead of the EC2 Classic.
The cloud you are using lacks the internet gateway virtual component that is necessary for the cloud to be reachable from the public internet.
You need to add an internet gateway to your private cloud for it to be able to connect to internet; with that in place, you can use Elastic IPs (after all, they are internet addressable; your VPC instances can have static instance IPs), and add a routing entry for internet addresses (0.0.0.0/0, or a narrower space).

A: You need to assign an Internet Gateway to your VPC.

*

*Go to VPC service and under VIRTUAL PRIVATE CLOUD on the left, click
"Internet Gateways"

*To create a new one, click on "Create Internet gateway", give it a name and create it

*Select the Gateway on the list, click "Actions" and "Attach to VPC"

*Select the VPC and click on "Attach Internet gateway"

Then you will be able to Assign the Elastic IP to your EC2 instance.


text:
Q: Reading text from a .txt file into a different worksheet excel I have taken this code from elsewhere because I don't know how to code... I just need help with how to make this file print into a different sheet in the workbook, lets say sheet 3, currently it is just printing in sheet 1. I know its probably simple but I have tried for about the past hour and I keep getting errors.
Private Sub ReadTxtFiles()

'Dim start As Date
'start = Now

Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")

Dim oFS As Object

'''''Assign the Workbook File Name along with its Path
'''''Change path of the Target File name

Dim v As Variant, filepath As String
For Each v In Worksheets("Sheet2").Columns("B").SpecialCells(xlCellTypeConstants)
filepath = v.Value
Debug.Print filepath

Dim arr(100000) As String
Dim i As Long
i = 0

If oFSO.FileExists(filepath) Then
    On Error GoTo Err

    Set oFS = oFSO.OpenTextFile(filepath)
    Do While Not oFS.AtEndOfStream
        arr(i) = oFS.ReadLine
        i = i + 1
    Loop
    oFS.Close
Else
    MsgBox "The file path is invalid.", vbCritical, vbNullString
    Exit Sub
End If

For i = LBound(arr) To UBound(arr)
    If InStr(1, arr(i), ThisWorkbook.Sheets(1).Range("A20").Value, vbTextCompare) Then

    'While value in 'ThisWorkbook.Sheets(1).Range("A20").Value' has not been found,
    'keep looping to print out contents starting from 'ThisWorkbook.Sheets(1).Range("A21").Value'
    Do While InStr(1, arr(i), ThisWorkbook.Sheets(1).Range("A21").Value, vbTextCompare) = 0

        Debug.Print i + 1,
        Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
        Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

        'increment count
        i = i + 1

    Loop

    'Print out the 'ThisWorkbook.Sheets(1).Range("A21").Value' line as well
    Debug.Print i + 1, arr(i)
    Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
    Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

    Exit For

End If

Next

Next

    Debug.Print DateDiff("s", start, Now)

Exit Sub

Err:
    MsgBox "Error while reading the file.", vbCritical, vbNullString
    oFS.Close
    Exit Sub

End Sub

A: While I extensively looked at what your script is doing here. To simply change the output sheet, it should be something like this.
Private Sub ReadTxtFiles()

'Dim start As Date
'start = Now

Dim oFSO As Object
Set oFSO = CreateObject("Scripting.FileSystemObject")

Dim oFS As Object

'''''Assign the Workbook File Name along with its Path
'''''Change path of the Target File name

Dim v As Variant, filepath As String
For Each v In Worksheets("Sheet2").Columns("B").SpecialCells(xlCellTypeConstants)
filepath = v.Value
Debug.Print filepath

Dim arr(100000) As String
Dim i As Long
i = 0

If oFSO.FileExists(filepath) Then
    On Error GoTo Err

    Set oFS = oFSO.OpenTextFile(filepath)
    Do While Not oFS.AtEndOfStream
        arr(i) = oFS.ReadLine
        i = i + 1
    Loop
    oFS.Close
Else
    MsgBox "The file path is invalid.", vbCritical, vbNullString
    Exit Sub
End If

For i = LBound(arr) To UBound(arr)
    If InStr(1, arr(i), ThisWorkbook.Sheets(1).Range("A20").Value, vbTextCompare) Then

    'While value in 'ThisWorkbook.Sheets(1).Range("A20").Value' has not been found,
    'keep looping to print out contents starting from 'ThisWorkbook.Sheets(1).Range("A21").Value'
    Do While InStr(1, arr(i), ThisWorkbook.Sheets(1).Range("A21").Value, vbTextCompare) = 0

        Debug.Print i + 1,
        '###################
        '#  Added the sheet name to the front of this variable.
        '#  Make sure there is a third sheet in your workbook!
        '##################
        sheets("Sheet3").Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
        sheets("Sheet3").Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

        'increment count
        i = i + 1

    Loop

        '###################
        '#  Also added the sheet name here
        '##################
    'Print out the 'ThisWorkbook.Sheets(1).Range("A21").Value' line as well
    Debug.Print i + 1, arr(i)
    sheets("Sheet3").Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
    sheets("Sheet3").Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

    Exit For

End If

Next

Next

    Debug.Print DateDiff("s", start, Now)

Exit Sub

Err:
    MsgBox "Error while reading the file.", vbCritical, vbNullString
    oFS.Close
    Exit Sub

End Sub

A: substitute:
For i = LBound(arr) To UBound(arr)
    If InStr(1, arr(i), ThisWorkbook.Sheets(1).Range("A20").Value, vbTextCompare) Then

    'While value in 'ThisWorkbook.Sheets(1).Range("A20").Value' has not been found,
    'keep looping to print out contents starting from 'ThisWorkbook.Sheets(1).Range("A21").Value'
    Do While InStr(1, arr(i), ThisWorkbook.Sheets(1).Range("A21").Value, vbTextCompare) = 0

        Debug.Print i + 1,
        Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
        Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

        'increment count
        i = i + 1

    Loop

    'Print out the 'ThisWorkbook.Sheets(1).Range("A21").Value' line as well
    Debug.Print i + 1, arr(i)
    Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = i + 1
    Range("B" & Range("B" & Rows.Count).End(xlUp).Row + 1) = arr(i)

    Exit For

End If

Next

with:
    Dim sheet1A20 As String
    Dim sheet1A21 As String
    With ThisWorkbook
        sheet1A20 = .Sheets(1).Range("A20").Value
        sheet1A21 = .Sheets(1).Range("A21").Value
        With .Sheets(3)
            For i = LBound(arr) To UBound(arr)
                If InStr(1, arr(i), sheet1A20, vbTextCompare) = 0 Then
                    'While value in 'ThisWorkbook.Sheets(1).Range("A20").Value' has not been found,
                    'keep looping to print out contents starting from 'ThisWorkbook.Sheets(1).Range("A21").Value'
                    Do While InStr(1, arr(i), sheet1A21, vbTextCompare) = 0
                        Debug.Print i + 1
                        .Cells(.Rows.count, 1).End(xlUp).Offset(1).Resize(, 2) = Array(i + 1, arr(i))
                        i = i + 1 'increment count
                    Loop
                    'Print out the 'ThisWorkbook.Sheets(1).Range("A21").Value' line as well
                    Debug.Print i + 1, arr(i)
                    .Cells(.Rows.count, 1).End(xlUp).Offset(1).Resize(, 2) = Array(i + 1, arr(i))
                    Exit For
                End If
            Next
        End With
    End With


text:
Q: ActionBarShelock duplicates actionbar actions on hardware menu key press I'm developing an app which supports APIS 9 to 17.
It also has a Navigation Drawer and for the action bar I use ActionBarSherlock. The problem comes when I press the menu hardware button (API <= 10). The actions displayed in the actionbar are duplicated. How to fix this issue?
Here's my code to inflate the menu
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuInflater inflater = getSupportMenuInflater();
    inflater.inflate(R.menu.menu_content_action_menu, menu);
return true;
}

And my menu_content_action_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/send_order_action"
        android:icon="@drawable/ic_navigation_accept"
        android:showAsAction="ifRoom|withText"
        android:title="@string/send_order_button_text">
    </item>
</menu>

Hope you can help me.

A: Use your code in the onCreateOptionsMenu() implementation instead.
public boolean onCreateOptionsMenu(final Menu menu) {
    getSupportMenuInflater().inflate(R.menu.menu_content_action_menu, menu);
    return true;
}


text:
Q: How can I bind a key to show/hide the dock on Ubuntu 20.04? I like the idea of being able to hide the dock and use as much screen space as possible, but I get really anoyed with the default bahaviour of the "Auto-hide dock" option. Sometimes I hover the pointer over the dock space, and it just won't show up, so I have to keep repeating this action until it slides in.
I'd like to bind a key to hide or show the dock (something like a switch key) instead of having to hover the cursor over it to do so. Can someone help me?
PS: If I could use a mouse macro to do so would be even better.


text:
Q: Install latest Konsole on non KDE-based distros I'd like to install latest konsole on Ubuntu 20.10.
I see in the public repo that latest version is konsole/groovy,now 4:20.08.2-0ubuntu1 amd64, but I know that the current latest is 21.04.1.
Is there a way to always have latest version and keep it automatically updated (PPA, flatpak, snap etc...)?
Thanks

A: Add the relevant Flatpack repositories, which can be added with two commands:
flatpak remote-add --if-not-exists kdeapps --from https://distribute.kde.org/kdeapps.flatpakrepo
flatpak remote-add --if-not-exists flathub-beta --from https://flathub.org/beta-repo/flathub-beta.flatpakrepo

Then install Konsole from (for the latest versions) the former repository.


text:
Q: Installing/uninstalling multiple/different versions of an application (e.g. virtualbox) on Ubuntu 13.04 I've been trying to get vagrant to work with virtualbox for hours now and I've been trying different combinations of versions of both. I finally got the whole thing working but during the painful process I wondered the following (I am a linux noob btw so please excuse me if these questions sound really dumb and vague)

*

*When I uninstall virtualbox (or any application for that matter) through Ubuntu software centre does it leave any extra garbage (kind of like windows and registry) that could possibly cause future problems (e.g. during upgrades, reinstallations)? Or are they (or at least virtualbox)  completely encapsulated (kind of like .app files on OS X) that I probably won't ever need to worry about it after removal?

*Is there any relatively easy and safe remove all these garbage leftovers (if any) to ensure I don't have version problems later on?
Thanks in advance

A: For now, VirtualBox 4.2.18 + Vagrant 1.3.1 is the good combination.
A few tips:

*

*better start to get your hands dirty with commands instead of software center (even synaptic is better than that crap). For VirtualBox

*To check what the virtualbox-4.2 package contains => dpkg -L virtualbox-4.2, you'll have a better understanding of what installing the package means. Removing the packages removes all the files contained in the package.

*apt-get purgeremoves the package as well as the configuration files, I think that is what you want.

*to clean up unwanted configration files system wide, try => aptitude purge '~c'

*start to use deborphan and gtkorphan (GUI) to cleanup orphaned packages.
To answer your questions:

*

*NOT really. Only configuration files and your virtual machines remain.

*sudo apt-get purge virtualbox-4.2 or after you've run sudo apt-get remove do a aptitude purge '~c'

*You can also delete ~/.VirtualBox, it's safe to delete.


text:
Q: Javascript - Change image after some amount of time This may be a common question, but I have tried some solutions, and my code isn't work yet.
So, I have a .GIF image on my WYSIWYG page. My code works fine to start and to replay my .gif, by changing an ImageStart.jpg to my Image.gif. But i need to load a new image "ImageEnd.jpg after my Image.gif has ended.
So, I've tried SetTimeout:
function play(){
  if (document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/PesquisaStart.jpg"){
    document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa.gif";
  }else{
    document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa1.gif";
  }
  SetTimeout(function(){end()},24000);
}

function end(){
  document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/PesquisaEnd.jpg";
}

The way I see it, my code should change my Image.gif to an ImageEnd.jpg after 24 seconds, which is the lenght of the animation.
Something wrong about it?

A: The logic in your if condition is faulty in addition to the setTimeout misspelling. Should use two equal signs to perform a comparison. Also, try to store a reference to a DOM element instead of searching for it every time. Also makes for cleaner code.
function play(){
  var img = document.getElementById("Pesquisa");
  if (img.src == "http://www.lyuz.com.br/media/./images/Software/PesquisaStart.jpg"){
    img.src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa.gif";
  }else{
    img.src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa1.gif";
  }
  setTimeout(function(){end()},24000);//you had SetTimeout(...), upperCased S previously
}

function end(){
  document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/PesquisaEnd.jpg";
}

A: Use the onload event :
document.getElementById("Pesquisa").onload=function(){end()}


text:
Q: Basic standard IPTables configuration
Possible Duplicate:
Can you recommend a good intro to iptables?

I'm going to be setting up IPTables on my server.  I have never done anything with IPTables and want to get started.  What are your most common configurations, or your must-haves?

A: I'd review the netfilter documentation before doing much of anything. Understanding how packets flow through the various tables and chains (where routing decisions are made, etc) is a good first thing to understand. Then you'll have a feel for what the product is capable of.
As far as something practical: You should start your INPUT, FORWARD, and OUTPUT chains with the following to allow established connections to "shortcut" evaluating all the rules on the chains and to drop patently invalid packets before any further evaluation is done:
-m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-m conntrack --ctstate INVALID -j DROP

This will help with performance, though you may not be moving enough traffic for it to make any real difference.
You should think strongly about setting the default policy on your "filter" table chains to DROP, and designing your rules to explicitly allow traffic through, rather than attempting to block traffic.

A: The preferred interface to simple firewalling on Ubuntu is ufw. You could start by using it, and then progressively move on to handwritten iptables rules as your needs grow. The command iptables-save dumps the current iptables state in a format that is close to a sequence of iptables commands that would recreate it.
The iptables Ubuntu wiki page is a good starting point for documentation.


text:
Q: Check status in handlebars Hi I want to check the string response in HB. I've tried this:
{{#if status=='false'}}
    {{console.log("hi");}}
{{else}}
   {{console.log("no");}}
{{#endif}}

How can I check the response simple? I want to show a message if it's true and another message if it's false.

A: Handlebars is designed to be very simple and doesn't have this functionality out of the box. You should pass the status as a boolean rather than a string, then just use an if statement:
{{#if status}}
    {{console.log("hi");}}
{{else}}
   {{console.log("no");}}
{{#endif}}

You could also write a helper function:
Handlebars.registerHelper('ifEq', function(a, b, options) {
  if (a == b) return options.fn(this)
  else return options.inverse(this)
});

Then your handlebars becomes:
{{#ifEq status 'true'}}
  Hello
{{else}}
  No
{{/ifEq}}


text:
Q: `Undefined Property` error in laravel jobs I am running a job in laravel the code of my job looks like:
app/jobs/StoreFloorPlan.php
<?php

namespace App\Jobs;

use App\Events\FloorPlanUploaded;
use App\Http\Services\AmenityService;
use App\Mail\CSVFailedJob;
use App\Mail\CSVImportJobCompleted;
use App\Mail\CSVImportJobPartiallyCompleted;

use App\Models\Notice;
use App\Models\Property;
use App\Models\UnitTypeDetail;
use Mail;

use App\Models\FloorPlan;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use League\Csv\Reader;
use League\Csv\Statement;

class StoreFloorPlan implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data,$error_arr,$error_row_numbers,$table;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data,$error_arr,$error_row_numbers) {
        $this->data = $data;
        $this->error_arr = $error_arr;
        $this->error_row_numbers = $error_row_numbers;
        $this->table = 'floor_plans';
    }

    /**
     * Execute the job.
     *
     * @throws \League\Csv\Exception
     *
     * @return void
     */
    public function handle()
    {
//        $result = 1/0;
        $header_row = $this->data['header_row'];
        $offset = $this->data['offset'];
        $limit = $this->data['limit'];
//        $limit = 5;
        $filename = $this->data['file_name'];
        $service = new AmenityService();
        $dbase = new FloorPlan();

        $map_data = $this->data['map_data'];

        $db_header_obj = new FloorPlan();
//        $db_header = $db_header_obj->getTableColumns();

        $csv_file_path = storage_path('app/files/floor-plan/').$filename;
        if (!ini_get("auto_detect_line_endings")) {
            ini_set("auto_detect_line_endings", TRUE);
        }
        $csv = Reader::createFromPath($csv_file_path, 'r');

        $input_bom = $csv->getInputBOM();
        if ($input_bom === Reader::BOM_UTF16_LE || $input_bom === Reader::BOM_UTF16_BE) {
            $csv->addStreamFilter('convert.iconv.UTF-16/UTF-8');
        }

//        $csv->addStreamFilter('convert.iconv.ISO-8859-15/UTF-8');

//        $csv->setOutputBOM(Reader::BOM_UTF8);
//        $csv->addStreamFilter('convert.iconv.ISO-8859-15/UTF-8');

        $csv->setHeaderOffset($header_row);
//        $csv_header = $csv->getHeader();

        $rec_arr = array();
//        $properties_arr = array();

        $stmt = (new Statement())
            ->offset($offset)
            ->limit($limit)
        ;

        $records = $stmt->process($csv);

        foreach ($records as $record)
        {
            $record = array_merge($record, $this->data['additional_value']);
            $rec_arr[] = array_values($record);
        }

        $records_arr = $service->trimArray($rec_arr);

        if(count($records_arr)>0)
        {
            foreach($records_arr as $ck => $cv) {

                $floorPlanArr = array();
                foreach ($map_data as $mk => $mv) {
                    if (isset($mv)) {
                        $floorPlanArr[$mv] = $cv[$mk];
                    }
                }
                $floorPlanArr['created_at'] = Carbon::now();
                $floorPlanArr['updated_at'] = Carbon::now();
                if (!array_key_exists('pricing_offset', $floorPlanArr)){
                    $floorPlanArr['pricing_offset'] = '';
                }
//                $properties_arr[] = $floorPlanArr;

                try{
                    $unitTypeDetail = UnitTypeDetail::firstOrCreate([
                        'unit_type' => $floorPlanArr['unit_type'],
                        'property_id' => $this->data['property_id']
                    ]);

                    $floorPlan = FloorPlan::firstOrCreate(
                        [
                            'pms_property' => empty($floorPlanArr['pms_property'])?NULL:$floorPlanArr['pms_property'],
                            'pms_unit_type' => empty($floorPlanArr['pms_unit_type'])?NULL:$floorPlanArr['pms_unit_type'],
                            'description' => isset($floorPlanArr['description'])?$floorPlanArr['description']:NULL,
                            'beds' => isset($floorPlanArr['beds'])?$floorPlanArr['beds']:NULL,
                            'baths' => isset($floorPlanArr['baths'])?(int)$floorPlanArr['baths']:NULL,
                            'sqft' => $floorPlanArr['sqft'],
                            'unit_count' => $floorPlanArr['unit_count'],
                            'pricing_offset' => (empty($floorPlanArr['pricing_offset']) &&  $floorPlanArr['pricing_offset'] != '0')?NULL:$floorPlanArr['pricing_offset'],
                            'unit_type_id' => $unitTypeDetail->id,
                            'property_id' => $this->data['property_id'],
                        ]
                    );
//                    Property::where('id',$this->data['property_id'])->update(['floor_file' => 2]);

                } catch (\Exception $e) {

                    if(isset($e->errorInfo)){
                        $error_arr = $e->errorInfo[2];
                        $this->error_arr[] = str_replace('at row 1', '', $error_arr);
                    }else{
                        $this->error_arr[] = $e->getMessage();
                    }

                    $this->error_row_numbers[] = $this->data['row_value'];
                }

                $this->data['row_value'] = $this->data['row_value'] + 1;
            }

            $this->data['offset'] = $offset + $limit;

            $propertyInsertJob = (new StoreFloorPlan($this->data,$this->error_arr,$this->error_row_numbers))->delay(Carbon::now()->addSeconds(3));
            dispatch($propertyInsertJob);

        }else{
            $arr_data = array();

            $err_count = count($this->error_arr);
            if($err_count > 0) {
                Property::where('id',$this->data['property_id'])->update(['floor_file' => 3]);
                $error = '';
                if($err_count>0){
                    $error .= "Error occurred in following rows:
";
                    for($i=0; $i<$err_count; $i++){
                        $error .= $this->error_row_numbers[$i].' ( '.$this->error_arr[$i].' ) ';
                        $error .="
";
                    }
                    $error .= "
";
                }
                $array_from_to = array (
                    '[[USER_NAME]]' => $this->data['user']->name,
                    '[[FILENAME]]' => $filename,
                    '[[ERROR]]' => $error,
                );
                $mailBody = $this->service->formatMailBody('csv-insert-job-partially-completed',$array_from_to);
                $arr_data['mailBody'] = $mailBody;
                $slug = Notice::generateRandomSlug();
                Notice::updateOrCreate(
                    [
                        'property_id' => $this->data['property_id'],
                        'file_type' => '2',
                    ],
                    [
                        'title' => 'File uploaded with errors',
                        'slug' => $slug,
                        'body' => json_encode($mailBody),
                        'user_id' => $this->data['user']->id,
                        'seen' => 'n'
                    ]
                );
                event(new FloorPlanUploaded($this->data['property_id']));
                if($this->data['user']->email_notification == 'on'){
                    Mail::to($this->data['user']->email)->send(new CSVImportJobPartiallyCompleted($arr_data));
                }
            }else{
                Property::where('id',$this->data['property_id'])->update(['floor_file' => 1]);
                $error = '';
                $array_from_to = array (
                    '[[USER_NAME]]' => $this->data['user']->name,
                    '[[FILENAME]]' => $filename,
                    '[[ERROR]]' => $error,
                );
                $mailBody = $this->service->formatMailBody('csv-insert-job-completed',$array_from_to);
                $arr_data['mailBody'] = $mailBody;
                event(new FloorPlanUploaded($this->data['property_id']));
                if($this->data['user']->email_notification == 'on'){
                    Mail::to($this->data['user']->email)->send(new CSVImportJobCompleted($arr_data));
                }
            }

        }

        if (!ini_get("auto_detect_line_endings")) {
            ini_set("auto_detect_line_endings", FALSE);
        }
    }

}

And, I am receiving error as
ErrorException: Undefined property: App\Jobs\StoreFloorPlan::$service in D:\wamp64\www\amenity\app\Jobs\StoreFloorPlan.php:215
Stack trace:
#0 D:\wamp64\www\amenity\app\Jobs\StoreFloorPlan.php(215): Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(8, 'Undefined prope...', 'D:\\wamp64\\www\\a...', 215, Array)
#1 [internal function]: App\Jobs\StoreFloorPlan->handle()
#2 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(32): call_user_func_array(Array, Array)
#3 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#4 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#5 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\Container.php(576): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#6 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Bus\Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#7 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(128): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(App\Jobs\StoreFloorPlan))
#8 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(104): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(App\Jobs\StoreFloorPlan))
#9 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Bus\Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#10 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Queue\CallQueuedHandler.php(49): Illuminate\Bus\Dispatcher->dispatchNow(Object(App\Jobs\StoreFloorPlan), false)
#11 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Queue\Jobs\Job.php(88): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#12 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(337): Illuminate\Queue\Jobs\Job->fire()
#13 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(283): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#14 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Queue\Worker.php(118): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#15 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(102): Illuminate\Queue\Worker->daemon('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#16 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Queue\Console\WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#17 [internal function]: Illuminate\Queue\Console\WorkCommand->handle()
#18 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(32): call_user_func_array(Array, Array)
#19 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(90): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#20 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\BoundMethod.php(34): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#21 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Container\Container.php(576): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#22 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Console\Command.php(183): Illuminate\Container\Container->call(Array)
#23 D:\wamp64\www\amenity\vendor\symfony\console\Command\Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#24 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Console\Command.php(170): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#25 D:\wamp64\www\amenity\vendor\symfony\console\Application.php(1000): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#26 D:\wamp64\www\amenity\vendor\symfony\console\Application.php(271): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#27 D:\wamp64\www\amenity\vendor\symfony\console\Application.php(147): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#28 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Console\Application.php(90): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 D:\wamp64\www\amenity\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php(133): Illuminate\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 D:\wamp64\www\amenity\artisan(37): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#31 {main}

I could not understand what is property. It is showing error in line number 215 but there is no property variable in entire file, instead there is property_id.
Any suggestion how could I fix it or from where I could start debugging?
Let me know if you need any further details.

A: The answer is clear on your error message Undefined property: App\Jobs\StoreFloorPlan::$service there you can see undefined property $service.
There you have used $this->service->formatMailBody but you forgot to define it. Add
public $service and on __construct add $this service = new Service() //or what that service is.


text:
Q: What class to add to buttonset elements to show select status after a group select action? I have a toolbar of checkboxes that are grouped together via a buttonset() call.  If one checkbox is selected, I'd like to set the entire group to selected, and deselect on a second click event.
I have this click handler instanciated
$("#category_all").click(function(e){

  if ($("#category_1").is(":checked")) {
    $(".category_selector").prop("checked", false);
    $(".category_selector").removeClass("ui-state-active");

  } else {
    $(".category_selector").prop("checked", true);
    $(".category_selector").addClass("ui-state-active");
  }
});

The check state change is applied to all buttonset elements, but the rest of the elements maintain the same styling.  I've also tried "checked" for the class, but no result.
What is the jQuery UI class to be added to the buttonset group to show that they are all selected?

A: Try calling the refresh method after setting the checked property.  This is outlined in the docs here


text:
Q: How to set data-* attribute of checked radio to class of another element using jquery? How do I take the data-attribute of a checked radio button and output it inside the class attribute of a different element?
Please take a look at the example:

body{
  background: #eee;
}

.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

.box.black{
  background: #000;
}

.box.white{
  background: #fff;
}

.box.green{
  background: #00d300;
}

<input data-color="black" id="radio1" type="radio" name="radio" checked>
Black
<input data-color="white" id="radio2" type="radio" name="radio">
White
<input data-color="green" id="radio3" type="radio" name="radio">
Green

A: You can do it using CSS only. :checked select checked radio and ~ is General sibling selectors.
input[data-color="black"]:checked ~ .box {
    background: #000;
}

.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

input[data-color="black"]:checked ~ .box {
  background: #000;
}

input[data-color="white"]:checked ~ .box {
  background: #fff;
}

input[data-color="green"]:checked ~ .box {
  background: #00d300;
}
<input data-color="black" id="radio1" type="radio" name="radio" checked>
Black
<input data-color="white" id="radio2" type="radio" name="radio">
White
<input data-color="green" id="radio3" type="radio" name="radio">
Green

If you want to do it using jquery, you need to get value of data-color attribute using .attr() or .data() and set it to class of .box using .addClass().
$("input[name='radio']").change(function(){
    $(".box").removeClass().addClass("box " + $(this).attr("data-color"));
});

$("input[name='radio']").change(function(){
    $(".box").removeClass().addClass("box " + $(this).attr("data-color"));
});
.box{
  background: #000;
  margin: 40px;
  width: 200px;
  height: 200px;
}

.box.black{
  background: #000;
}

.box.white{
  background: #fff;
}

.box.green{
  background: #00d300;
}

<input data-color="black" id="radio1" type="radio" name="radio" checked>
Black
<input data-color="white" id="radio2" type="radio" name="radio">
White
<input data-color="green" id="radio3" type="radio" name="radio">
Green


text:
Q: Projecting Austria data with QGIS? I'm trying to reproject this dataset from Austria Statistik Geodata.
Data comes in "MGI_Austria_Lambert", and I'm trying to reproject to WGS84
What I'm doing is Saving layer as... and selecting EPSG:4326, but the layer is still in the same place.
The other option i'm trying is changing the original .prj file with other one from a layer in EPSG:4326, but I have the same result.
I don't what can I do to solve it.
I've also tried setting the projection with:Set SRC to layer, and selecting 4326, but no changes.

A: I tried this out and had no issues... once the data was re-projected and added to the map, I re-set the map to EPSG:3857, added the Google map via OpenLayers, and the re-projected (and projected on the fly) dataset of yours worked just fine:

A: follow the instructions I gave here Reprojecting vector layer in QGIS? and you are done:
before:

and after:


text:
Q: Feature Importance with SVR I would like to plot Feature Importance with SVR, but I don't know if possible with support vector regression it's my code.
from sklearn.svm import SVR
C=1e3
svr_lin = SVR(kernel="linear", C=C)
y_lin = svr_lin.fit(X,Y).predict(X)
scores = cross_val_score(svr_lin, X, Y, cv = 5)
print(scores)
print(scores.mean())
print(scores.std())

A: SVR does not support native feature importance scores, you might need to try Permutation feature importance which is a technique for calculating relative importance scores that is independent of the model used.
First, a model is fit on the dataset, such as a model that does not support native feature importance scores. Then the model is used to make predictions on a dataset, although the values of a feature (column) in the dataset are scrambled. This is repeated for each feature in the dataset. Then this whole process is repeated 3, 5, 10 or more times. The result is a mean importance score for each input feature (and distribution of scores given the repeats).
This approach can be used for regression or classification and requires that a performance metric be chosen as the basis of the importance score, such as the mean squared error for regression and accuracy for classification.
Permutation feature selection can be used via the permutation_importance() function that takes a fit model, a dataset (train or test dataset is fine), and a scoring function.
model = SVR()
# fit the model
model.fit(X, y)
# perform permutation importance
results = permutation_importance(model, X, y, scoring='neg_mean_squared_error')
# get importance
importance = results.importances_mean
# summarize feature importance
for i,v in enumerate(importance):
    print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
pyplot.bar([x for x in range(len(importance))], importance)
pyplot.show()


text:
Q: Write a function that determines the maximum number of consecutive BA, CA character pairs per line My respects, colleagues.
I need to write a function that determines the maximum number of consecutive BA, CA character pairs per line.
print(f("BABABA125"))  # -> 3
print(f("234CA4BACA"))  # -> 2
print(f("BABACABACA56"))  # -> 5
print(f("1BABA24CA"))  # -> 2

Actually, I've written a function, but, to my mind, it's not very good.
def f(s: str) -> int:

    res = 0

    if not s:
        return res

    cur = 0
    i = len(s) - 1

    while i >= 0:
        if s[i] == "A" and (s[i-1] == "B" or s[i-1] == "C"):
            cur += 1
            i -= 2
        else:
            if cur > res:
                res = cur
                cur = 0
            i -= 1
    else:
        if cur > res:
            res = cur

    return res

In addition, I'm not allowed to use libraries and regular expressions (only string and list methods). Could you please help me or rate my code in this context. I'll be very grateful.

A: Here's a function f2 that performs this operation.

*

*if not re.search('(BA|CA)', s): return 0
First check if the string actually contains any BA or CA (to prevent ValueError: max() arg is an empty sequence on step 3), and return 0 if there aren't any.

*matches = re.finditer(r'(?:CA|BA)+', s)
Find all consecutive sequences of CA or BA, using non-capturing groups to ensure re.finditer outputs only full matches instead of partial matches.

*res = max(matches, key=lambda m: len(m.group(0)))
Then, among the matches (re.Match objects), fetch the matched substring using m.group(0) and compare their lengths to find the longest one.

*return len(res.group(0))//2
Divide the length of the longest result by 2 to get the number of BA or CAs in this substring. Here we use floor division // to coerce the output into an int, since division would normally convert the answer to float.

import re

strings = [
    "BABABA125",  # 3
    "234CA4BACA",  # 2
    "BABACABACA56",  # 5
    "1BABA24CA",  # 2
    "NO_MATCH_TO_BE_FOUND",  # 0
]

def f2(s: str):
    if not re.search('(BA|CA)', s): return 0
    matches = re.finditer(r'(?:CA|BA)+', s)
    res = max(matches, key=lambda m: len(m.group(0)))
    return len(res.group(0))//2

for s in strings:
    print(f2(s))

UPDATE: Thanks to @StevenRumbalski for providing a simpler version of the above answer. (I split it into multiple lines for readability)
def f3(s):
    if not re.search('(BA|CA)', s): return 0
    matches = re.findall(r'(?:CA|BA)+', s)
    max_length = max(map(len, matches))
    return max_length // 2

*

*if not re.search('(BA|CA)', s): return 0
Same as above

*matches = re.findall(r'(?:CA|BA)+', s)
Find all consecutive sequences of CA or BA, but each value in matches is a str instead of a re.Match, which is easier to handle.

*max_length = max(map(len, matches))
Map each matched substring to its length and find the maximum length  among them.

*return max_length // 2
Floor divide the length of the longest matching substring by the length of BA, CA to get the number of consecutive occurrences of BA or CA in this string.

A: Here's an alternative implementation without any imports. Do note however that it's quite slow compared to your C-style implementation.
The idea is simple: Transform the input string into a string consisting of only two types of characters c1 and c2, with c1 representing CA or BA, and c2 representing anything else. Then find the longest substring of consecutive c1s.
The implementation is as follows:

*

*Pick a char that is guaranteed not to appear in the input string; here we use + as an example. Then pick a char different from the previous one; here we use -.

*Replace each occurrence of CA and BA with a +.

*Replace everything else in the string (that is not a +) with a - (this is why + cannot be present in the original input string). Now we have a string consisting purely of +s and -s.

*Split the string with - as delimiter, and map each resulting substring to their length.

*Return the maximum of these substring lengths.

strings = [
    "BABABA125",  # 3
    "234CA4BACA",  # 2
    "BABACABACA56",  # 5
    "1BABA24CA",  # 2
    "NO_MATCH_TO_BE_FOUND",  # 0
]

def f4(string: str):
    string = string.replace("CA", "+")
    string = string.replace("BA", "+")
    string = "".join([(c if c == "+" else "-") for c in string])
    str_list = string.split("-")
    str_lengths = map(len, str_list)
    return max(str_lengths)

for s in strings:
    print(f4(s))


text:
Q: Share A List Across two IActionresult Below is my code
private readonly IConfiguration configuration;
    private readonly IHostingEnvironment env;
    private readonly IActionContextAccessor actionContextAccessor;
    private utility util;

    public GeneratePDFController(IConfiguration _configuration, IHostingEnvironment _env, IActionContextAccessor _actionContextAccessor)
    {
        configuration = _configuration;
        env = _env;
        actionContextAccessor = _actionContextAccessor;
        util = new utility(_configuration, _env);
    }

    public IActionResult Index()
    {
        IndusIndVM model = new IndusIndVM();
        try
        {
            util.DeleteFolders();
            util.CreateFolders(HttpContext.Session.GetString("UserID"));
            model.BranchList = GetBranchWiseList();
        }
        catch (Exception ex)
        {
            TempData["Msg"] = ex.Message;
        }
        finally
        {
        }
        return View(model);
    }

    public IActionResult GetMemberList(string BranchCode)
    {
        IndusIndVM model = new IndusIndVM();
        try
        {
            Parallel.Invoke(
                            () => { model.BranchList = GetBranchWiseList(); },
                            () => { if (BranchCode != null) { model.MemberList = GetMemberWiseList(BranchCode); } }
                        );
        }
        catch (Exception ex)
        {
            TempData["Msg"] = ex.Message;
        }
        finally
        {
            TempData["BranchCode"] = BranchCode;
        }
        return View("Index", model);
    }

In Index IActionResult  I am calling a method GetBranchWiseList() which take around 30 seconds to run and in GetMemberList IActionResult  again I want same data so have to run this method again
So here now instead of running this method again in GetMemberList()
I want to store this in a global list
This will give me one benefit ,list will be populated once in Index() and no need to get it again from database in GetMemberList() (will share global list in both Action Method)
For this I declared a global list
 private List<PendingListBranchWise> BL;

and in constructor
 BL = new List<PendingListBranchWise>();

And in Index() store list into it
 model.BranchList = GetBranchWiseList();
 BL = model.BranchList;

Now in GetMemberList()
 model.BranchList = BL;

But BL is null here , I tried making this list is static too , but its value is null for GetMemberList() , Storing in TempData is not a good option either
How can I retain this list and use it across ActionMethods ?

A: There are multiple ways you can achieve this:
1. Use [OutputCache(--)]  Attribute for Index method so instead of calling it every time,
   it will return the cached result.
2. Store the list in the application session.
3. store this list in a global variable.


text:
Q: How to change the row color based on data that can change in a tableview? I am writing a podcast player and have a list of files that I display.
The user can double click an entry and that files play. If they select another one. I don't know what has been selected in the list. The idea is to highlight the file that is playing in a different color. With still keeping the ability to select another file (don't want to lose that functionality).  Most audio players work on the same principle.
I had a look at this JavaFX tableview colors and this changes the color of the row based on data. But if the data changes the row color do not refresh as the data changes.
I have a table with cell factory and based on the variable "isSelectedFile" I set the cell style.
If the isSelectedFile=True at load time all is ok but once I change the data while the rows are loaded into the tableview it doesn't refresh.
My cell factory is as follows:
entryDisplayNameColumn.setCellFactory(new Callback<TableColumn<PlaylistEntry, String>, TableCell<PlaylistEntry, String>>() {
            @Override
            public TableCell call(TableColumn p) {

                TableCell cell = new TableCell<Task, Object>() {
                    @Override
                    public void updateItem(Object item, boolean empty) {
                        super.updateItem(item, empty);
                        setText(empty ? null : getString());
                        setGraphic(null);
                        TableRow currentRow = getTableRow();
                        PlaylistEntry ple = currentRow == null ? null : (PlaylistEntry) currentRow.getItem();

                        if (ple != null) {
                            clearPriorityStyle();
                            setPriorityStyle(ple.isSelectedFile());
                        }
                    }

                    @Override
                    public void updateSelected(boolean upd) {
                        super.updateSelected(upd);
                        System.out.println("is update");
                    }

                    private void clearPriorityStyle() {
                        ObservableList<String> styleClasses = getStyleClass();
                        styleClasses.remove("priorityLow");
                        styleClasses.remove("priorityMedium");
                        styleClasses.remove("priorityHigh");
                    }

                    private void setPriorityStyle(boolean activeValue) {
                        if (activeValue) {
                            getStyleClass().add("priorityLow");
                        } else {
                            getStyleClass().add("priorityMedium");
                        }
                    }

                    private String getString() {
                        return getItem() == null ? "" : getItem().toString();
                    }
                };
                return cell;
            }
        });

My CSS:
.priorityLow {
-fx-control-inner-background: snow;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
}

.priorityMedium {
-fx-control-inner-background: #1d1d1d;
-fx-accent: derive(-fx-control-inner-background, -40%);
-fx-cell-hover-color: derive(-fx-control-inner-background, -20%);
 }

A: try this its perfectly worked...
tablecol.setCellFactory(new Callback<TableColumn<CheckDo, String>, TableCell<CheckDo, String>>() {

        @Override
        public TableCell<CheckDo, String> call(TableColumn<CheckDo, String> p) {

             return new TableCell<CheckDo, String>() {

            @Override
            public void updateItem(String item, boolean empty) {
                super.updateItem(item, empty);
                if (!isEmpty())
                    this.setStyle("-fx-background-color:red");
                    this.getTableRow().setStyle("-fx-background-color:red");
                        setText(item);
                }
            }
        };


text:
Q: uploading file using ajax and servlet i'm getting message "File not found". please help me.
here id my code
index.jsp

<title>Ajax File Upload</title>

 <link href="style.css" rel="stylesheet" type="text/css" />
 <link href="login_style.css" rel="stylesheet" type="text/css" />

    <form name="login_frm"  enctype="multipart/form-data" id="login_frm" action="" method="post">

   Citizen Login

Upload Pic :

<input type="file" name="file" id="file"/>

                        <input type="submit" name="upload" id="upload" value="Upload" class="send_button" />

        </form>

now, this is my servlet
uploads.java
package fileupload;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Iterator;
import java.io.File;
import java.util.Random;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import java.util.regex.*;

public class uploads extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
//out.println("items: "+items);
} catch (FileUploadException e) {
e.printStackTrace();
}
FileItem file = (FileItem)items.get(0);
//out.print(file);
Iterator itr = items.iterator();
int noFile=0;
while (itr.hasNext()) {

FileItem item = (FileItem) itr.next();
if (item.isFormField()){

String name = item.getFieldName();
String value = item.getString();
} else {
try {

String itemName = item.getName();
Random generator = new Random();
int r = Math.abs(generator.nextInt());
String reg = "[.*]";
String replacingtext = "";
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(itemName);
StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(buffer, replacingtext);
}
int IndexOf = itemName.indexOf(".");
String domainName = itemName.substring(IndexOf);
String finalimage = buffer.toString()+"_"+r+domainName;
File savedFile = new File("C:/tmp/"+"images\\"+finalimage);
item.write(savedFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
out.print(noFile+" File(s) Uploaded !!");
}
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

same code is running perfectly without ajax.

A: use ajaxfileupload library to upload file using ajax.
below link may help you to upload file using ajax.
http://www.phpletter.com/Our-Projects/AjaxFileUpload/

A: You can have a look for this ;)
Ajax File Upload to Java Servlet


text:
Q: Is there a way to select all JSON objects containing a specific value? Let's say you have JSON like the following:
[{
    "Rarity": "Common",
    "EffectOne": "+4 ACC",
    "EffectTwo": "-1 SPD",
    "EffectThree": "",
  },
{
    "Rarity": "Common",
    "EffectOne": "+4 ACC",
    "EffectTwo": "-1 SPD",
    "EffectThree": "",
  },
{
    "Rarity": "Rare",
    "EffectOne": "+4 ACC",
    "EffectTwo": "-1 SPD",
    "EffectThree": "",
  }]

How can you target the objects that have a shared value for one of the Properties, such as "Rarity": "Common".
Can you do (for the sake of this example, let's say this JSON is just named data): data.rarity.common? or would it be data.rarity("Common"). The reason I ask is I actually can't seem to find this info anywhere in JSON jquery documentation and I would like to populate data in different places based on specific values.

A: There you go with plain JavaScript. The variable common_value is set to Common as a filter for the rarity. Is this what you are looking for?

var json = [{
    "Rarity": "Common",
    "EffectOne": "+4 ACC",
    "EffectTwo": "-1 SPD",
    "EffectThree": "",
  },
{
    "Rarity": "Common",
    "EffectOne": "+4 ACC",
    "EffectTwo": "-1 SPD",
    "EffectThree": "",
  },
{
    "Rarity": "Rare",
    "EffectOne": "+4 ACC",
    "EffectTwo": "-1 SPD",
    "EffectThree": "",
  }];

var common_value = "Common";
var results = [];

for(var i = 0; i < json.length; i++){
 if(json[i].Rarity === common_value){
   results.push(json[i]);
  }
}

console.log(results);


text:
Q: How to enumerate list items randomly in C#? I have a challenging question for you big experts. This has not yet a practical usage in my code, but comes from an idea I just had.
If I have an IList<T>, how do I implement an enumerator that randomly walks the list and that can be used by multiple threads simultaneously?
For example, if I have elements A, B, C, D, E, F and two concurrent threads performing a for-each loop on the list with a ReaderLock acquired (so I'm sure nobody else will touch the list thus causing an exception), I would like their respective cycles to return, for example, B, E, C, D, A, F and E, B, D, C, A, F.
The reason why I need this is because I need to place locks on List<SslStream> elements to send data to clients, because SslStream is not thread-safe. Picking elements randomly (but making sure I pick them all) reduces the lock conflict probabilities and is supposed to improve I/O-bound operations performance.
Please keep in mind that even if I told you why I need such an enumerator, I still like challenge. There can be other ways of sending the same data to multiple clients, but my question remains the same :) :)

A: Something like this (obviously needs to be productionized):
class RandomList<T> : IEnumerable<T> {
     private readonly IList<T> list;
     private readonly Random rg;
     private readonly object sync = new Object();
     public RandomList(IList<T> list) : this(list, new Random()) { }

     public RandomList(IList<T> list, Random rg) {
         Contract.Requires<ArgumentNullException>(list != null);
         Contract.Requires<ArgumentNullException>(rg != null);
         this.list = list;
         this.rg = rg;
     }

     public IEnumerator<T> GetEnumerator() {
         List<int> indexes;
         // Random.Next is not guaranteed to be thread-safe
         lock (sync) {
             indexes = Enumerable
                 .Range(0, this.list.Count)
                 .OrderBy(x => this.rg.Next())
                 .ToList();
         }
         foreach (var index in indexes) {
             yield return this.list[index];
         }
     }
}
      IEnumerator IEnumerable.GetEnumerator() {
          return GetEnumerator();
      }
}

A: Create an array of the same size as your list, initially populate it as a[i] = i and then shuffle using a Fisher Yates algorithm.
Your enumerator can then iterate over this array, returning elements from your source list at the random index provided.

A: This should do it:
public static IEnumerable<T> YieldRandom<T>(this IList<T> items) {
    Random random = new Random();
    HashSet<int> yielded = new HashSet<int>(items.Count);

    for (int i=0; i<items.Count; i++) {
        // find an index we haven't yielded yet
        int yieldIndex;
        do {
            yieldIndex = random.Next(items.Count);
        }
        while (yielded.Contains(yieldIndex));

        yielded.Add(yieldIndex);
        yield return items[yieldIndex];
    }
}

I'm sure more LINQ could be used in places :)


text:
Q: connecting to server on one machine from another on same wifi network Probably a simple task, but not so simple for me.
I am running a parse server deployed locally on my laptop.
When i run an software from my laptop with connection string http://localhost:1337/parse it works fine. When i run the software on my another device in same wifi network, obviously localhost does not work.
Laptop with server is on ubuntu.
How do i connect from the other device to my laptop's server?


text:
Q: Systemd - Unknown lvalue 'ConditionEnvironment' in section 'Unit' Simple systemd service not working as expected
Service name: test.service
[Unit]
Description=Test
ConditionEnvironment=STACK=prod

[Service]
Restart=always
ExecStart=/bin/bash -l -c 'echo "do prod stuff!!!"'

[Install]
WantedBy=default.target

sudo systemctl daemon-reload
sudo service test restart
journalctl -u test -f

Systemd is giving an error when I try to use the ConditionEnvironment setting.
Apr 27 13:16:33 ip-172-31-105-2 systemd[1]: Failed to start Test.
Apr 27 13:19:53 ip-172-31-105-2 systemd[1]: /etc/systemd/system/test.service:3: Unknown lvalue 'ConditionEnvironment' in section 'Unit'

Systemd ConditionEnvironment docs

A: While writing this question I found the answer.
The ConditionEnvironment setting was added in systemd version 246.
See release notes here
Seems Ubuntu is shipping with earlier versions.
ubuntu ~$ systemctl --version
systemd 237 (245.4-4ubuntu3.6)

Notes on updating systemd here: https://askubuntu.com/questions/627174/how-would-i-upgrade-systemd


text:
Q: Confused by the many versions of Hahn-Banach Separation Theorem I am studying the Hahn-Banach Separation Theorem. However, there are many versions of the theorem, which is quite confusing. So I want to ask some questions to clarify my confusion.
First, some defintions. The following definitions are adopted from the book Infinite Dimensional Analysis - A Hitchhiker's Guide

Let $X$ be a real vector space and $A, B \subseteq X$ be two
non-empty, disjoint sets. A hyperplane is a set of the form $\{f = c\}$,
where $f: X \to \mathbb{R}$ is a non-zero linear functional and
$c \in \mathbb{R}$. The hyperplane is closed if $X$ is topological
and $f$ is continuous.

*

*We say $A, B$ are weakly separated by a hyperplane $\{f = c\}$ if $ \sup f(A) \leq c \leq \inf f(B) $.

*We say $A, B$ are properly separated by a hyperplane if it separates $A, B$ weakly and does not contain all of $A \cup B$.

*We say $A, B$ are strictly separated by a hyperplane $\{f = c\}$ if $ f(a) < c < f(b) $ for all $a \in A, b \in B$.

*We say $A, B$ are strongly separated by a hyperplane $\{f = c\}$ if $ \sup f(A) < c < \inf f(B) $.

Question 1: Why do we need the extra condition in proper separation? Are there two non-empty, disjoint, convex sets that can be weakly separated but cannot be properly separated?
The first version of Hahn-Banach Separation Theorem is purely algebraic and does not require any topological structure.

Let $X$ be a real vector space and $A, B \subseteq X$ be two
non-empty, disjoint, convex sets. If one of $A, B$ has an internal
point, then they can be properly separated by a hyperplane.

Question 2: Is it true that any internal point $x_0$ of $A$ or $B$ must satisfy $f(x_0) < c$ or $f(x_0) > c$?
The second version is from the wiki page.

Let $X$ be a locally convex topological vector space and
$A, B \subseteq X$ be two non-empty, disjoint, convex sets. If
$A$ has a non-empty interior, then they can be properly separated
by a closed hyperplane $\{f = c\}$. Moreover, any $x_0 \in A^\circ$
must satisfy $f(x_0) < c$.

Question 3: The wiki page requires $X$ to be locally convex. However, from what I have read from "Infinite Dimensional Analysis", it seems that $X$ is only required to be a topological vector space. Does this version still hold if $X$ is merely a topological vector space?

Let $X$ be a topological vector space and $A, B \subseteq X$ be
two non-empty, disjoint, convex sets. If both $A, B$ are open, then
they can be strictly separated by a closed hyperplane.

This seems to be a direct corollary of the previous version, provided that the previous version still holds if $X$ is merely a topological vector space.

Let $X$ be a locally convex topological vector space and $A, B \subseteq X$
be two non-empty, disjoint, convex sets. If $A$ is closed and $B$ is compact,
then they can be strongly separated by a closed hyperplane.

Question 4: I know that if $B$ is merely closed, then we cannot even separate $A, B$ strictly, let alone strong separation. What if we merely need proper separation or weak separation? Can we separate two closed, non-empty, disjoint, convex sets properly or weakly?


text:
Q: Silex in subdirectory on localhost : "Sorry, the page you are looking for could not be found" I know there are SEVERAL similar questions already asked on this topic. I've looked at all of them and none of them have solved my issues. Here's what i have done so far:

*

*Already considered using a Virtual Host (i dont want to, for several reasons)

*Made sure mod_rewrite is on (YES, it is!)

*written an .htaccess file that contains the default
 Silex Webserver Configuration. posted [here](http://silex.sensiolabs.org/doc/web_servers.html) and is contained inside silex/ directory. code below

*Successfully reached the silex/web/index.php page via localhost/~username/silex (so mod_rewrite is definitely working). code below as well

*I echo out a "here!" statement and on silex/web/index.php

*I tried one solution that consisted of placing a second .htaccess file in the silex/web/ dir

.htaccess file:
Options -MultiViews
RewriteEngine On
## this was uncommented because silex is in a subdir
RewriteBase /~username/silex/web
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

/silex/web/index.php file:
require_once __DIR__.'/../vendor/autoload.php';

$app = new Silex\Application();

echo "HELLO";

$app->get('/', function() {
    return 'Hello!';
});

$app->run();

When I get to the silex/web/index.php here's what I get:

I've been working on this for about 2 days now and am starting to lose it.
any help will be greatly appreciated.
thanks.

A: AH HA! i found my answer here -> MAMP Silex htaccess.
I'm hoping this solution will help other people from going though my pain! :)

A: In your .htaccess is missing the rewrite condition for the directory, try this:
<IfModule mod_rewrite.c>
  Options -MultiViews
  RewriteEngine On
  RewriteBase /~username/silex/web
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^ index.php [QSA,L]
</IfModule>

or use
FallbackResource /~username/silex/web/index.php

if your Server is running Apache >= 2.2.16.

A: Expanding on the solution, you need to create an htaccess for the subdirectory containing Silex (and probably Symfony, etc) and tell Apache how to interpret routes.  To paraphrase crzpata's Gist:
<IfModule mod_rewrite.c>
 RewriteEngine on
 #UNCOMMENT next line if silex app root is in a mamp subdirectory
 #RewriteBase /your_mamp_htdocs_silex_app_root
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^ web/index.php [L]
</IfModule>

Then define your silex routes using that defined root:
$app->get('/directory_in_silex_root'...


text:
Q: Resolve: $\ddot{x_1}=2x_1-3x_2, \ddot{x_2}=x_1-2x_2$ Resolve:   $\ddot{x_1}=2x_1-3x_2,  \ddot{x_2}=x_1-2x_2$
I have to $\ddot{x}=\begin{pmatrix}\ddot{x_1}\\ \ddot{x_2}\end{pmatrix}=\begin{pmatrix}2 & -3\\1 & -2\end{pmatrix}\begin{pmatrix}x_1\\ x_2\end{pmatrix}=Ax$ and I know that for a $\dot{x}=Ax$ system the solution is given by $x=e^{At}x_0$, I just know how to apply this to this system, I thought to do the following:
I have to $\ddot{x}=Ax$, could you say that $\dot{x}=e^{At}x_0$ and so $x=e^{e^At}x_0$? Or I have thought of linearizing the system and I already found that $\bar{x}=\begin{pmatrix}0\\ 0\end{pmatrix}$ is equilibrium point and so to solve $\ddot{x}=Ax$, I can solve $\ddot{x}=D_f(\bar{x})x$ and in this way how would I do?Thank you in advance.


text:
Q: objective-c difference between x.y and [x y]? An example that made me ask is:
Xcode tells me to

// Get the new view controller using [segue
  destinationViewController].

but i did it like this
destViewController = segue.destinationViewController;

Im just starting to learn objective-c, i'v only ever wrote c++. Could someone elaborate on the [ ] and the difference between segue.destinationViewController and [segue destinationViewController] and when you should use one or the other? (I don't know what terminology to search)
destinationViewController just holds the pointer to a view controller and is not a method right? This is whats confusing my i thought [x y] syntax is for calling methods so why does xcode tell me to do this?


text:
Q: Migration of database in Rhomobile How do you migrate the data from your database with Property bag model to the application you build in Rho-mobile.
To illustrate this let I have an application in which I have a model Products and three attributes Name,Brand and SDK. I have inserted a number of values into the Products model while it was in development phase and running on emulator.But after building the application I don't see the data which I had inserted while running on the device.

A: There are several caveats when trying to pre-populate information into the database of the app (such as file size in older Android versions and such), but if you are determined, this is the link to the documentation of how to do it:
http://docs.rhomobile.com/faq#how-to-pre-populate-client-database

A: Incase the docs move again, I'll copy it here:

How to pre-populate client database
Run application on target emulator, insert objects to database(locally or get data from server)
Copy all files from 'db' folder on emulator to '/platform\shared\db\res\db'. Here is how to find 'db' emulator folder:

*

*iPhone: look inside log to find paths with guid – this is where
application store files on emulator. Or run search by
'syncdbuser.sqlite' from disk root

*Android: difficult since emulator
is virtual machine and files stored inside emulator. Use adb command
line to find path to application package

*Windows Mobile: open device
explorer from ActiveSync or 'Mobile Device center', navigate to
'Program Files//rho/db'

*Blackberry: open on computer file system –
'/components/simulator/sdcard/Rho//db Build application, now all db
files are in the application package

From my own experience with Android, it's easiest to open the DDMS perspective in Eclipse while an instance of the app is running on an AVD. In the File Explorer tab, navigate to /data/data/your.packagename.app/rhodata/db, and you'll find the database files to copy to the target directory.


text:
Q: Recursive XSLT transformation with attributes With the following XML :
<Sections>

</Sections>

I want to produce the following output :
<Sections><Type1 Text="blabla1"><Type2 Text="blabla2"/></Type1></Sections>

I'm playing with XSLT since many hours, I cant even figure out something to start with... There are many good example on XLST transformation but I'm still missing something about recursivity and using the Type attribute to create my node.  How to transform any section node in the document to its corresponing type attribute?
Any tutorial that do something similar , xslt resources or anything to start with whould be great
Thanks

A: How's this (as requested in comments, modified to convert in both directions):
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

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

  <xsl:template match="@Type" />

  <xsl:template match="Section">
    <xsl:element name="{@Type}">
      <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
  </xsl:template>

  <xsl:template match="Sections//*[not(self::Section)]">

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

  </xsl:template>

</xsl:stylesheet>

Output when run on your first example:
<Sections>
  <Type1 Text="blabla1">
    <Type2 Text="blabla2" />
  </Type1>
</Sections>

Output when run on your second example:
<Sections>

</Sections>


text:
Q: Java 8 - triple nested for loops I have written the below code in Java and trying to convert the same to Java 8.
The code works as expected for the input (a List created by createTempList method) and output(a map whose key is the 1st decimal of the string and value is the other decimals of the string)
public static void main(String[] args) {
    List<String> tempList = createTempList();
    createMap8(tempList);
}

public static Map<String,List<String>> createMap8(final List<String> tempList) {
    Map<String,List<String>> vlanFoos = new HashMap<String,List<String>>();
    for(int i=0; i< tempList.size(); i++) {
        String[] idsI = tempList.get(i).split("\\.");
        String vlanI = idsI[0];
        List<String> fooList = new ArrayList<String>();
        for(int j = 0 ; j < tempList.size() ; j ++) {
            String foo = "";
            String[] idsJ = tempList.get(j).split("\\.");
            String vlanJ = idsJ[0];
            if(vlanI.equals(vlanJ)) {
                        for(int k = 1; k < idsJ.length; k++) {
                            foo = foo + idsJ[k];
                            if(idsJ.length - k != 1) {
                                foo = foo + ".";
                            }
                        }
            }
            if(!foo.isEmpty()) {
                fooList.add(foo);
            }
        }
        vlanFoos.put(vlanI, fooList);
    }
    return vlanFoos;
}

Input :
private static List<String> createTempList() {
    List<String> tempList = new ArrayList<String>();
    tempList.add("1.24.75.13.45.91.0");
    tempList.add("1.88.213.110.66.182.127");
    tempList.add("1579.204.45.224.38.12.161");
    tempList.add("1580.204.45.224.38.12.161");
    tempList.add("21.204.45.224.38.12.161");
    tempList.add("39.204.45.224.38.12.161");
    tempList.add("5.12.244.213.2.178.192");
    tempList.add("5.204.45.224.38.12.161");
    tempList.add("5.212.202.109.116.154.217");
    tempList.add("5.212.202.109.116.154.218");
    tempList.add("5.40.153.58.148.24.67");
    tempList.add("5.76.177.205.33.164.80");
    tempList.add("5.84.236.47.13.223.64");
    tempList.add("5.88.213.110.66.182.128");
    return tempList;
}

Output :
 {1=[24.75.13.45.91.0, 88.213.110.66.182.127],
 1579=[204.45.224.38.12.161],
 5=[12.244.213.2.178.192, 204.45.224.38.12.161, 212.202.109.116.154.217, 212.202.109.116.154.218, 40.153.58.148.24.67, 76.177.205.33.164.80, 84.236.47.13.223.64, 88.213.110.66.182.128],
 39=[204.45.224.38.12.161],
 1580=[204.45.224.38.12.161],
 21=[204.45.224.38.12.161]}

A: This is probably the most concise way to do it:
public static Map<String, List<String>> createMap8(final List <String> tempList) {
    return tempList.stream()
                   .map(s -> s.split("\\.", 2))
                   .collect(groupingBy(p -> p[0], mapping(a -> a[1], toList())));
}

For the createTempList method, you can just use Arrays.asList

A: After modifying your data you can do this:
Map<String, List<String>> map = tempList.stream()
         .map(t -> t.split("\\.", 2))
         .collect(Collectors.toMap(a -> a[0], v -> new ArrayList<>(singletonList(v[1])),
                                   (l1, l2) -> {l1.addAll(l2); return l1;}
                                  )
                 );

A: I suggest you create another class to do the string parsing stuff:
// please give this a better name!
// I don't know what the numbers mean, but you should!
class MyObject {
    private String key;
    private String value;

    public String getKey() {
        return key;
    }

    public String getValue() {
        return value;
    }

    public MyObject(String s) {
        // here I split the string into the first and the rest
        String[] parts = s.split("\\.", 2);
        key = parts[0];
        value = parts[1];
    }
}

Then with streams, the grouping by can be done like this:
public static Map<String,List<String>> createMap8(final List<String> tempList) {

    return tempList.stream().map(MyObject::new).collect(
            Collectors.groupingBy(
                    MyObject::getKey, Collectors.mapping(MyObject::getValue, Collectors.toList())
            )
    );
}


text:
Q: Animation theory (natural animations) I want, for example: to animate how a bird is flying through the sky, i am not talking about the animation of the wings, but how to animate an object random over a canvas.
I use to animate those kind of objects with a lot of randomisation, for example: move [object] from a to b (random distance, random speed, random x, random y, etc.).
But is that really the best way to do it? or is there any algorithm theory available on how to achieve the most natural behaviour.
The animation can be a bird, but it could also be dust, or flying sand)
(I hope my question is clear enough)

A: In fact, a bird is rarely on its own in the sky, maybe you could have a look at flocking behavior of boids.
They basically lie on 3 rules known as

*

*separation: steer to avoid crowding local flockmates alignment:

*steer towards the average heading of local flockmates cohesion:

*steer to move toward the average position (center of mass) of local
  flockmate

This said you can imagine it is a bit different from sand and dust movement calculation, because these are actual physics problem (mostly fluid mechanics navier stokes)
But I'm pretty sure if you don't actually want to be accurate (navier stokes aren't accurate) you could hack some of boids rules to move particles.

A: Answer extracted from this post

Lévy flights or brownian motion should work. These are random walks
  where at each time step the insect moves a random direction and
  distance. They differ in what distribution the random variables are
  sampled from.
The motion of hunting sharks can be modeled as brownian motion when
  prey is plentiful and lévy flight when prey is scarce.
Depending on what you use it for, you might want to restrict their
  motion (to keep them near a specific part of a level) or limit the
  acceleration (to make them appear to have have more inertia).


text:
Q: ORA-00904: "DBMS_METADATA"."GET_DDL": invalid identifier I get the ORA-00904: "DBMS_METADATA"."GET_DDL": invalid identifier error when I run dbms_metadata.
That error is for having the wrong column name or alias. I am not sure why I am getting it.
Here is some code to show the error: I create a table:
create table test_table (
   column1 varchar2(300));

I insert a row of data:
insert into test_table values (55);

I try to get the DDL for it:
SELECT DBMS_METADATA.GET_DDL('TABLE','test_table') FROM dual;

Here is the error:
>> SELECT DBMS_METADATA.GET_DDL('TABLE','test_table') FROM dual
       *
Error at line 1
ORA-00904: "DBMS_METADATA"."GET_DDL": invalid identifier

I checked permissions and it appears I have the correct permissions:
select * FROM DBA_ROLE_PRIVS where granted_role = 'SELECT_CATALOG_ROLE';

My user (aka schema) is in that list.
Here are, what I believe, the docs: https://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_metada.htm#i1016867

A: Run this command as SYS:
grant execute on sys.dbms_metadata to public;

Granting access to your specific user may have solved your current problem, but that package really needs to be available to the entire system.  Many third party programs depend on DBMS_METADATA.  By default that package should be granted to PUBLIC.
Some old versions of the STIG (Secure Technical Implementation Guidelines, which almost every auditor uses as the basis for their security scripts), would revoke access from public packages.  But that was a stupid idea even 10 years ago, and it's not in the current STIGs anymore anyway.


text:
Q: iOS vpn Using the MS Defender app Anyone 1noticed the MS defender app VPN not working on the iPhone.   The iPhone actually shows the vpn is connected, but in WiFiMan the phone shows connected to the cell co. With the vpn server missing? Wandering if this started after the iOS 16 upgrade, I did the other day, did not really pay attention.  The cloudflare and google vpn working fine

A: The defender vpn started working again per wifiman (other net tools also). For several days a lot of people did not have VPN connection, even though their iPhone showed they did…