text:
Q: JBOSS Exception formatter for MySQL We have a solution that uses JBoss and Oracle, in the datasource configuration file it makes reference to a OracleXAExceptionFormatter class. We are migrating from Oracle to MySQL, my question is does JBoss have an equivalent exception formatter class for MySQL or at least a generic equivalent?
<datasources>
  <xa-datasource>
    <jndi-name>datasource.nikecms</jndi-name>
    <track-connection-by-tx/>
    <isSameRM-override-value>false</isSameRM-override-value>
    <xa-datasource-class>oracle.jdbc.xa.client.OracleXADataSource</xa-datasource-class>
    <xa-datasource-property name="URL">jdbc:oracle:thin:@ppg-oracledev:1521:devdb</xa-datasource-property>
    <xa-datasource-property name="User"></xa-datasource-property>
    <xa-datasource-property name="Password"></xa-datasource-property>
    <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</exception-sorter-class-name>
    <no-tx-separate-pools/>
      <metadata>
         <type-mapping>Oracle10g</type-mapping>
      </metadata>
  </xa-datasource>

  <mbean code="org.jboss.resource.adapter.jdbc.vendor.OracleXAExceptionFormatter"
         name="jboss.jca:service=OracleXAExceptionFormatter">
    <depends optional-attribute-name="TransactionManagerService">jboss:service=TransactionManager</depends>
  </mbean>

</datasources>

A: according to the documentation there is a MySQLExceptionSorter available, but no other ExceptionFormatters than the one for oracle.
In $JBOSS_HOME/docs/example/jca is an example how to configure the mysql-ds.
You probably don't need this mbean any longer.


text:
Q: How do I connect local nodeJS server with MySQL which is running on AWS? Here is my code to connect with MYSQL, I am getting connection timeout error :
This is my connection file to connect with MYSQL :
/*
* @sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*/

var mysql = require('mysql');
var sqlConnection = function sqlConnection(sql, values, next) {

    // It means that the values hasnt been passed
    if (arguments.length === 2) {
        next = values;
        values = null;
    }
    var connection = mysql.createConnection({
        "host": process.env.dbHost,
        "user": process.env.dbUser,
        "password": process.env.dbPass,
        "database": process.env.dbName,
        "port":process.env.dbPort
    });
    connection.connect(function (err) {
        if (err !== null) {
            console.log("[MYSQL] Error connecting to mysql:" + err + '\n');
        }
        else {
            console.log("Connection is available");
        }
    });

    connection.query(sql, values, function (err) {
        connection.end(); // close the connection

        if (err) {
            throw err;
        }

        // Execute the callback
        next.apply(this, arguments);
    });
};

module.exports = sqlConnection;

This is the error what I am getting :
Error: connect ETIMEDOUT
    at Connection._handleConnectTimeout (/home/himanshu/node_modules/mysql/lib/Connection.js:411:13)
    at Object.onceWrapper (events.js:313:30)
    at emitNone (events.js:106:13)
    at Socket.emit (events.js:208:7)
    at Socket._onTimeout (net.js:420:8)
    at ontimeout (timers.js:482:11)
    at tryOnTimeout (timers.js:317:5)
    at Timer.listOnTimeout (timers.js:277:5)
    --------------------

I think I am doing something wrong in the config file which looks like, I don't know what to provide in db HOST or How actually I can connect with aws mysql db :
dbHost=00.00.000.000 // aws instance ip
dbName=HIMANSHU
dbUser=ROOT
dbPass=PASSWORD
dbPort=3360

A: @Himanshu Just check the Inbound rule of your Instance.
As per your code, it looks like you are running MySQL in your EC2 machine.
So just make sure, you have allowed 3306 port in your Inbound rules and outbound rules also

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS gradient fits only viewport In the following page, the css gradient is correctly rendert, if the viewport is higher than #container (600px). But if the viewport is only 400px, then the gradient is missing at the bottom 200px (outside the viewport).
How can I fix that?
<!doctype html>

  <meta charset="utf-8">
  <title>Test-Site for css gradient</title>

</webl:context>

EDIT: Here you can see it online: Test-Site

A: Have to ever try this style in #container:
display:block;
overflow:hidden;

A: This happens because height: 100% sets the height of the document, the  element, and your
 to match the viewport (which, in this case, is less than the height of the content).
Add min-height: 600px to html, body, #body-wrapper?


text:
Q: How to retrieve variable from swift class to objective c class I am trying to retrieve some variables from my swift class in my objective c class. How can I do that.
I tried this but it doesn't retrieve the value when I debug it. And it says unresolved identifier while typing it in.
UGPaymentBankAccController *PaymentSwift = [[UGPaymentBankAccController alloc] init];
PaymentSwift.cityAddress.text


text:
Q: Installing Chef-Server on Fedora 18 I am trying to install chef-server on a Fedora 18 aws small instance. The first steps that I have done are the following:
yum update
rpm -Uvh http://rbel.frameos.org/rbel6

With the intention of bring the Fedora 18 instance up to the latest updates and installing the repo from which I will install the chef-server from.
The next step I did was the following:
yum --disablerepo="*" --enablerepo="rbel6" install rubygem-chef-server

Which causes me the following problem which I will be needing your assistance in. Note that I am purposely disabling the other repos because it would appear that some of the packages that are outdated versions that don't seem to be available from the fedora repo.
Error: Package: rubygem-chef-server-0.10.6-1.el6.noarch (rbel6)
       Requires: java-1.6.0-openjdk
Error: Package: couchdb-0.11.2-2.el6.x86_64 (rbel6)
       Requires: libicudata.so.42()(64bit)
Error: Package: rubygem-chef-server-0.10.6-1.el6.noarch (rbel6)
       Requires: libxml2-devel
Error: Package: rubygem-chef-server-0.10.6-1.el6.noarch (rbel6)
       Requires: ntp
Error: Package: ruby-libs-1.8.7.352-4.el6.x86_64 (rbel6)
       Requires: libdb-4.7.so()(64bit)
Error: Package: erlang-R12B-5.10.el6.x86_64 (rbel6)
       Requires: tk
Error: Package: couchdb-0.11.2-2.el6.x86_64 (rbel6)
       Requires: libicuuc.so.42()(64bit)
Error: Package: rubygem-chef-server-0.10.6-1.el6.noarch (rbel6)
       Requires: java-1.6.0-openjdk-devel
Error: Package: ruby-libs-1.8.7.352-4.el6.x86_64 (rbel6)
       Requires: libgdbm.so.2()(64bit)
Error: Package: couchdb-0.11.2-2.el6.x86_64 (rbel6)
       Requires: libicui18n.so.42()(64bit)
Error: Package: erlang-R12B-5.10.el6.x86_64 (rbel6)
       Requires: libodbc.so.2()(64bit)

After dealing with the dependencies that I could easily resolve:
yum install ntp
yum install tx
yum install libxml2-devel

After running the command : yum install 'libodbc.so.2' and successfully installing the package :
yum install 'libodbc.so.2'
Package unixODBC-2.3.1-2.fc18.i686 already installed and latest version

I am still getting the error message:
Error: Package: erlang-R12B-5.10.el6.x86_64 (rbel6)
       Requires: libodbc.so.2()(64bit)

I am not sure why I am getting this error and I would appreciate any help in explaining the issue to me and helping me resolve it.
The other packages were not in the fedora repo so I googled for the rpms, downloaded them using wget, and installed them using yum install (if there is a better way to do this please tell me because it can be a pain, esp when there may be more dependencies):
wget ftp://rpmfind.net/linux/fedora/linux/releases/18/Everything/x86_64/os/Packages/u/unixODBC-2.3.1-2.fc18.i686.rpm
yum install unixODBC-2.3.1-2.fc18.i686.rpm
wget ftp://ftp.muug.mb.ca/mirror/fedora/linux/updates/16/x86_64/java-1.6.0-openjdk-devel-1.6.0.0-71.1.11.6.fc16.x86_64.rpm
yum install java-1.6.0-openjdk-1.6.0.0-71.1.11.6.fc16.x86_64.rpm
yum install java-1.6.0-openjdk-devel-1.6.0.0-71.1.11.6.fc16.x86_64.rpm

Which leaves me wit this error message after doing all of the above:
Error: Package: erlang-R12B-5.10.el6.x86_64 (rbel6)
       Requires: libodbc.so.2()(64bit)
Error: Package: ruby-libs-1.8.7.352-4.el6.x86_64 (rbel6)
       Requires: libgdbm.so.2()(64bit)
Error: Package: ruby-libs-1.8.7.352-4.el6.x86_64 (rbel6)
       Requires: libdb-4.7.so()(64bit)

I am not sure what I can do about libgdbm since it appears to a core package and is already installed so not sure what it isn't being detected and I haven't tried installing libdb-4.7.so as I want to get the first two issues resolved. Any advice on how I should proceed from here?
P.S. I apologize for the level of details here. I was hoping that someone would look at what I am doing and tell me that there is a better way of doing this since I just learned how to do these kinds of things ad hoc.

A: I would assume you those packages are looking for 64Bit version of that lib.
So,
'sudo yum search unixODBC'

comes up with this package "unixODBC-2.3.1-2.fc18.x86_64.rpm"


text:
Q: Button displayed on next screen I have a button on one fragment designed as follows :
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:tag="ActivityFragment"
    android:id="@+id/fragment_activity_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
...
...

<Button
        android:id="@+id/btnCreateActivity"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_gravity="right|top"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/create"
        />
</FrameLayout>

OnClick of this button, I am moving to another fragment :
btnCreateActivity.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    FragmentManager fm = getActivity().getSupportFragmentManager();
                    FragmentTransaction transaction = fm.beginTransaction();
                    transaction.addToBackStack(null);
                    transaction.setCustomAnimations(R.anim.enter_anim, R.anim.exit_anim, R.anim.enter_anim, R.anim.exit_anim);
                    WebFragment fragment = WebFragment.newInstance(Globals.TGURL_CREATE_ACTIVITY, "");
                    transaction.replace(R.id.fragment_activity_layout, fragment);
                    transaction.commit();
                }
            });

When the WebFragment (next screen) loads, btnCreateActivity is still there.
fragment_web layout :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent"
    android:id="@+id/webFragment"
    android:layout_height="fill_parent"
    tools:context="truegroups.activities.WebFragment"
    android:background="#ffffff">
        <WebView
            android:id="@+id/webFragment_webview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            />
</RelativeLayout>

This is specific only to few devices like Galaxy Note 3, Galaxy S3.

On rest of devices it works correctly and the button is not displayed on next screen.
Why so ?

A: The new fragment which you have called, comes on the top of the stack. Since it has transparent/null background, so the controls on the lower fragment remains visible.

A: Put your button out side of framelayout


text:
Q: Getting Primary Key from database (Python / Django) I'm trying to use Hashids which works when I manually input the number to encode, but doesn't work if I try to get it to encode the Primary Key from each table row.
models.py
from hashids import Hashids
from django.db import models

class AddToDatabase(models.Model):

    hashids = Hashids()
                                  # hasids.encode(123) works correctly
    slug = models.CharField(default=hashids.encode(pk), max_length=12)

The above says pk is undefined, regardless of what I try to import.

A: You cannot do what you are trying now(Since pk will get value only after INSERT operation). One option is
class AddToDatabase(models.Model):
    hashids = Hashids()
    slug = models.CharField(max_length=12)

    def save(self, *args, **kwargs):
        super(AddToDatabase, self).save(*args, **kwargs)
        self.slug = self.hashids.encode(self.pk)
        super(AddToDatabase, self).save(*args, **kwargs)

A: Another solution is calculating hashid on demand
class AddToDatabase(models.Model):

    @property
    def slug(self):
        hashids = Hashids()
        return hashids.encode(self.pk)


text:
Q: Assign value to cell with button press in google sheet modalDialog I have a google sheet with client data.
I use the phone number as a unique ID. I know it's not ideal, I'll change it later, for now it's fine.
On an other sheet, Column B is the user name, Column C is phone number, with data validation range on the client data sheet.
Whenever there is a new entry in Column B, the function selectClient(clientName) is called. clientName is an array with the names and phone numbers that match the entered name.
It displays a popup HTML, with buttons for each row of the array.
I need to set the value of the Column C in the row where the new entry is made, with the phone number in the HTML button that is pressed.
What is the simplest way?
function selectClient(clientName){
  var phoneRows = lookUpClientPhone(clientName);
  var t = HtmlService.createTemplateFromFile('test');
  t.data = phoneRows;
  html = t.evaluate();
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(html, 'Egyező nevek');
}

 function lookUpClientPhone(clientName){
  var ugyfelRange = SpreadsheetApp.getActiveSpreadsheet().getRange('Ügyfél!B2:D');
  var ugyfelRangeSize = realRangeHeight(ugyfelRange);
  ugyfelRangeSize++;
  ugyfelRange = SpreadsheetApp.getActiveSpreadsheet().getRange('Ügyfél!B2:D'+ ugyfelRangeSize);
  var clientPhone = ugyfelRange.getValues();
  clientPhone = clientPhone.filter(function(row){
    return removeAccents(row[0]).toLowerCase() === removeAccents(clientName).toLowerCase()});
  return clientPhone;
}

The HTML part:
<!DOCTYPE html>

    <base target="_top">

      <? for (var i = 0; i < data.length; i++) { ?>

            <button id="button<?i?>" type="submit" onClick="" value="<? data[i][2] ?>"><?= data[i]?></button>

      <? } ?>


text:
Q: Creating a nested matrix from two lists I have a matrix and two lists:
matrix = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
a = {{1, 2, 2, 1}, {3, 4, 4, 3}, {8, 5, 5, 8}};
d = {{I, 2, -I}, {I, 1, -1}, {4, I, 0}};

I am trying to do write a code as psudo-code here to joined a and b and add them to matrix:
Do[matrix[[i, j]] = AppendTo[a[[i]], a[[j]]], {i, 0, 3}, {j, 0, 3}];

the desired result is as below
matrix =
  {{{1, 2, 2, 1, 1, 2, 2, 1, d[[1, 1]]},
    {1, 2, 2, 1, 3, 4, 4, 3, d[[1, 2]]},
    {1, 2, 2, 1, 8, 5, 5, 8, d[[1, 3]]}},
   {{3, 4, 4, 3, 1, 2, 2, 1, d[[2, 1]]},
    {3, 4, 4, 3, 3, 4, 4, 3, d[[2, 2]]},
    {3, 4, 4, 3, 8, 5, 5, 8, d[[2, 3]]}},
   {{8, 5, 5, 8, 1, 2, 2, 1, d[[3, 1]]},
    {1, 2, 2, 1, 3, 4, 4, 3, d[[3, 2]]},
    {8, 5, 5, 8, 8, 5, 5, 8, d[[3, 3]]}}};

I would be so glad to have a way to obtain the result. Also, it will be good if I have a final matrix in horizontal shape for its sub_matrices in the nested final matrix instead of column shape for them.

A: MapThread[
 Append,
 {Outer[Join, a, a, 1], d},
 2
 ]

A: Xavier's comment with an additional Partition gives:
Partition[Flatten /@ Transpose[{Tuples[a, {2}], Flatten@d}], Length@d]

I think this is what the OP had in mind but it doesn't correspond to the next to last row of his "desired result."

A: Let's build your matrix in three steps.
a = {{1, 2, 2, 1}, {3, 4, 4, 3}, {8, 5, 5, 8}};
d = {{I, 2, -I}, {I, 1, -1}, {4, I, 0}};

m1 = Join[#, #] & /@ a

{{1, 2, 2, 1, 1, 2, 2, 1},
 {3, 4, 4, 3, 3, 4, 4, 3},
 {8, 5, 5, 8, 8, 5, 5, 8}}

m2 = ConstantArray[#, 3] & /@ m1

{{{1, 2, 2, 1, 1, 2, 2, 1},
  {1, 2, 2, 1, 1, 2, 2, 1},
  {1, 2, 2, 1, 1, 2, 2, 1}},
 {{3, 4, 4, 3, 3, 4, 4, 3},
  {3, 4, 4, 3, 3, 4, 4, 3},
  {3, 4, 4, 3, 3, 4, 4, 3}},
 {{8, 5, 5, 8, 8, 5, 5, 8},
  {8, 5, 5, 8, 8, 5, 5, 8},
  {8, 5, 5, 8, 8, 5, 5, 8}}}

matrix = MapThread[Append, {m2, d}, 2]

{{{1, 2, 2, 1, 1, 2, 2, 1, I},
  {1, 2, 2, 1, 1, 2, 2, 1, 2},
  {1, 2, 2, 1, 1, 2, 2, 1, -I}},
 {{3, 4, 4, 3, 3, 4, 4, 3, I},
  {3, 4, 4, 3, 3, 4, 4, 3, 1},
  {3, 4, 4, 3, 3, 4, 4, 3, -1}},
 {{8, 5, 5, 8, 8, 5, 5, 8, 4},
  {8, 5, 5, 8, 8, 5, 5, 8, I},
  {8, 5, 5, 8, 8, 5, 5, 8, 0}}}

This, of course, can be nested into one expression.
matrix = MapThread[Append, {(ConstantArray[#, 3] & /@ (Join[#, #] & /@ a)), d}, 2]

But it is much harder to understand how it works in that form.
Update
Another approach to solving this problem is to break it into two parts -- to first write a helper function that can generate any single row of the desired matrix and then map that function over the two given matrices to produce the desired matrix.
helper[aRow_, dRow_] :=
  MapThread[Append, {ConstantArray[Join[aRow, aRow], 3], dRow}]

matrix = MapThread[helper, {a, d}]

Update 2
matrix // MatrixForm


text:
Q: Update text outside of partialview .Net 6 I have created a table from a list of objects, using a partialview. Using an ajax call(so the page doesnt have to refresh), when a user searchs, filters, etc, it updates the entries in the table(partialview) using a controller method.
Outside of the partial view, above the table, there is a "TotalHours" field that shows the total hours of the labor entries that are currently displayed in said table.
I was originally using a TempData variable in the controller method to update the "TotalHours" field each time a filter or search was applied, but for some reason, the table didnt refresh with search/filtered entires. If I remove the TempData variable, the search/filter function I created works perfectly.
My question is, what do I need to do to update the "TotalHours" field that is outside the partialview that is being refreshed? It is calculated by sum of "Hours" variables in the list of objects that are used in the table.
Controller code, with the TempData variable still included even though it doesnt update the partialview in the view:
[HttpPost]
        public async Task<PartialViewResult> GetRows(Guid? cust, Guid? task, int? workType, int? weekFrom, int? weekTo, int? yearFrom, int? yearTo,
            string startDate = "", string endDate = "", string search = "",string sortName = "", string sortDir = "")
        {
            var model = new List<TimeEntryViewModel>();
            try
            {
                var timeRepo = new TimeRepository(_context);
                var customerRepo = new CustomerRepository(_context);
                var taskRepo = new TaskRepository(_context);
                var user = await _userManager.GetUserAsync(User);
                var entries = await timeRepo.GetTimeEntriesByUserID(user.Id);
                DateTime startWeekYearDate;
                DateTime endWeekYearDate;
                int?[] weekYears = { weekFrom, weekTo, yearFrom, yearTo };

                var entriesFiltered = entries.Where(r => r.CustomerID == cust || cust.Equals(Guid.Empty) || cust == null)
                    .Where(r => r.TaskID == task || cust.Equals(Guid.Empty) || task == null)
                    .Where(r => r.WorkTypeID == workType || workType == null || workType == 0)
                    .ToList();

                if (weekYears.All(x => x.HasValue))
                {
                    startWeekYearDate = new DateTime((int)yearFrom, 1, 1);
                    endWeekYearDate = new DateTime((int)yearTo, 1, 1);
                    startWeekYearDate = startWeekYearDate.AddDays(7 * (int)weekFrom).AddDays(-7);
                    endWeekYearDate = endWeekYearDate.AddDays(7 * (int)weekTo);

                    entriesFiltered = entriesFiltered.Where(r => r.Start >= startWeekYearDate)
                        .Where(r => r.End <= endWeekYearDate).ToList();
                }
                if (!string.IsNullOrEmpty(startDate))
                {
                    entriesFiltered = entriesFiltered.Where(r => r.Start >= DateTime.Parse(startDate)).ToList();
                }
                if (!string.IsNullOrEmpty(endDate))
                {
                    entriesFiltered = entriesFiltered.Where(r => r.End <= DateTime.Parse(endDate)).ToList();
                }

                foreach (var entry in entriesFiltered)
                {
                    var entryVm = _mapper.Map<TimeEntryViewModel>(entry);

                    var customer = await customerRepo.GetCustomerByID(entry.CustomerID);
                    var task1 = await taskRepo.GetTaskById(entry.TaskID);
                    entryVm.Customer = customer;
                    entryVm.Task = task1;
                    entryVm.EmployeeName = user.FirstName + " " + user.LastName;
                    entryVm.CustomerName = customer.CustomerName;
                    entryVm.TaskName = task1.Name;

                    model.Add(entryVm);
                }

                if (!string.IsNullOrEmpty(search))
                {
                    model = model.Where(r => r.EmployeeName.Contains(search)
                    || r.CustomerName.Contains(search) || r.TaskName.Contains(search)).ToList();
                }

                model = TimeEntryViewModel.SortList(model, sortName, sortDir);
            }
            catch (Exception e)
            {
                _logger.LogError(e.Message, e);
            }
            var totalHours = 0.0;
            foreach(var m in model)
            {
                totalHours += m.TotalHours;
            }
            TempData["Total"] = Math.Round(totalHours, 2);

            return PartialView("_entryRows", model);
        }

PartialView cshtml:
@using TimeLogger.Core.Enums
@using TimeLogger.ViewModels
@model List<TimeEntryViewModel>

    @foreach(var entry in Model)
            {

                    @entry.EmployeeName
                    @entry.Start
                    @entry.End
                    @entry.TotalHours
                    @entry.CustomerName
                    @entry.TaskName
                    @Enum.GetName(typeof(WorkType), entry.WorkTypeID)

                        <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown">
                        @*
                        *@
                        </button>

                            Edit
                            Delete

            }

View that renders partialview:
@using TimeLogger.Core.Enums
@using TimeLogger.ViewModels
@model List<TimeEntryViewModel>
@{
    ViewData["Title"] = "Time Entries";
}

                    <input class="form-control w-100" placeholder="" id="searchBox">

                    Total Hours: @TempData["Total"]

            <button class="btn btn-primary addEntry">Add Entry  </button>
                <button class="btn filter" onclick="toggleDiv('filters'); return false">Filters  </button>

                    Customer: @Html.DropDownList("Customers", (IEnumerable<SelectListItem>)ViewBag.Customers, new { @class = "form-control", @id = "customerDropDown" })

                    Task: @Html.DropDownList("Tasks", (IEnumerable<SelectListItem>)ViewBag.Tasks, new { @class = "form-control", @id = "tasksDropDown" })

                    Work Type: @Html.DropDownList("WorkTypes", (IEnumerable<SelectListItem>)ViewBag.WorkTypes, new { @class = "form-control", @id = "workTypesDropDown" })

                        From Week: @Html.DropDownList("WeekFrom", (IEnumerable<SelectListItem>)ViewBag.Weeks, new { @class = "form-control", @id = "weekFromDropDown" })

                        To Week: @Html.DropDownList("WeekTo", (IEnumerable<SelectListItem>)ViewBag.Weeks, new { @class = "form-control", @id = "weekToDropDown" })

                        From Year: @Html.DropDownList("YearFrom", (IEnumerable<SelectListItem>)ViewBag.Years, new { @class = "form-control", @id = "yearFromDropDown" })

                        To Year: @Html.DropDownList("YearTo", (IEnumerable<SelectListItem>)ViewBag.Years, new { @class = "form-control", @id = "yearToDropDown" })

                          Start Date

                          <input placeholder="Select date" type="text" id="startDateFilter" class="form-control" disabled="disabled">

                            End Date

                          <input placeholder="Select date" type="text" id="endDateFilter" class="form-control" disabled="disabled">

                    <button onclick="filter(); return false" class="btn btn-primary">Filter</button>
                    <button id="dateWeeksToggle" onclick="toggleDatesWeeks(); return false" class="btn btn-info">Filters for Dates</button>

                    <button onclick="clearFilter(); return false" type="reset" class="btn btn-secondary">Clear Filters</button>

                        Employee
                        Start Time
                        End Time
                        Hours
                        Customer
                        Task
                        Work Type

                    @await Html.PartialAsync("_entryRows", Model)

A: One easy option that comes to mind would be to add a hidden input to your partial view and set it's value to the Total Count of TempData, then in your ajax use this hidden value to set the one outside of your partial view:
Partial View:
....
<input type="hidden" id="hdnhourlytotal" value="@(TempData["total"] ?? 0)" />
@foreach(var entry in Model)
....

ajax:
success: function(data) {
   //add view to DOM
  ....
  //set the element outside of your partial using hidden input
  const totalfromhidden = parseFloat(document.getElementById("hdnhourlytotal").value);
  document.getElementById("totalHours").textContent = `Total Hours: ${totalfromhidden}`;
}


text:
Q: Using ES lint with browserify, missing fs Module error Im trying to browserify the ESlint (latest version) and the problem that ES lint contain fs module and when I try to use it I got error, any idea how to overcome this ?
I read the following but not sure that I understand if how to solve it,any idea how ?

A: If you are using gulp task to create the eslint bundle then you can use npm package 'vinyl-source-stream' along with browserify.
var gulp = require('gulp');
var gutil = require('gulp-util');
var derequire = require('gulp-derequire');
var source = require('vinyl-source-stream');
var browserify = require('browserify');

gulp.task('js',function(){
    browserify('./app/app.js')
        .bundle()
        .on('error',function(e){
            gutil.log(e);
        })
        .pipe(source('bundle_lint.js'))
        .pipe(derequire())
        .pipe(gulp.dest('./app/dist'));
});

gulp.task('default',['js']);

//app.js file code
var eslint = require('eslint');


text:
Q: how to avoid "duplicate class" in Java Suppose I have have a java project myProject and am using an external library jar (someJar.jar), which has a class com.somepackage.Class1.class.
Now I find an updated version of Class1.java which fixes a bug in the original jar.
I include the new Class1.java in my source code under package com.somepackage
When I build the project (e.g., using Netbeans), there is a dist\myProject.jar which contains the classcom.somepackage.Class1.class and a dist\lib\someJar.jar which also contains a class with the same name.
When I run the file (e.g, using java -jar dist\myProject.jar), the new version of Class1.class is used (as I want).

*

*How does Java decide which class file to run in case of such duplicates? Is there any way I can specify precedence ?

*Is there any 'right' way to avoid such clashes?

*In Proguard, when I try to compress my code, I get a duplicate class error. How do I eliminate this?

A: Can you not create an updated jar file which contains the bug fix? It's going to make things a lot simpler if you don't have two versions of the same fully-qualified class around.

A: *

*Java decides which one to use based on the order of the classpath. List yours first and you'll be fine.

*The "right" way would be to fix the orignal source, but sometimes that's not always an option.

*I haven't used ProGuard, but I have re-jarred libaries before that had duplicate classes. The solution in my case was to tell Ant to ignore duplicate classes. I would assume ProGuard would have that support too.

A: 1) Updated Jar is a better solution.
2) Use a different class name. Is there a reason, why you want to use the same class name and same packing? I don't think there is a reason.
3) create a wrapper/ proxy class, that encapsulate all the calls to the jar and you can decide to call this new class that fixes the bug ( provided it has a different name and packaging)


text:
Q: Can not deploy spring boot application to the heroku I try to deploy my spring boot application on the Heroku . I connect my github to the Heroku and create clearDB for the application. After when deploy success I go to the application. But in the logs of the heroku shows me 2020-02-24T20:00:33.959429+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=POST path="/auth/signin" host=linkedin-search.herokuapp.com request_id=52208cc6-575e-444b-bb45-c3910d49b175 fwd="134.249.164.109" dyno= connect= service= status=503 bytes= protocol=https
My Procfile contains that: web: java -jar target/Linkedin_Search-0.0.1-SNAPSHOT.jar
My pom.xml build section is:
 <build>
     <sourceDirectory>src/main/java</sourceDirectory>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.2.2.RELEASE</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>11</source>
                    <target>11</target>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <version>3.0.1</version>
                    <executions>
                        <execution>
                            <id>copy-dependencies</id>
                            <phase>package</phase>
                            <goals><goal>copy-dependencies</goal></goals>
                        </execution>
                    </executions>
            </plugin>
        </plugins>
    </build>

I do all as in the tutorial on the Heroku dev center but nothing is works.

A: According to your logs this is the root cause for your issue:

2020-02-27T13:58:45.159924+00:00 app[web.1]: no main manifest attribute, in target/Linkedin_Search-0.0.1-SNAPSHOT.jar

The JAR file you create does not have the Main class specified in its manifest. How to fix this really depends on your build setup. I see you're using spring-boot-maven-plugin which usually detects and sets that attribute for you. You can try to configure it explicitly in that plugins configuration section:
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>2.2.2.RELEASE</version>
    <configuration>
        <mainClass>com.example.Main</mainClass>
    </configuration>
</plugin>

You could also specify the main class explicitly in your Procfile:
web: java -cp target/Linkedin_Search-0.0.1-SNAPSHOT.jar com.example.Main

A: i recomend you to push your apllication on GitHub and then  use the automatic deploy from heroku. it is more easy. always  work fine for me.


text:
Q: How to set 2015-01-20 as Jan 15 I have a date that I want to display in SQL Server like this:
 Date=`2015-12-08`

 O/p=Dec 15(I need output like this)

How can I do it? I tried like
SELECT
    LEFT(DATENAME(MONTH, GETDATE()), 3) + ' ' + DATENAME(YEAR, GETDATE()) AS [Mon YYYY]`

But it returns output like Dec 2015 but I need it to be Dec 15

A: try
 SELECT CONVERT(CHAR(4), GETDATE(), 100) + CONVERT(CHAR(4), GETDATE(), 120)

update :
Your can try if you want only jan 15
    SELECT RIGHT(CONVERT(varchar, "yourdate",6),6)

A: try this
SELECT LEFT(CAST(Date as varchar(20)), 3) + '-' + RIGHT(CAST(YEAR(Date) as CHAR(4)), 2) as MonYr

FROM YourTable

A: This is what you are looking for
SELECT RIGHT(CONVERT(varchar, GetDate(),6),6)


text:
Q: SparkR - override default parameters in spark.conf I am using sparkR (spark 2.0.0, yarn) on cluster with following configuration: 5 machines (24 cores + 200 GB RAM each). Wanted to run sparkR.session() with additional arguments to assign only a percentage of total resources to my job:
if(Sys.getenv("SPARK_HOME") == "") Sys.setenv(SPARK_HOME = "/...")

library(SparkR, lib.loc = file.path(Sys.getenv('SPARK_HOME'), "R", "lib"))

sparkR.session(master = "spark://host:7077",
               appname = "SparkR",
               sparkHome = Sys.getenv("SPARK_HOME"),
               sparkConfig = list(spark.driver.memory = "2g"
                                 ,spark.executor.memory = "20g"
                                 ,spark.executor.cores = "4"
                                 ,spark.executor.instances = "10"),
               enableHiveSupport = TRUE)

The weird thing is that parameters seemed to be passed to sparkContext, but at the same time I end with number of x-core executors which make use of 100% resources (in this example 5 * 24 cores = 120 cores available; 120 / 4 = 30 executors).
I tried creating another spark-defaults.conf with no default paramaters assigned (so the only default parameters are those existed in spark documentation - they should be easily overrided) by:
if(Sys.getenv("SPARK_CONF_DIR") == "") Sys.setenv(SPARK_CONF_DIR = "/...")

Again, when I looked at the Spark UI on http://driver-node:4040 the total number of executors isn't correct (tab "Executors"), but at the same time all the config parameters in tab "Environment" are exactly the same as those provided by me in R script.
Anyone knows what might be the reason? Is the problem with R API or some infrastructural cluster-specific issue (like yarn settings)

A: I found you have to use the spark.driver.extraJavaOptions, e.g.
spark <- sparkR.session(master = "yarn",
            sparkConfig = list(
              spark.driver.memory = "2g",
              spark.driver.extraJavaOptions =
              paste("-Dhive.metastore.uris=",
                    Sys.getenv("HIVE_METASTORE_URIS"),
                    " -Dspark.executor.instances=",
                    Sys.getenv("SPARK_EXECUTORS"),
                    " -Dspark.executor.cores=",
                    Sys.getenv("SPARK_CORES"),
                    sep = "")
              ))

Alternatively you change the spark-submit args, e.g.
Sys.setenv("SPARKR_SUBMIT_ARGS"="--master yarn --driver-memory 10g sparkr-shell")


text:
Q: vim custom syntax, highlight class occurrences with different colors I'm new to vim syntax highlight customizations. Trying to create a text based call path description file:
// Entry point
Class1#mainMethod
    Class1#privateMethod2
    Class2#method3
        Class3#method4
    Class4#method5

In plantUML the equivalent would be:
ExternalActor -> Class1 : mainMethod
Class1 -> Class1 : privateMethod2()
Class1 -> Class2 : method3()
Class2 -> Class3 : method4()
Class1 -> Class4 : method5()

I already have some decent syntax file in place that makes it look like:

current syntax file looks like:
syn keyword celTodo contained TODO FIXME XXX NOTE
syn match celComment "//.*$" oneline contains=celTodo
hi celComment ctermfg=yellow
hi celTodo ctermfg=green

syn match methodCall /\(#\)\@<=\w*/ contained oneline
hi methodCall ctermfg=blue

syn match className /\w*\(#\)\@=/ contained oneline
hi className ctermfg=red

syn region line start='\(\.\)\@<=\w' end='.\($\)\@=' oneline fold transparent contains=celComment,className,methodCall

Problem
I think a different background color for each occurrence of the same class would help understand the sequence better.
Is there any way to achieve this? So that Class1 will have a different background color than Class2, 3, and 4. But each class always the same, consistent color.

A: Syntax highlighting associates a keyword, pattern match, or region with a syntax group. A corresponding highlight group then (directly or indirectly through linked groups) determines the color and formatting of the text.
In order to have different (background or otherwise) colors for each class name, you'd have to define different syntax groups, and assign different highlight groups, too. Your syntax file would not only have a fixed set of :syntax match commands, but also a loop that extracts matches from the current buffer and builds the corresponding :syntax match and :highlight command as the syntax loads (using :execute).
Then you have the problem of updating, if the user adds or changes class names. Normally, a syntax is static, so once it loads, it's done. In your case, you'd have to define :autocmds that periodically re-scan the buffer, and add new class names (and maybe even recycle unused highlight group names, so you don't run out of colors). The CursorHold event would be a good candidate for it, but there will be a delay until the colors show up. The available colors is another problem if you want to make this syntax available to other users. The number of colors can vary wildly, and coming up with background colors that work well with various colorschemes is difficult.
Summary
It is possible, but it would be unusual for a syntax, and have side effects like delays in updating or poor performance. (I've seen this used for highlighting function names from the tags file, though.) Some users definitely would want to turn this off.
Alternative
For small files with few (or very distinct) class names, this additional highlighting probably isn't necessary. For large files with many classes, having everything light up would make it appear like a Christmas tree, and all the colors could be more distracting than helpful. I'd rather leave it to the user to do such highlighting of some classes of interest, on demand. My Mark plugin provides the generic functionality for this, in a way that does not interfere with syntax highlighting, and it ships with color palettes that look like text marker highlightings. I use this often to have better orientation in log files or legacy code bases. (The plugin page has links to alternative plugins; there are a few.)
Your syntax

*

*Group names typically have a common prefix that's identical to the name of your syntax. If that is cel, use celMethodCall instead of methodCall, and so on.

*I would put the :hi commands all at the bottom; most syntax plugins do it like this.

*Especially if you intend to later share the syntax, favor :hi linking to existing syntax groups (:help highlight-groups) over defining your own colors. Even for your personal use, defining your colors in your ~/.vimrc has the benefit of having a single place to adapt and reuse it, instead of hunting around various syntax scripts.

*By using :hi def, users can customize the syntax, e.g. in their ~/.vimrc. :help 44.12 has more information on writing syntax plugins.


text:
Q: Wix: show custom dialog if previous version found I want to customize my installer to show custom dialog when previous version is already installed: after Welcome dialog user should see a custom dialog OldVersionDlg with information that previous version was found and will be uninstalled automatically.
But for some reason property set by UpgradeVersion element always null when I check it in condition in UI/Publish Dialog.
Here are essential code snippets.
Product.wxs:
<Product Id="*" Version="$(var.Version)" UpgradeCode="$(var.ProductId)"
         Language="1033" Name="$(var.ProductFullName)" Manufacturer="$(var.Manufacturer)">
  <Package Description="$(var.ProductDescription)" InstallerVersion="200" Compressed="yes"
           Manufacturer="$(var.Manufacturer)" />

  <Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
  <Upgrade Id="$(var.ProductId)">
    <UpgradeVersion Minimum="1.0.0.0" Maximum="$(var.Version)"
                    Property="PREVIOUSVERSIONSINSTALLED"
                    IncludeMinimum="yes" IncludeMaximum="no" />
  </Upgrade>

  <InstallExecuteSequence>
    <RemoveExistingProducts Before="InstallInitialize" />
  </InstallExecuteSequence>
</Product>

WixUI_Wizard.wxs:
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="OldVersionDlg">PREVIOUSVERSIONSINSTALLED</Publish>
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="SetupTypeDlg">NOT Installed</Publish>

The button Next doesn't work.
I've checked in logs that PREVIOUSVERSIONSINSTALLED is set after FindRelatedProducts. If I use it in conditions in Product.wxs then everything is OK. But in UI configuration it is always null.
Thanks for any help.

A: The problem was caused by the second line in WixUI_Wizard.wxs. For some reason WiX always uses it. So, to implement checking of previous version we need to exclude PREVIOUSVERSIONSINSTALLED from the second condition:
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="OldVersionDlg">PREVIOUSVERSIONSINSTALLED</Publish>
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="SetupTypeDlg">NOT Installed AND NOT PREVIOUSVERSIONSINSTALLED</Publish>


text:
Q: can not find logs of resque worker as a systemd service im hosting/supporting a Ruby on Rails application without any Ruby background myself. The application itself is mostly used in germany if i am not mistaking. But my Problem hat nothing really to do with the application but rather with the resque worker which is used.
I configured the resque worker as a systemd service as seen here:
[Unit]
Description=resque-worker for pageflow

[Service]
User=pageflow
WorkingDirectory=/home/pageflow/pageflow_daad
ExecStart=/usr/local/bin/bundle exec /usr/local/bin/rake resque:work >
/home/pageflow/pageflow_daad/log/resquework.log &
#ExecStart=/home/pageflow/.rbenv/shims/rake resque:work &
Environment=QUEUE=*
Environment=RAILS_ENV=production

[Install]
WantedBy=multi-user.target

This worker handles image/video uploads without problems. Now i added a new application feature which crawls specific pages. This process is handled by the worker as well. In this case i end up with an error which i cant find in any logs. To be specific i cant find any logs from the worker or sheduler at all.
I looked in these locations by now:

*

*Applicationroot/log/production.log

*Applicationroot/log/jobs/production (which is not used anymore as told by the app developer)

*/var/log/nginx/error.log

*journalctl -u resque-worker.service

This is the output of systemctl status resque-worker.service
esque-worker.service - resque-worker for pageflow
   Loaded: loaded (/etc/systemd/system/resque-worker.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2021-03-11 13:46:52 CET; 3 days ago
 Main PID: 30864 (bundle)
    Tasks: 5
   Memory: 186.0M
      CPU: 2min 10.308s
   CGroup: /system.slice/resque-worker.service
           └─30864 resque-1.27.4: Waiting for default,mailer,mailers,resizing,scraping,slow

Mar 11 13:46:52 ostheim-stg bundle[30864]: Gem::Specification#rubyforge_project= called from /home/pageflow/pageflow_daad/vendor/bundle/ruby/2.3.0/specifications/zencoder-2.5.1.gemspec:15.
Mar 11 13:46:52 ostheim-stg bundle[30864]: NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Mar 11 13:46:52 ostheim-stg bundle[30864]: Gem::Specification#rubyforge_project= called from /home/pageflow/pageflow_daad/vendor/bundle/ruby/2.3.0/specifications/vegas-0.1.11.gemspec:17.
Mar 11 13:46:52 ostheim-stg bundle[30864]: NOTE: Gem::Specification#rubyforge_project= is deprecated with no replacement. It will be removed on or after 2019-12-01.
Mar 11 13:46:52 ostheim-stg bundle[30864]: Gem::Specification#rubyforge_project= called from /home/pageflow/pageflow_daad/vendor/bundle/ruby/2.3.0/specifications/rufus-scheduler-2.0.24.gemspec:16.
Mar 11 13:46:56 ostheim-stg bundle[30864]: DEPRECATION WARNING: Sprockets method `register_engine` is deprecated.
Mar 11 13:46:56 ostheim-stg bundle[30864]: Please register a mime type using `register_mime_type` then
Mar 11 13:46:56 ostheim-stg bundle[30864]: use `register_compressor` or `register_transformer`.
Mar 11 13:46:56 ostheim-stg bundle[30864]: https://github.com/rails/sprockets/blob/master/guides/extending_sprockets.md#supporting-all-versions-of-sprockets-in-processors
Mar 11 13:46:56 ostheim-stg bundle[30864]:  (called from block in <class:Railtie> at /home/pageflow/pageflow_daad/vendor/bundle/ruby/2.3.0/gems/react-rails-1.8.0/lib/react/rails/railtie.rb:110)

Can anyone give me a hint where to further look for?
A also changed the applications log-level to :info to be sure to not miss any log.
Im using Rails 5.2.0 and Ruby 2.3.1p112
Thanks in advance

A: After hours of research for some reason i now found the logs in the Approot/logs/production.log so the default Rails log location. I really dont know why i missed that beforehand. Maybe because i changed the line of the log level configuration....
So for future reference: even if the the resque worker is handled by systemd the logs still can be found in the application logging as configured in the environments.


text:
Q: Problems while Accessing SharePoint List items in SharePoint 2013 using REST API in NAPA tool I am trying to access the list item using an APP in my office 365 share point hosted trial environment.It seems like the call REST call is failing, the alert in error function is getting executed.
This is the Url https://test.sharepoint.com/sites/AppSite/. I have created an APP called SharePointAppTest under AppSite web. There is a list called TestList created under Appsite web.TestList has an entry with ID as '1' and title as firstValue.
Below is the code I am using to access that item with ID using REST API
(function () {
    $(document).ready(function () {
        getListItem();
    });
    getListItem("https://test.sharepoint.com/sites/AppSite","TestList",1,"complete","failure");
})();

function getListItem(url, listname, id, complete, failure) {
    $.ajax({
        url: url + "/_api/web/lists/getbytitle('" + listname + "')/items(" + id + ")",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: function (data) {
            // Returning the results
            alert("it is a success");
            complete(data);
        },
        error: function (data) {
            alert("it is a failure");
            failure(data);
        }
    });
}

A: It appears that the list resides in Host web instead of the App web. In this case the app needs to be given permission to read the List of the host web. Moreover, the REST call needs to be done using cross domain library. Example of cross domain call using REST:
executor.executeAsync(
    {
        url:
            appweburl +
            "/_api/SP.AppContextSite(@target)/web/title?@target='" +
            hostweburl + "'",
        method: "GET",
        headers: { "Accept": "application/json; odata=verbose" },
        success: successHandler,
        error: errorHandler
    }
);

Read these for more information:
MSDN Article 1
MSDN Article 2

A: When you create or deploy app to the SharePoint it creates a web of its own(even your app may have list and libraries of its own) so app is nothing but a site in your SP, now when you try accessing the your site from this SP App SharePoint won't allow it due to security reasons, and you may get Access Denied error, So to overcome this you need to make a Cross Domain Call (a request from your App Domain/App web to your Site Domain/Host web)
For a app web you can access data as
 executor.executeAsync(
            {
              url:
                  appweburl +
                  "/_api/web/lists/getbytitle('Announcements')/items",
              method: "GET",
              headers: { "Accept": "application/json; odata=verbose" },
              success: successHandler,
              error: errorHandler
            }

While in case of a host web you need to change the context to the the context of Host web so you have to do it as below
executor.executeAsync(
{
    url:
        appweburl +
        "/_api/SP.AppContextSite(@target)/web/title?@target='" +
        hostweburl + "'",
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    success: successHandler,
    error: errorHandler
}

See the difference in URL property of request you can change the context site by using the AppContextSite endpoint
find some Samples here

A: Problem is with crossdomain communication.
Sol : Load the SpExecutor,js from 15 Folder and perform all your operation with that.

Example:

$(document).ready(function () {
    SPAppWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
    SPHostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));

    // the cross-domain library is loaded
    $.getScript(SPHostUrl + "/_Layouts/15/SP.RequestExecutor.js");
    getItems_HostWeb();
});

// read URL parameters
function getQueryStringParameter(param) {
    var params = document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == param) {
            return singleParam[1];
        }
    }
}

var SPHostUrl; // the host web URL

// read the items from a list called Test in the host web
function getItems_HostWeb() {

    var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target)" +
        "/web/lists/getbytitle('Employees')/items?" +
        "@target='" + SPHostUrl + "'";
    var globalvar;
    var executor = new SP.RequestExecutor(SPAppWebUrl);
    executor.executeAsync({
        url: url,
        method: "GET",
        headers: { "Accept": "application/json;odata=verbose" }, // return data format
        success: function (data) {
            // parse the returned data
            test(data);
            var body = JSON.parse(data.body);
            $("#dvMessage").html("Found " + body.d.results. + " items.");
        },
        error: function (data) {
            $("#dvMessage").html("Failed to read items.");
        }
    });
}


text:
Q: Microsoft.AspNetCore.App is only compatible with the netcoreapp2.2 target framework I am working on an older .net app and trying to bring up a few parts.  I upgraded netcoreapp to 2.2.8 and it looks like AspNetCore.app does not like this version.  What version should I bring it up to so I get away from this error?
Thank you for any input

Severity    Code    Description Project Path    File    Line    Suppression State
Error       This version of Microsoft.AspNetCore.App is only compatible with the netcoreapp2.2 target framework. Please target netcoreapp2.2 or choose a version of Microsoft.AspNetCore.App compatible with netcoreapp2.2.8.   UI          0


text:
Q: Variable length (Dynamic) Arrays in Java I was wondering how to initialise an integer array such that it's size and values change through out the execution of my program, any suggestions?

A: *

*It is recommend to use List to deal with small scale size.

*If you have a huge number of numbers, NEVER use List and autoboxing,
List< Integer> list
For every single int, a new Integer is auto created. You will find it getting slow when the size of the list increase. These Integers are unnecessary objects.
In this case, to use a estimated size would be better,
int[] array = new int[ESTIMATED_SIZE];

A: Arrays in Java are of fixed size. What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java.
Instead of
Integer[] ints = new Integer[x]

you use
List<Integer> ints = new ArrayList<Integer>();

Then to change the list you use ints.add(y) and ints.remove(z) amongst many other handy methods you can find in the appropriate Javadocs.
I strongly recommend studying the Collections classes available in Java as they are very powerful and give you a lot of builtin functionality that Java-newbies tend to try to rewrite themselves unnecessarily.

A: You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.
But your best option is to use IntList from jacarta commons. (here)
It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

A: How about using a List instead? For example, ArrayList<integer>

A: Arrays are fixed size once instantiated. You can use a List instead.
Autoboxing make a List usable similar to an array, you can put simply int-values into it:
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);

A: Yes: use ArrayList.
In Java, "normal" arrays are fixed-size.  You have to give them a size and can't expand them or contract them. To change the size, you have to make a new array and copy the data you want - which is inefficient and a pain for you.
Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too.  You'll want to check the Java 6 API for a full list of them.
One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints).  In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.

A: I disagree with the previous answers suggesting ArrayList, because ArrayList is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:
ArrayList list = new ArrayList(4);
list.put(3,"Test");

It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance


text:
Q: regular expression to get date format after a particular string match I have to write a regular expression to extract date from this string in python
but date might get repeat so i only want to extract the date after Invoice Value (in INR):
i.e  23/01/2023
the string is
INVOICE DETAILS Invoice Number: Invoice Date: Invoice Value (in INR): 19 23/01/2023 2416.5 ITEM DETAILS CTSH:42029900 (ii) SKU NO : (iii)

This is working
(?<=Invoice Value \(in INR\):\s\d\d\s)+\d{1,2}\/\d{1,2}\/\d{4}
But it specifies the spaces and digits after the Invoice Value (in INR):
but these spaces and digits are not fixed
And I can't use \s* and \d*  inside the quantifier

A: Surely there's something better, but this would work, using a capture group (named my_date):
Invoice Value \(in INR\):\s*\d*\s*(?<my_date>\d{1,2}\/\d{1,2}\/\d{4})
Take a look: https://regex101.com/r/GJxKb7/1


text:
Q: Pandas GroupBy and max on MultiIndex upper column level I'm trying to get the max of 2 columns for each row in a Pandas Multi-Column Index Dataframe.
I've loaded multiple stock data into Pandas and I am trying to get the max of the Close and Open price for each stock and each day.
The example I've given is a simplistic example of what I am really trying to do, so I'd appreciate it if someone can give me a solution that doesn't require to loop through each column or row and has a quick run time.
# import libaries
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
from pandas_datareader import data as pdr
import fix_yahoo_finance as yf

#declare dates
end_date = datetime.date.today()
start_date = end_date - relativedelta(days=3)

#load stock data (this code sometimes brings an error, just rerun it and it should work within a few tries)
yf.pdr_override()
df = pdr.get_data_yahoo(['AAPL','FB'], start_date, end_date)
print(df)

Output:
              Open               Close
              AAPL     FB        AAPL     FB
Date
2019-05-29    176.42   183.50    177.38   182.19
2019-05-30    177.95   183.08    178.30   183.01
2019-05-31    176.23   180.28    175.07   177.47

Desired Output:
              Open               Close              Max
              AAPL     FB        AAPL     FB        AAPL     FB
Date
2019-05-29    176.42   183.50    177.38   182.19    177.38   183.50
2019-05-30    177.95   183.08    178.30   183.01    178.30   183.08
2019-05-31    176.23   180.28    175.07   177.47    176.23   180.28

Thanks in advance!

A: Just try using this
Compare two or more columns in a dataframe using max keyword.
import pandas as pd

df = pd.DataFrame({"A": [1, 2, 3], "B": [-2, 8, 1], "C": [1, 2, 3], "D": [-2, 8, 1]})
df["E"] = df[["A", "B"]].max(axis=1)
df["F"] = df[["C", "D"]].max(axis=1)
print(df)

Output:

    A   B   C   D   E   F
0   1   -2  1   -2  1   1
1   2   8   2   8   8   8
2   3   1   3   1   3   3

A: Best solution IMO is using groupby with the level argument along the columns:
u = df.groupby(level=1, axis=1).max()

Or, more specifically,
u = df[['Open','Close']].groupby(level=1, axis=1).max()
u
              AAPL      FB
Date
2019-05-29  177.38  183.50
2019-05-30  178.30  183.08
2019-05-31  176.23  180.28

Now, fix the columns and concatenate the result.
u.columns = pd.MultiIndex.from_product([['Max'], u.columns])
pd.concat([df, u], axis=1)

              Open           Close             Max
              AAPL      FB    AAPL      FB    AAPL      FB
Date
2019-05-29  176.42  183.50  177.38  182.19  177.38  183.50
2019-05-30  177.95  183.08  178.30  183.01  178.30  183.08
2019-05-31  176.23  180.28  175.07  177.47  176.23  180.28


text:
Q: How can I attach VS Profiler 2012 to ASP.NET solution when menu item is disabled? I've followed the instructions to attempt to profile my ASP.NET solution using Visual Studio 2012 Profiler: http://msdn.microsoft.com/en-us/library/ms182384.aspx
However, when I open the right-click menu, the "Attach/Detach" menu item is disabled.
What do I need to do to enable this feature?

A: Apparently you cannot attach to VS Profiler to a process when using instrumentation as the binary has to be modified by the profiler and then started.
However, you can use the command line:
http://social.msdn.microsoft.com/forums/en-US/vstsprofiler/thread/f2f291da-8e83-4fa4-b4cb-a184965bfe16


text:
Q: How to open a log window for a game without using the executable's shortcut? I have been using a log window to find commands while playing the Unreal Engine game Batman Arkham City. Normally, I do this by adding the -log switch to a shortcut of the game.
I also use the Texmod modding program a lot when playing the game. The problem is, in order for Texmod to work correctly, you need to the launch the game through it. But then, if you do that, the log window won't appear.
What I'm looking for is a way to have a log window while playing the game even though I am launching it using Texmod.


text:
Q: Set operation on a list of strings I got a list of strings,on which I would like to do an operation which concats each item with rest of the items. The below test fails at the moment, I think the join is not the correct linq method I should be using- can you please let me know how to get this done? The pattern of the output should tell how the projection should be,if not the rule is simple:take one item and concatenate with all the other items and then move to the next item.Test below:
[Test]
        public void Should_concatenate_all_items()
        {
            var items = new List<string> {"a", "b", "c", "d"};

            var concatenatedList = items .Join(items , x => x, y => y, (x, y) => string.Concat(x, y));

            foreach (var item in concatenatedList)
            {
                //Should output:ab
                //Should output:ac
                //Should output:ad
                //Should output:bc
                //Should output:bd
                //Should output:cd
                Console.WriteLine(item);
            }
        }

Note: I'm using .NET 3.5.

A: You could use something like this:
var concatenatedList =
    from x in items.Select((str, idx) => new { str, idx })
    from y in items.Skip(x.idx + 1)
    select x.str + y;

Or in fluent syntax:
var concatenatedList =
    items.Select((str, idx) => new { str, idx })
         .SelectMany(x => items.Skip(x.idx + 1), (x, y) => x.str + y);

A: var concatenatedList = (from i in items
                     from x in items
                     where i != x
                     select string.Concat(i, x)).ToList();

For the exact output that you listed:
 var concatenatedList = (from i in items
                     from x in items
                     where i != x && items.IndexOf(i) < items.IndexOf(x)
                     select string.Concat(i, x)).ToList();

A: I think my solution may be overkill, but in real world situations it is probably more helpful. Also, I could not find a clean way to do it in Linq. Linq's Except does not seem suited for this.
You can use an IEnumerator to enumerate the values for you.
public class ConcatEnum : IEnumerator
{
    public List<String> _values;

    // Enumerators are positioned before the first element
    // until the first MoveNext() call.
    int position1 = 0;
    int position2 = 0;

    public ConcatEnum(List<String> list)
    {
        _values = list;
    }

    public bool MoveNext()
    {
        position2 = Math.Max(position2 + 1, position1 + 1);
        if (position2 > _values.Count - 1){
            position1++;
            position2 = position1 + 1;
        }

        return position1 < _values.Count - 1;
    }

    public void Reset()
    {
        position1 = 0;
        position2 = 0;
    }

    object IEnumerator.Current
    {
        get
        {
            return Current;
        }
    }

    public String Current
    {
        get
        {
            try
            {
                return _values[position1] + _values[position2];
            }
            catch (IndexOutOfRangeException)
            {
                throw new InvalidOperationException();
            }
        }
    }

    public IEnumerator GetEnumerator()
    {
        this.Reset();
        while (this.MoveNext())
        {
            yield return Current;
        }
    }
}

Call it like this:
var items = new List<string> { "a", "b", "c", "d" };
foreach (var i in new ConcatEnum(items))
{
    //use values here
}


text:
Q: Java Classloader complexity In trying to learn about Java class loaders from Wikipedia, I think I can see why they have the three major class loaders:
1) Bootstrap class loader
2) Extensions class loader
3) System class loader
They go on to say you can define your own classloader. I'm not sure I see the value in defining your own, but the following quote from Wikipedia really makes me wonder:

The most complex JAR hell problems arise in circumstances that take
  advantage of the full complexity of the classloading system. A Java
  program is not required to use only a single "flat" classloader, but
  instead may be composed of several (potentially very many) nested,
  cooperating classloaders. Classes loaded by different classloaders may
  interact in complex ways not fully comprehended by a developer,
  leading to errors or bugs that are difficult to analyze, explain, and
  resolve.

If it's so complex, why bother with it? Shouldn't the three already-defined classloaders be enough?
(And yes, for those curious, I did run into a ClassCastException that I didn't think should have happened, much like the graphic labelled Figure 2. Class identity crisis. I'm trying to understand the background is all.)

A: Certain use cases require custom classloaders.
A few examples:

*

*Dynamically adding new folders/jars to be loadable. (Without restarting the whole application).

*Dynamically removing folder/jars from being loadable.

*Runtime bytecode generation with javassist.

*Multiple (actually used at the same time) versions of the same classes in the same application/jvm


text:
Q: On the kuratowski definition of ordered pairs. Kuratowski gave the following definition for ordered pair,
$$(a,b)=\{\{a\},\{a,b\}\}$$
Coming to it's geometric explanation, I think of it as a point in Cartesian plane.
Now similarly, what if we take only one argument inside my ordered pair?
My argument is that,
$$(a)=a$$
Because intuitively, $(a)$ is a point on 1-dimensional plane i.e number line.
And at the same time can we use kuratowski definition to prove it(if my argument is true)?

A: Define an "assignment" (i.e. a class function) $F$ by
$$F(x,y)=\{\{x\},\{x,y\}\}$$
You can think of $F(x,y)$ as a set-theoretical encoding from the inputs $x$ and $y$. The encoding has the desired meaning of an "ordered pair" since there are two projection functions $\pi_1$ and $\pi_2$ that satisfy the following property: $\pi_1(F(x,y))=x$ and $\pi_2(F(x,y))=y$. You can think of $\pi_1$ and $\pi_2$ as set-theoretical decoders that allow us to identify what the first coordinate is (by applying $\pi_1$) or to identify what the second coordinate is (by applying $\pi_2$). I forgo defining $\pi_1$ and $\pi_2$ explicitly here.
Now you want to introduce another "assignment" $G$ defined by
$$G(x)=\boxed{???}$$
I put three question marks here because you didn't actually define it, but the important thing I gathered was that it takes one input. The map $F$ requires two inputs therefore $F\ne G$. Then you want to argue that $G(x)=x$ and you believe Kuratowski's $F$ map is somehow relevant. I hope I made it clear why your question is perceived as nonsensical.
I'll play along and assume you want to propose $G(x)=x$ by definition. You can think of $G(x)$ as the trivial encoding where nothing happens. Then the projection function $\pi_1$ can also do nothing, i.e., $\pi_1(y)=y$. Then indeed $\pi_1(G(x))=x$ since both $ G $ and $\pi_1$ do nothing to the input $x$.


text:
Q: Attaching conditional AND condition in SQL Server? I want to have an AND condition attached to my WHERE clause based on some condition. Below is the situation I am facing
DECLARE
    @param1 INT, @param2 INT

SET @param1 = 1
SET @param2 = 1

SELECT *
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.a = t2.b
INNER JOIN TABLE Table3 t3 ON t3.c = t2.d
WHERE t1.id = 1
  AND t2.id = 2

Here is where i want the condition to come in--
Case when `@param1 = 1` and `@param2 = 1` THEN `AND t3.id = 4`

But I guess and does not work like this ? :/ Any workaround for this?

A: Just add this to your where clause
and isnull(t3.id,'') = case when @param1 = 1 and @param2 = 1 then 4 else isnull(t3.id,'') end

A: I would write this as:
where t1.id = 1 and t2.id = 2 and
      ((@param1 = 1 and @param2 = 1 and t3.id = 4) or
       not (@param1 = 1 and @param2 = 1)
      )

This does assume that the parameters are never NULL.

A: You can add the following as an AND condition to check if t3.id = 4 when @param1 and @param2 both equal 1, or no additional condition if they don't:
SELECT *
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.a = t2.b
INNER JOIN Table3 t3 ON t3.c = t2.d
WHERE
    t1.id = 1
    AND t2.id = 2
And
(
    (
        @param1 = 1
    And @param2 = 1
    And t3.id = 4
    )
    Or
    (
        @param1 <> 1
    Or  @param2 <> 1
    )
)


text:
Q: match values according to index in bash I was wondering if there was an elegant way of doing the following in bash:
I need to check a list for a certain value, lets call it "1". For each entry which I find this value, I need to accumulate a matching string (with same index) in another list, and eventually print it out.
For example:
Lets assume the list of values is "1 0 1 1 "
and the list of strings is "What a wonderful day"
so the output string would be "What wonderful day"
Thanks

A: Here my proposed solution:
#!/bin/sh
myMatch=1 #This is the value you're looking for
myString="What a wonderful day";
myList=( $myString ) #String to Array conversion
count=0;
for i in $@; do #Iterate over the input parameters
    if [ $i -eq $myMatch ]; then
        echo -n "${myList[$count]} " #use -n to avoid newline and append space as a separator
        count=$(($count+1))
    fi
done

So calling the script giving the list of values:
$ . myScript.sh 1 0 1 1

you have the wanted result.


text:
Q: google drive hosting changes in URL I've developed a web app that uses google drive as hosting platform as explained here:
https://support.google.com/drive/answer/2881970?hl=en
The application has been working OK when users accessed:
https://googledrive.com/host/0B0YWdwxH6K5XdVpaNjhWUl9vZkE/?scriptid=AKfycbx66sZMaqLK8byhV7wY_DoQ8ouqF1acWRcc0JIHyDu5CVWZupAK&id=people
But yesterday it started redirecting that address to:
b216bdb4cf56e8d9d85cf1123921ca125a010325.googledrive.com/host/0B0YWdwxH6K5XdVpaNjhWUl9vZkE/
any idea why? is this a permanent change? does the subdomain key follow any logic?
Browser: occurs on chrome & IE
Operating System: windows8
Drive on the Web / Drive for desktop: when accessing googledrive.com/host

A: I found the right thread at google.com to answer this. Here it is: https://productforums.google.com/forum/#!category-topic/drive/mTyJXruRhBg
In short, the redirect and prefix is here to stay. It's for some security thing. All files within the same googledrive folder will be prefixed with the same guid-looking string. That is, provided we use this googledrive url form: googledrive.com/host/{folderID}/FriendlyFilename. Then, any support files you want to access or link from that folder, just access them as FriendlyFilename with relative url form.
My problem was, I was using the obscure form googledrive.com/host/{userID+fileID}. (no FolderID or FriendlyFilename). That now gets a different domain prefix for every file within the same folder.
Here's a different variation of that test file I showed above (which was getting Security exception for webworker). It works now by using the {FolderID}/FriendlyFilename form. Tada. https://googledrive.com/host/0B8BLd2qPPV7XME1rNU9iWnYtbTg/ded-worker-F12throw.html


text:
Q: My while loop runs infinite times when I think its not supposed to I was trying write a code that gives index of a minimum value of list one after other
For example:
if list=[2,4,1,2,5]
         0 1 2 3 4

output:

[2,0,3,1,4]--> where each element in this corresponds to index of list
variable

import math
list=[2,4,1,2,5]
a=[]
i=0
while(i <= (len(list)-1)):
    if(list[i]==min(list)):
        a.append(i)
        list[i]=math.inf
        i=-1
    i+=1

print(a)

A: The problem is that, when list becomes all inf, list[i]==min(list) is true because both list[i] and min(list) are inf.  Then i resets to zero and you're in an infinite loop.
print(list, i, list[i], min(list), a)

Outputs:
[inf, inf, inf, inf, inf] 0 inf inf [2, 0, 3, 1, 4, 0, 0, 0, 0]

You can see that list a is being appended with zeroes.
"List" is actually a keyword in Python.  Yes, it lets you use it, but that's bad form and you should use something like "lyst" or just "x" or something like that.

A: Don't use 'list' to define your list. Use something else like 'my_list'.
you can use numpy library to generate an index of a minimum value of a list.
import numpy as np

my_list = [2,4,1,2,5]
minimum_value_index = [np.argsort(my_list)[x] for x in range(len(my_list))]

print(minimum_value_index)

This will output as following:
[2, 0, 3, 1, 4]

Hope this helps.


text:
Q: iOS App -On firebase console I am not able to log the events from real users whereas the events are getting properly logged in debug view I have implemented firebase in my already live iOS application with multiple environments (can say - PROD and PrePROD) both are having individual project settings in firebase.
For PrePROD the data is showing up correctly however for PROD enviroment I am able to see events in debug view using simulator but we are unable to track data for live Users.
I understand that event sometime takes time to get logged but I have waited enough to see the progress.
Firebase runscript that I have added in the project which seems to be working fine as I am able to track simulator data on debug views

# Name of the resource we're selectively copying
GOOGLESERVICE_INFO_PLIST=GoogleService-Info.plist

# Get references to dev and prod versions of the GoogleService-Info.plist
# NOTE: These should only live on the file system and should NOT be part of the target (since we'll be adding them to the target manually)
GOOGLESERVICE_INFO_DEV=${PROJECT_DIR}/${TARGET_NAME}/Config/FirebaseConfigFiles/Dev/${GOOGLESERVICE_INFO_PLIST}
GOOGLESERVICE_INFO_PROD=${PROJECT_DIR}/${TARGET_NAME}/Config/FirebaseConfigFiles/Prod/${GOOGLESERVICE_INFO_PLIST}

# Make sure the dev version of GoogleService-Info.plist exists
echo "Looking for ${GOOGLESERVICE_INFO_PLIST} in ${GOOGLESERVICE_INFO_DEV}"
if [ ! -f $GOOGLESERVICE_INFO_DEV ]
then
echo "No Development GoogleService-Info.plist found. Please ensure it's in the proper directory."
exit 1
fi

# Make sure the prod version of GoogleService-Info.plist exists
echo "Looking for ${GOOGLESERVICE_INFO_PLIST} in ${GOOGLESERVICE_INFO_PROD}"
if [ ! -f $GOOGLESERVICE_INFO_PROD ]
then
echo "No Production GoogleService-Info.plist found. Please ensure it's in the proper directory."
exit 1
fi

# Get a reference to the destination location for the GoogleService-Info.plist
PLIST_DESTINATION=${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.app
echo "Will copy ${GOOGLESERVICE_INFO_PLIST} to final destination: ${PLIST_DESTINATION}"
echo ${CONFIGURATION}
# Copy over the prod GoogleService-Info.plist for Release builds
if [ "${CONFIGURATION}" == "Appstore" ] || [ "${CONFIGURATION}" == "Release(PROD)" ] || [ "${CONFIGURATION}" == "Debug(PROD)" ]
then
echo "Using ${GOOGLESERVICE_INFO_PROD}"
cp "${GOOGLESERVICE_INFO_PROD}" "${PLIST_DESTINATION}"
else
echo "Using ${GOOGLESERVICE_INFO_DEV}"
cp "${GOOGLESERVICE_INFO_DEV}" "${PLIST_DESTINATION}"
fi

Run script Logs:
Runscript logs
Scheme Details:
Scheme details
Analytics tracking Method:

func track(_ eventName: String, properties: [String: Any]? = nil) {
        if let localProps = properties {
            Analytics.logEvent(eventName, parameters: localProps)
        } else {
            Analytics.logEvent(eventName, parameters: nil)
        }

Please note I am still able to see the simulator events on debug view for PROD environment but there is no trace of events happening on real devices for real users. And for the same project I am able to see data for android aswell
I need help from you guys to tell me if is there anything I am missing in setting up the project or while archiving the build for the appstore release.
Let me know If you require more details regarding the implementation.
Looking forward for some solutions. I am stuck in this since so long


text:
Q: Include file.php + id. Is this possible with php? I've built my site with php include and the index is as follows:
Menu.php (menu system)
main.php (Index site)
footer.php (footer obv.)
Anyway, when main.php (index) opens, I've added a news script that uses $_GET to fetch the news-data from our mysql database. This generates an ID for each news, and it shows only a few characters of the full news.
So, I've added a link in each news that says "Read more" to expand the news, it looks like this:
<a href="news.php?id=<?=$row['id']?>">Read More

So, is there a way for me to include this site (replace news.php?id=x with main.php)?
It gives me syntax error when I'm trying to use <?php include in the link since it's already using <?=$row['id']?>.
The only help I got so far are people telling me to change the menu system to Javascript (Ajax, Jquery) but I'm not too familiar with this. Is there something I can do more simple than changing the menu to javascript?
Thanks for your help and understanding,
Have a great day!

A: Change it to main.php, get the id value on main.php, pass it to your news function.

A: Yeah, include basically adds the code of another file to the execution of the code you are using.  So if you already have the variable in you index file can just use it in your menu file.
If the menu file has to be loaded on it own sometimes you can do a conditional for the existence of the GET, then the existence of the variable in your index file, and finally if none of them exit, set a default value.

A: leave your link as is, it's fine.
do not include main into news.
include only menu and footer into news.


text:
Q: User defaults Only Working On Restart I am trying to implement a light and dark mode in my application. In the settingsViewController I have these lines of code:
//Sets user default for colour
let lightMode = UserDefaults.standard.bool(forKey: "lightMode")

//UISegment control for user to pick colour
@IBOutlet var colourSegment: UISegmentedControl!

//Updates lightMode based on user selection
@IBAction func didChangeColours(_ sender: Any) {

    if colourSegment.selectedSegmentIndex == 0 {
        UserDefaults.standard.set(true, forKey: "lightMode")
    } else if colourSegment.selectedSegmentIndex == 1 {
        UserDefaults.standard.set(false, forKey: "lightMode")
    }

}

In my entryViewController, in my viewDidLoad, I have:
let lightMode = UserDefaults.standard.bool(forKey: "lightMode")

if lightMode == false {
    Colours.darkMode()
}

customisations()

The issue that I'm running into is that for some reason, my application is only changing it's colour scheme after I restart it. That is, if the user selects the darkIndex of the colourSegment, the application only updates the colour after I restart. I am wondering what is the solution for this.

A: The problem is in the line -
//Sets user default for colour
let lightMode = UserDefaults.standard.bool(forKey: "lightMode")

this line is not for setting the Userdefaults but instead it gets the UserDefaults. Since you use it before setting the default Value, it doesn't reflect the right segmented choice. So your setting part is correct and you should fetch the value only after you have set it.
Also in your entryViewController, instead of using it from settingsVC, do below -
//get from UserDefaults
let lightMode = UserDefaults.standard.bool(forKey: "lightMode")

//Compare the previous fetched value
if lightMode == false {
    Colours.darkMode()
}

//This function sets the colour for the elements
colours()

A: Because you are assigning the lightMode value ONLY 1 time during init, you don't reflect the changes to the variable, so it will always be that value
To always get the lastest value, use this:
let lightMode: Bool {
   get {
       return UserDefaults.standard.bool(forKey: "lightMode")
   }
}

Also, you should call the color change immediatelly after change the value

A: I am assuming that you are returning to your entryViewController from your settingsViewController; Since you are returning to an existing view controller instance, the code in viewDidLoad is not executed when you return.
Move the code to viewWillAppear; This way your code will execute prior to the view controller appearing even when you return to the existing instance:
func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let lightMode = UserDefaults.standard.bool(forKey: "lightMode")

    if lightMode == false {
        Colours.darkMode()
    }
}


text:
Q: org.apache.commons.mail.EmailException: Missing final '@domain'( by: javax.mail.internet.AddressException: Missing final '@domain' in string ``1'') I'm trying to use javamail in my web application.
MailService:
@Service
public class MailServiceImpl implements MailService {
    Email email = new SimpleEmail();

    private MailServiceImpl() {
        email.setCharset("utf-8");
        email.setHostName("smtp.googlemail.com");
        email.setSmtpPort(465);
        email.setAuthenticator(new DefaultAuthenticator("1", "1"));
        email.setSSL(true);
    }

    @Override
    public void sendMail(String to, String subject, String body) {
        try {
            email.setFrom("1");
            email.setSubject(subject);
            email.setMsg(body);
            email.addTo(to);
            email.send();
            email.getToAddresses().clear();
        } catch (EmailException e) {
            e.printStackTrace();
        }
    }
}

Logs:
org.apache.commons.mail.EmailException: Missing final '@domain'
    at org.apache.commons.mail.Email.createInternetAddress(Email.java:605)
    at org.apache.commons.mail.Email.setFrom(Email.java:668)
    at org.apache.commons.mail.Email.setFrom(Email.java:651)
    at org.apache.commons.mail.Email.setFrom(Email.java:631)
    at by.netcracker.artemyev.service.impl.MailServiceImpl.sendMail(MailServiceImpl.java:28)
    at by.netcracker.artemyev.service.impl.UserServiceImpl.addUser(UserServiceImpl.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy39.addUser(Unknown Source)
    at by.netcracker.artemyev.web.UserController.registrationUser(UserController.java:48)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:475)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1354)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: javax.mail.internet.AddressException: Missing final '@domain' in string ``1''
    at javax.mail.internet.InternetAddress.checkAddress(InternetAddress.java:915)
    at javax.mail.internet.InternetAddress.validate(InternetAddress.java:856)
    at org.apache.commons.mail.Email.createInternetAddress(Email.java:601)
    ... 58 more

I eneter: artyomartemyev962015@gmail.com and then give: Missing final '@domain'.
What does it mean? Every recipient's address is valid and sender address is verified and valid.
Question: How fix?

A: The from address does not have a domain:
email.setFrom("1");

Use something that does have a domain as the from address:
email.setFrom("1@example.com");

A: It's necessary to check that there is no kind of space before the "@".


text:
Q: How i can get only the difference between two array objects keeping one property? I have this two array of objects:
const groupScreens = [
  {
      "id": "6b7c1891-e98f-4ca5-87db-7d4578268b8f",
      "name": "Cad 1",
      "screen_id": "7b9bb725-2fa8-4416-a664-37395d28da95",
      "group_id": "319588ba-8c5d-474b-aaf2-2ea8fbfed898",
      "allow_read": false,
      "allow_create": true,
      "allow_update": false,
      "allow_delete": false,
      "created_at": "2020-04-07 08:32:58",
      "updated_at": "2020-04-07 08:32:58"
  },
  {
      "id": "7ae7c727-6dd3-43ab-be91-816e34da42ce",
      "name": "Cad 2",
      "screen_id": "b1793127-09f1-4c70-982d-c2cea57709ee",
      "group_id": "319588ba-8c5d-474b-aaf2-2ea8fbfed898",
      "allow_read": true,
      "allow_create": true,
      "allow_update": true,
      "allow_delete": true,
      "created_at": "2020-04-07 08:32:58",
      "updated_at": "2020-04-07 08:32:58"
  },
  {
      "id": "1de0a773-9df8-4e7c-98c0-e12d2f79a3d3",
      "name": "Cad 3",
      "screen_id": "b829677f-c597-48e5-b50d-736b0a1bda00",
      "group_id": "319588ba-8c5d-474b-aaf2-2ea8fbfed898",
      "allow_read": true,
      "allow_create": true,
      "allow_update": false,
      "allow_delete": true,
      "created_at": "2020-04-07 08:32:58",
      "updated_at": "2020-04-07 08:32:58"
  }
]

const changedGroupScreen = [
  {
      "id": "6b7c1891-e98f-4ca5-87db-7d4578268b8f",
      "name": "Cad 1",
      "screen_id": "7b9bb725-2fa8-4416-a664-37395d28da95",
      "group_id": "319588ba-8c5d-474b-aaf2-2ea8fbfed898",
      "allow_read": false,
      "allow_create": true,
      "allow_update": true,
      "allow_delete": true,
      "created_at": "2020-04-07 08:32:58",
      "updated_at": "2020-04-07 08:32:58"
  },
  {
      "id": "7ae7c727-6dd3-43ab-be91-816e34da42ce",
      "name": "Cad 2",
      "screen_id": "b1793127-09f1-4c70-982d-c2cea57709ee",
      "group_id": "319588ba-8c5d-474b-aaf2-2ea8fbfed898",
      "allow_read": true,
      "allow_create": true,
      "allow_update": true,
      "allow_delete": true,
      "created_at": "2020-04-07 08:32:58",
      "updated_at": "2020-04-07 08:32:58"
  },
  {
      "id": "1de0a773-9df8-4e7c-98c0-e12d2f79a3d3",
      "name": "Cad 3",
      "screen_id": "b829677f-c597-48e5-b50d-736b0a1bda00",
      "group_id": "319588ba-8c5d-474b-aaf2-2ea8fbfed898",
      "allow_read": true,
      "allow_create": true,
      "allow_update": false,
      "allow_delete": false,
      "created_at": "2020-04-07 08:32:58",
      "updated_at": "2020-04-07 08:32:58"
  }
]

I need to compare this two arrays by the property screen_id and return the differences that is in changedGroupScreen keeping the property screen_id.
I need this result:
const result = [{
    "screen_id": "7b9bb725-2fa8-4416-a664-37395d28da95",
    "allow_update": true,
    "allow_delete": true
}, {
    "screen_id": "b829677f-c597-48e5-b50d-736b0a1bda00",
    "allow_delete": false
}]

I'm receiving: Cannot set property screen_id of undefined:
let result = [{}]
let countResult = 0
let foundedDifference = false
for (let i_group_screens = 0 ; i_group_screens < groupScreens.length; i_group_screens++) {
  foundedDifference = false
  for (let i_changed = 0; i_changed < changedGroupScreen.length; i_changed++) {
    if (groupScreens[i_group_screens].screen_id === changedGroupScreen[i_changed].screen_id) {
      if(groupScreens[i_group_screens].allow_read !== changedGroupScreen[i_changed].allow_read) {
        result[countResult].screen_id = groupScreens[i_group_screens].screen_id
        result[countResult].allow_read = changedGroupScreen[i_changed].allow_read
        foundedDifference = true
      }
      if(groupScreens[i_group_screens].allow_create !== changedGroupScreen[i_changed].allow_create) {
        result[countResult].screen_id = groupScreens[i_group_screens].screen_id
        result[countResult].allow_create = changedGroupScreen[i_changed].allow_create
        foundedDifference = true
      }
      if(groupScreens[i_group_screens].allow_update !== changedGroupScreen[i_changed].allow_update) {
        console.log(countResult)
        result[countResult].screen_id = groupScreens[i_group_screens].screen_id
        result[countResult].allow_update = changedGroupScreen[i_changed].allow_update
        foundedDifference = true
      }
      if(groupScreens[i_group_screens].allow_delete !== changedGroupScreen[i_changed].allow_delete) {
        result[countResult].screen_id = groupScreens[i_group_screens].screen_id
        result[countResult].allow_delete = changedGroupScreen[i_changed].allow_delete
        foundedDifference = true
      }
      if(foundedDifference === true) {
        countResult++
      }
    }
  }
}

A: If someone needs something like this, i make this work this way:
let result = []
let countResult = 0
let foundedDifference = false

for (let i_group_screens = 0 ; i_group_screens < groupScreens.length; i_group_screens++) {
  foundedDifference = false
  for (let i_changed = 0; i_changed < changedGroupScreen.length; i_changed++) {
    if (groupScreens[i_group_screens].screen_id === changedGroupScreen[i_changed].screen_id) {
      if(groupScreens[i_group_screens].allow_read !== changedGroupScreen[i_changed].allow_read) {
        let obj = {screen_id: groupScreens[i_group_screens.screen_id], allow_read: changedGroupScreen[i_changed].allow_read}
        result.push(obj)
        foundedDifference = true
      }
      if(groupScreens[i_group_screens].allow_create !== changedGroupScreen[i_changed].allow_create) {
        if (foundedDifference === true) {
          result[countResult].allow_create = changedGroupScreen[i_changed].allow_create
        } else {
          let obj = {screen_id: groupScreens[i_group_screens].screen_id, allow_create: changedGroupScreen[i_changed].allow_create}
          result.push(obj)
        }
      }
      if(groupScreens[i_group_screens].allow_update !== changedGroupScreen[i_changed].allow_update) {
        if (foundedDifference === true) {
          result[countResult].allow_update = changedGroupScreen[i_changed].allow_update
        } else {
          let obj = {screen_id: groupScreens[i_group_screens].screen_id, allow_update: changedGroupScreen[i_changed].allow_update}
          result.push(obj)
        }
        foundedDifference = true
      }
      if(groupScreens[i_group_screens].allow_delete !== changedGroupScreen[i_changed].allow_delete) {
        if(foundedDifference === true) {
          result[countResult].allow_delete = changedGroupScreen[i_changed].allow_delete
        }else {
          let obj = {screen_id: groupScreens[i_group_screens].screen_id, allow_delete: changedGroupScreen[i_changed].allow_delete}
          result.push(obj)
        }
        foundedDifference = true
      }
      if(foundedDifference === true) {
        countResult++
      }
    }
  }
}

Probably not the best solution (so much code) but is working like i expect.
(If you have some trick to do this better, feel free to comment)


text:
Q: Scripting .NET objects I have a simple .NET application which runs as Windows Service.
Say it has one Class
MyClass
{
  Run(Destination d)
  Walk(Destination d)
  Wash(Dishes d)
}

I want to create a console application where I would type simple human readable commands
like
run left
walk right

Pretty much like you do in windows console. I wonder what is the best way to implement this mapping. A straight methods is of course create your own string parser with lots of switch statements but I think if there is better and faster method.

A: This might be too much for your needs, but I think a robust, flexible way to do it would be creating a couple of meta-data attributes to decorate the classes you might want to call from your shell, something like:
[ScriptableClass]
public class MyClass
{
     [ScriptableMethod(typeof (Destination),typeof(int))]
     public void Run (Destination f, int distance) {}
}

Then, during your shell's startup, you load your assemblies via reflection and look for types marked with the ScriptableClass attribute. For each of them, you inspect their public methods looking for those marked with the ScriptableMethod attribute, and you can build a dictionary of classes and their scriptable methods (along with info about parameters). For the previous example, you would have a 'MyClass.Run' command you can could from the shell. When received, your scripting engine would create / lookup an instance of the class and execute the method.
The advantage of this method is that you wouldn't have to modify your scripting engine every time you add new classes or modify methods.

A: You have two options here:

*

*Use reflection to find the class method with the approrpiate name and invoking it.

*Use the command pattern, where each command object would have a name and a Run() method. You can easily find the desired command by name, then run it.
UPDATE: Aggreed, there are more than two options (see Guffa's answer). But these two are the ones that make the code clearer IMHO.

A: Not really. There are other methods, but if they are better is mostly a matter of taste, and for identifying a string you can't do it much faster than a switch.
If all method have the same parameters, you could set up a dictionary of strings and delegates.
Example:
var methods = new Dictionary<string, Action<int>>();
methods.Add("run", n => MyClass.Run(n));
methods.Add("walk", n => MyClass.Walk(n));
methods.Add("wash", n => MyClass.Wash(n));

string cmd = "run";
int param = 42;
if (methods.ContainsKey(cmd)) {
   methods[cmd](param);
} else {
  Console.WriteLine('Say what, human?');
}

A: Perhaps a PowerShell CommandLet would be an option, although that would constrain you or your users to PowerShell (which is a superior shell IMO).


text:
Q: Dynamic constant name in PHP I am trying to create a constant name dynamically and then get at the value.
define( CONSTANT_1 , "Some value" ) ;

// try to use it dynamically ...
$constant_number = 1 ;
$constant_name = ("CONSTANT_" . $constant_number) ;

// try to assign the constant value to a variable...
$constant_value = $constant_name;

But I find that $constant value still contains the NAME of the constant, and not the VALUE.
I tried the second level of indirection as well $$constant_name But that would make it a variable not a constant.
Can somebody throw some light on this?

A: To use dynamic constant names in your class you can use reflection feature (since php5):
$thisClass = new ReflectionClass(__CLASS__);
$thisClass->getConstant($constName);

For example:
if you want to filter only specific (SORT_*) constants in the class
class MyClass
{
    const SORT_RELEVANCE = 1;
    const SORT_STARTDATE = 2;

    const DISTANCE_DEFAULT = 20;

    public static function getAvailableSortDirections()
    {
        $thisClass = new ReflectionClass(__CLASS__);
        $classConstants = array_keys($thisClass->getConstants());

        $sortDirections = [];
        foreach ($classConstants as $constName) {
            if (0 === strpos($constName, 'SORT_')) {
                $sortDirections[] =  $thisClass->getConstant($constName);
            }
        }

        return $sortDirections;
    }
}

var_dump(MyClass::getAvailableSortDirections());

result:
array (size=2)
  0 => int 1
  1 => int 2

A: And to demonstrate that this works with class constants too:
class Joshua {
    const SAY_HELLO = "Hello, World";
}

$command = "HELLO";
echo constant("Joshua::SAY_$command");

A: http://dk.php.net/manual/en/function.constant.php
echo constant($constant_name);


text:
Q: Override HTML id using css I have the following declaration:
<header id="page-header" class="head">

How do I override the id 'page-header' to any other name using css?

A: Not css but easily done with JS
You simply make a reference to the element let header = document.getElementById("page-header");, remove the id attribute header.removeAttribute("id"); and add a new id attribute header.setAttribute("id", "newId");
Working snippet:

let header = document.getElementById("page-header");
console.log(header.id);

header.removeAttribute("id");
console.log(header.id);

header.setAttribute("id", "newId");

console.log(header.id);
<header id="page-header" class="head">