text:
Q: Group variables based on lengths of specific arrays I have a long list of variables in a dataset which contains multiple time channels with different sampling rates, such as time_1, time_2, TIME, Time, etc. There are also multiple other variables that are dependent on either of these times.
I'd like to list all possible channels that contain 'time' (case-insensitive partial string search within Workspace) and search & match which variable belongs to each item of this time list, based on the size of the variables and then group them in a structure with the values of the variables for later analysis.
For example:
  Name                     Size              Bytes  Class

  ENGSPD_1            181289x1             1450312  double
  Eng_Spd              12500x1              100000  double
  Speed                41273x1              330184  double
  TIME                 41273x1              330184  double
  Time                 12500x1              100000  double
  engine_speed_2        1406x1               11248  double
  time_1              181289x1             1450312  double
  time_2                1406x1               11248  double

In this case, I have 4 time channels with different names & sizes and 4 speed channels which belong to each of these time channels.
whos function is case-sensitive and it will only return the name of the variable, rather than the values of the variable.

A: As a preamble I'm going to echo my comment from above and earlier comments from folks here and on your other similar questions:
Please stop trying to manipulate your data this way.
It may have made sense at the beginning but, given the questions you've asked on SO to date, this isn't the first time you've encountered issues trying to pull everything together and if you continue this way it's not going to be the last. This approach is highly error prone, unreliable, and unpredictable. Every step of the process requires you to make assumptions about your data that cannot be guaranteed (size of data matching, variables being present and named predictably, etc.). Rather than trying to come up with creative ways to hack together the data, start over and output your data predictably from the beginning. It may take some time but I guarantee it's going to save time in the future and it will make sense to whoever looks at this in 6 months trying to figure out what is going on.
For example, there is absolutely no significant effort needed to output your variables as:
outputstructure.EngineID.time = sometimeseries;
outputstructure.EngineID.speed = somedata;

Where EngineID can be any valid variable name. This is simple and it links your data together permanently and robustly.

That being said, the following will bring a marginal amount of sanity to your data set:
% Build up a totally amorphous data set
ENGSPD_1       = rand(10, 1);
Eng_Spd        = rand(20, 1);
Speed          = rand(30, 1);
TIME           = rand(30, 1);
Time           = rand(20, 1);
engine_speed_2 = rand(5, 1);
time_1         = rand(10, 1);
time_2         = rand(5, 1);

% Identify time and speed variable using regular expressions
% Assumes time variables contain 'time' (case insensitive)
% Assumes speed variables contain 'spd', 'sped', or 'speed' (case insensitive)
timevars = whos('-regexp', '[T|t][I|i][M|m][E|e]');
speedvars = whos('-regexp', '[S|s][P|p][E|e]{0,2}[D|d]');

% Pair timeseries and data arrays together. Data is only coupled if
% the number of rows in the timeseries is exactly the same as the
% number of rows in the data array.
timesizes  = vertcat(speedvars(:).size);  % Concatenate timeseries sizes
speedsizes = vertcat(timevars(:).size);  % Concatenate speed array sizes

% Find intersection and their locations in the structures returned by whos
% By using intersect we only get the data that is matched
[sizes, timeidx, speedidx] = intersect(timesizes(:,1), speedsizes(:,1));

% Preallocate structure
ndata = length(sizes);
groupeddata(ndata).time = [];
groupeddata(ndata).speed = [];

% Unavoidable (without saving/loading data) eval loop :|
for ii = 1:ndata
    groupeddata(ii).time  = eval('timevars(timeidx(ii)).name');
    groupeddata(ii).speed = eval('speedvars(speedidx(ii)).name');
end

A non-eval method, by request:
ENGSPD_1       = rand(10, 1);
Eng_Spd        = rand(20, 1);
Speed          = rand(30, 1);
TIME           = rand(30, 1);
Time           = rand(20, 1);
engine_speed_2 = rand(5, 1);
time_1         = rand(10, 1);
time_2         = rand(5, 1);

save('tmp.mat')
oldworkspace = load('tmp.mat');
varnames = fieldnames(oldworkspace);

timevars = regexpi(varnames, '.*time.*', 'match', 'once');
timevars(cellfun('isempty', timevars)) = [];
speedvars = regexpi(varnames, '.*spe{0,2}d.*', 'match', 'once');
speedvars(cellfun('isempty', speedvars)) = [];

timesizes = zeros(length(timevars), 2);
for ii = 1:length(timevars)
    timesizes(ii, :) = size(oldworkspace.(timevars{ii}));
end
speedsizes = zeros(length(speedvars), 2);
for ii = 1:length(speedvars)
    speedsizes(ii, :) = size(oldworkspace.(speedvars{ii}));
end

[sizes, timeidx, speedidx] = intersect(timesizes(:,1), speedsizes(:,1));

ndata = length(sizes);
groupeddata(ndata).time = [];
groupeddata(ndata).speed = [];

for ii = 1:ndata
    groupeddata(ii).time  = oldworkspace.(timevars{timeidx(ii)});
    groupeddata(ii).speed = oldworkspace.(speedvars{speedidx(ii)});
end

See this gist for timing.


text:
Q: Choosing the parameter in a function to bring the function as close to 1 as possible when x is approximately equal to zero. The problem states the following:
How should the parameter λ be chosen so that f(x) = e^(-λx)/(1+2sin(x)) remains as close to 1 as possible, when x ≈ 0?
I understand that the solution first simplifies the function into a simpler approximation. However, the last line in the solution states the following: So F is const. to 1st order if λ = -2. I dont quite understand what is meant with this statement.
Problem with Solution

A: It means that $\lambda$ is chosen so that $(1 - \lambda x) (1 - 2x)$ will equal $1 + (0 \times x) + (\text{something}~ \times x^2).$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Java timer - Anyway to change it to auto start on opening the page rather that clicking start Instead of clicking start I need it to auto start on opening the page. Also would it be possible to allow to give the user the option to email the time back to them self as it will be used to time how long they took to answer questions

        <input id="start" name="controls" type="radio" />
        <input id="stop" name="controls" type="radio" />
        <input id="reset" name="controls" type="radio" />

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

:

0 1 2 3 4 5 6

0 1 2 3 4 5 6 7 8 9

:

0 1 2 3 4 5 6

0 1 2 3 4 5 6 7 8 9

:

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

            Start

A: You can start timer with JS code (with jQuery for simplify):
// detect page load
$(window).load(function () {

    // get start btn and toggle click on it -> start function must be called
    $('#start').click();

});

To send time to  users by email you must save this time in variable, and maybe send it with AJXA to backend (PHP), and there create this email and send it (if your server can do it :) )
P.s. Start something on page without customer - is bad idea, because when customer loads the page - you can't get 100% garantie, that he is on it.
Better to start timer with click - only user can make it, and for tests (like in your case) - clicking on buttons will give you better and more accurate results, if you need some for analytics.


text:
Q: How can I activate :focus on input[type="checkbox"]? SO I'm trying display: block menu on focus when I use keyboard to navigate trough the nav buttons (TAB)
code for on hover : display: block; that is working perfectly fine
 //desktop view - view sub menu on hover instead of click

    #menu li:hover > input[type="checkbox"] + .sub-menu {
      @include respond(tab-land) {
        display: block;
      }
    }

Trying to have menu display block on focus (keyboard tab navigation)
None of the below solutions work
#menu li:focus> input[type="checkbox"] + .sub-menu {
  @include respond(tab-land) {
    display: block;
  }
}
#menu li:focus::after > input[type="checkbox"] + .sub-menu {
  @include respond(tab-land) {
    display: block;
  }
}


text:
Q: Silly question about basis vectors as partial derivatives It's good to construct a notion of basis of a particular coordinate system as (for instance, in polar coordinate system):
$$\displaystyle \frac{\partial\vec{R}}{\partial r}= \frac{\vec{R_{h}}(r+h,\theta) - \vec{R}(r,\theta)}{h}:= \vec{e}_{r}$$
$$\displaystyle \frac{\partial\vec{R}}{\partial \theta}= \frac{\vec{R_{h}}(r,\theta+h) - \vec{R}(r,\theta)}{h}:= \vec{e}_{\theta}$$
Because now we have a quite general notion of basis of a coordinate system. But what is this "general notion of basis"? Well, in that question lies my doubt.
When is defined (in a elementary calculus course for example) the notion of partial derivatives,they are defined upon scalar functions like $f(r,\theta)$ i.e. Scalar Fields.
But in order to view basis vectors as partial derivatives, we defined up above as partial derivatives of a Vector $\vec{R}$. Furthermore, the books said that actually these partials ($\displaystyle \frac{\partial\vec{R}}{\partial \theta}$, $\displaystyle \frac{\partial\vec{R}}{\partial r}$) are indeed tangents (vectors) to coordinate curves.
So it seems that the whole construct deals with, Position vectors $\vec{R}$, a particular curve (parametrization) $\gamma (\lambda)$ and the composition:
$$\vec{R} \circ \gamma (\lambda) = \vec{R} [\gamma (\lambda)] = \vec{R}[r(\lambda),\theta(\lambda)]$$
And then, the "true" meaning of partial derivatives as basis vectors lies in this kind of derivation:
$$\displaystyle \frac{\partial}{\partial r}[\vec{R} \circ \gamma (\lambda)]:= \vec{e}_{r}$$
$$\displaystyle \frac{\partial}{\partial \theta} [\vec{R} \circ \gamma (\lambda)] := \vec{e}_{\theta}$$
Is it right what I've said?

A: You are correct until the last two definition $$\frac{\partial}{\partial r}[\vec{R} \circ \gamma (\lambda)]:= \vec{{e}_{r}}$$
$$\frac{\partial}{\partial \theta} [\vec{R} \circ \gamma (\lambda)] := \vec{{e}_{\theta}}$$
because the expression $\vec{R} \circ \gamma (\lambda)$ depends on solely $\lambda$. I don't think you would want to take partial derivative with respect to $r$ or $\theta$.
Instead, you have two curves $\gamma_r,\gamma_\theta$. The first curve will be used to define $\vec{{e}_{r}}$ and the other will be used to define $\vec{{e}_{\theta}}$. The curves are defined as $$\gamma_r:(0,\infty)\to(0,\infty)\times\Bbb R,\ \ \ \gamma_r(\lambda)=(\lambda,\theta_0)$$ where $\theta_0$ is a constant, and $$\gamma_\theta:\Bbb R\to(0,\infty)\times\Bbb R, \ \ \ \gamma_\theta(\lambda)=(r_0,\lambda)$$ where $r_0$ is a constant.
Then $$\frac{d}{d\lambda}[\vec{R} \circ \gamma_r (\lambda)]= \vec{{e}_{r}}$$ $$\frac{d}{d\lambda}[\vec{R} \circ \gamma_\theta (\lambda)]= \vec{{e}_{\theta}}$$
On a closer inspection, this is no different from the first definition you stated.


text:
Q: How can I update geojson properties using popup leaflet? I have GeoJSON file named json_point2. This file holds point data as follows:
var json_point2={
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "Class": null }, "geometry": { "type": "Point", "coordinates": [ 40.193168611061743, 40.904508523555492 ] } },
{ "type": "Feature", "properties": { "Class": null }, "geometry": { "type": "Point", "coordinates": [ 40.191358449981372, 40.902051540140285 ] } },

When I click this point on my web apps, I want to enter input value on popup and save this value geojson Class properties.
I can click on the point with the following code and enter the attribute. But he does not record it in his database.
My code:
map.createPane('pane_point2');
map.getPane('pane_point2').style.zIndex = 602;
map.getPane('pane_point2').style['mix-blend-mode'] = 'normal';
var layer_point2 = new L.geoJson(json_point2, {
    attribution: '',
    pane: 'pane_point2',
    onEachFeature: function (feature, layer) {
        var input = L.DomUtil.create('input', 'my-input');
        input.value = feature.properties.Class;
        L.DomEvent.addListener(input, 'change', function () {
            feature.properties.Class = input.value;
        });
        layer.bindPopup(input);

    }
}).addTo(map);

A: The new L.geoJson(json_point2... just loads the geojson content and create an instance of L.geoJson object. It is normal the modifications of the L.geoJon does not affect the initial JSON variable.
Somewhere in your code, you have to call :
var new_json_point2 = layer_point2.toGeoJSON();

to get a JSON representation of the layer_point2 layer.


text:
Q: How to add a new column in a migration file I'm using Ruby on rails and Sqlite and I got the rspec and factorybot gems. And i'm on Linux ubuntu.
Migration
class CreateArticles < ActiveRecord::Migration[6.0]
  def change
    create_table :articles do |t|
      t.string :title
      t.string :description
      t.integer :price
      t.string :picture
      t.string :author

      t.timestamps
    end
  end
end

Schema.rb
ActiveRecord::Schema.define(version: 2020_02_07_071425) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.string "description"
    t.integer "price"
    t.string "picture"
    t.string "author"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

end

article.rb
FactoryBot.define do
  factory :article do
    title { Faker::Company.name }
    description { Faker::Lorem.paragraph(sentence_count: 35)}
    price { Faker::Number.decimal(l_digits: 2) }
    picture { Faker::Company.logo }
    author { Faker::FunnyName.two_word_name }
  end
end

I just want add a new row like counter 0, but I tried everything (db:migrate, reset, modify all files..) every time my counter is undefined.
What do I need to do?


text:
Q: Puppet - exclude file from management for managed directory I have a couple Splunk servers in house which I manage part of the configuration through puppet. These are residing on CentOS 6 boxes.
My definition is set up as
file{ "/opt/splunk/etc/apps":
  recurse => true,
  purge => true,
  force => true,
  source => "puppet:///modules/splunk/$hostname/apps",
  ensure =>  present,
  mode => 755,
  owner =>  splunk,
  group => splunk,
  notify => Service["splunk"]
}

This works well, but I'd like to exclude the saved searches file at /opt/splunk/etc/apps/myapp/local/savedsearches.conf from being overwritten and / or automatically update the copy contained within Puppet with the version kept on the local server.
Is there a ready way to do this? I looked over the documentation and didn't see anything.

A: You can add ignore    => "savedsearches.conf" to the file stanza to exclude it from operations on the managed directory.
file{ "/opt/splunk/etc/apps":
  recurse => true,
  purge => true,
  force => true,
  source => "puppet:///modules/splunk/$hostname/apps",
  ensure =>  present,
  mode => 755,
  owner =>  splunk,
  group => splunk,
  ignore => "savedsearches.conf"
  notify => Service["splunk"]
}


text:
Q: Matplotlib: Plotting of 3D data on a Cartesian coordinate system, with 1D Arrays (Python) Good Afternoon All,
I'm attempting to create a contour map of surface elevation by using drilling data from a mineral exploration programme. I am new to programming, any feedback would be welcomed!
Each drill hole has a:

*

*hole id

*x co-ordinate (Easting)

*y co-ordinate (Northing)

*z value (surface elevation).

An excerpt of the data is as follows:

Methodology
I broke the work down into two steps.
1) Checking that the data plots in the correct area
I used pandas to extract the co-ordinates of each drilling hole from the csv file, and plotted the data using plt.scatter from matplotlib.
This is my output. So far it works, so now I want to plot the 3D (z axis) data.

2) Plotting of Surface_Elevation (z axis)
This is where I am having problems. I've read through several contouring guides for matplotlib which is dependent on plt.contour. The issue is that this function wants a 2D array, and the data that I want to contour is 1D. Am I missing something here?
My attempt
import matplotlib.pyplot as plt  # plot data
import pandas as pd  # extract data from csv

# access csv and assign as a variable
dataset = pd.read_csv('spreadsheet.csv')

# x_axis values extracted and converted to a list from the csv
x_axis = list(dataset["Orig_East"])

# y_axis values extracted and converted to a list from the csv
y_axis = list(dataset["Orig_North"])

# z_axis values extracted and converted to a list from the csv
z_axis = list(dataset["Surface_Elevation"])

plt.contour(x_axis, y_axis, z_axis, colors='black');
plt.ticklabel_format(useOffset=False, style='plain')  # remove exponential axis labels
plt.xlabel('Easting')  # label x axis
plt.ylabel('Northing')  # label y axis
plt.title('Surface Elevation') # label plot

# plot graph
plt.show()

A: A possible solution is to encode the elevation of each point into the color of the scatter marker. This can be done by calling plt.scatter(x, y, c=z)
you can also specify a desired cmap, see the documentation.


text:
Q: setVisibleXRangeMaximum and Changing the Dataset not Updating the Viewport to the Expected Zoom Level I'm using LineChart that uses 3 view modes; daily, monthly, and annual. The user may switch between those three. All those modes implement date based x-axis whose dataset is provided in milliseconds that is formatted into a specific date format.
I set the visible x range maximum to 6 entries, which means 6 days for daily mode, 6 month for monthly mode, and 6 years for annual mode. Initially, the chart is set to show in daily mode and the result goes as expected. After user switches to the monthly mode and then switches back to the daily mode, the chart seems to zoom according to x-range that was set to monthly mode. So it seems to zoom in to the level that is used by monthly mode. I have logged the last range and last minimum x value of each view modes and make sure that i have set the proper values for each of them.
Here, below is what i have done.
`
private void initChartData(int mode) {
    chart = (LineChart) findViewById(R.id.chart);

    List<Entry> entries = new ArrayList<Entry>();
    Calendar cal = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    Date today = cal.getTime();

    XAxis xAxis = chart.getXAxis();
    xAxis.setGranularityEnabled(true);
    xAxis.setGranularity(1f);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

    switch (mode) {
        case daily:

            cal2.add(Calendar.DAY_OF_MONTH, -30);
            Date thirtyDaysAgo = cal2.getTime();
            dataObjects = realm.where(AmalStat.class).greaterThan("date", thirtyDaysAgo).and().lessThan("date", today)
                    .findAll().sort("date", Sort.DESCENDING);

            Utils.logd("maxgettime: " + maxdaily);
            mindaily = dataObjects.get(dataObjects.size() - 1).getDate().getTime();
            Utils.logd("dataObjects size: " + dataObjects.size());
            int k = dataObjects.size() < 6 ? dataObjects.size() : 5;
            for (AmalStat data : dataObjects) {
                Utils.logd("time: " + data.getDate().getTime() + ", point: " + data.getPoint());
                entries.add(new Entry(data.getDate().getTime(), data.getPoint()));
                Utils.logd("k: " + k);
                if (k == 0) {
                    mindaily = data.getDate().getTime();
                    Utils.logd("min ini: " + mindaily);
                }
                k--;
            }
            rangedaily = maxdaily - mindaily;

            xAxis.setValueFormatter(new MyAxisValueFormatter(mode));
            xAxis.setLabelCount(entries.size(), true);
            break;
        case monthly:

            int month = cal.get(Calendar.MONTH) + 1;
            cal.set(Calendar.DAY_OF_MONTH, 0);
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
            Date minDay = cal.getTime();

            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
            cal.set(Calendar.MONTH, cal.get(Calendar.MONTH));
            Date maxDay = cal.getTime();

            int year = cal2.get(Calendar.YEAR);
            maxmonthly = maxDay.getTime();
            minmonthly = minDay.getTime();
            int j = 6;
            xAxis.setLabelCount(6, true);
            for (int i = month; i >= 0; i--) {
                cal2.set(Calendar.MONTH, i - 1);
                cal2.set(Calendar.YEAR, year);
                cal2.set(Calendar.DAY_OF_MONTH, 1);
                minDay = cal2.getTime();

                cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
                cal.set(Calendar.YEAR, cal.get(Calendar.YEAR));
                cal.set(Calendar.MONTH, i - 1);
                maxDay = cal.getTime();
                SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");

                String minDayText = simpleDate.format(minDay);
                String maxDayText = simpleDate.format(maxDay);
                Utils.logd(minDayText + " - " + maxDayText);
                int wajibs = realm.where(AmalStat.class).greaterThan("date", minDay).and().lessThan("date", maxDay)
                        .sum("wajib").intValue();
                int muakkads = realm.where(AmalStat.class).greaterThan("date", minDay).and().lessThan("date", maxDay)
                        .sum("muakkad").intValue();
                int nonMuakkads = realm.where(AmalStat.class).greaterThan("date", minDay).and().lessThan("date", maxDay)
                        .sum("nonMuakkad").intValue();
                int point = wajibs + muakkads + nonMuakkads;
                entries.add(new Entry(cal2.getTimeInMillis(), point));
                Utils.logd("i: " + i);
                j--;
                if (j == 0) {
                    Utils.logd("ini=" + i);
                    minmonthly = cal2.getTimeInMillis();
                }
            }

            if (month < 12) {
                for (int i = 12; i > month; i--) {
                    cal2.set(Calendar.MONTH, i - 1);
                    cal2.set(Calendar.YEAR, year - 1);
                    cal2.set(Calendar.DAY_OF_MONTH, 1);
                    int wajibs = realm.where(AmalStat.class).greaterThan("date", minDay).and().lessThan("date", maxDay)
                            .sum("wajib").intValue();
                    int muakkads = realm.where(AmalStat.class).greaterThan("date", minDay).and().lessThan("date", maxDay)
                            .sum("muakkad").intValue();
                    int nonMuakkads = realm.where(AmalStat.class).greaterThan("date", minDay).and().lessThan("date", maxDay)
                            .sum("nonMuakkad").intValue();
                    int point = wajibs + muakkads + nonMuakkads;
                    entries.add(new Entry(cal2.getTimeInMillis(), point));
                    Utils.logd("i: " + i);
                    j--;

                    if (j == 0) {
                        Utils.logd("itu=" + i);
                        minmonthly = cal2.getTimeInMillis();
                    }
                }
            }
            rangemonthly = maxmonthly - minmonthly;
            xAxis = chart.getXAxis();
            xAxis.setValueFormatter(new MyAxisValueFormatter(mode));

            break;
        case annual:

            break;
    }

    xAxis.setGranularityEnabled(true);
    xAxis.setGranularity(1f);
    xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);

    Collections.sort(entries, new EntryXComparator());

    LineDataSet dataSet = new LineDataSet(entries, "Label"); // add entries to dataset
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        dataSet.setColor(getColor(R.color.white));
        dataSet.setValueTextColor(getColor(R.color.white)); // styling, ...
    } else {
        dataSet.setColor(getResources().getColor(R.color.white));
        dataSet.setValueTextColor(getResources().getColor(R.color.white)); // styling, ...
    }

    LineData lineData = new LineData(dataSet);
    chart.setDescription(null);    // Hide the description
    chart.getAxisLeft().setDrawLabels(false);
    chart.getAxisLeft().setDrawGridLines(false);

    chart.getXAxis().setDrawLabels(true);
    chart.getXAxis().setEnabled(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        chart.getXAxis().setTextColor(getColor(R.color.white));
    } else {
        chart.getXAxis().setTextColor(getResources().getColor(R.color.white));
    }

    chart.getAxisRight().setDrawLabels(false);
    chart.getAxisRight().setDrawGridLines(false);
    chart.getAxisRight().setDrawAxisLine(false);
    chart.getLegend().setEnabled(false);   // Hide the legend
    chart.setData(lineData);
    chart.invalidate();

    switch (mode) {
        case daily:
            Utils.logd(rangedaily + " " + maxdaily + " " + mindaily);
            chart.setVisibleXRangeMaximum(rangedaily);
            chart.moveViewToX(maxdaily);
            break;
        case monthly:
            Utils.logd(rangemonthly + " " + maxmonthly + " " + minmonthly);
            chart.setVisibleXRangeMaximum(rangemonthly);
            chart.moveViewToX(maxmonthly);
            break;
        case annual:

    }
    chart.invalidate();
    Utils.logd("akhir");
}`

Is this really an issue of MPAndroidChart library or might i ridiculously miss something?

A: I had the same problem and solved it by using setVisibleXRange instead of setVisisbleXRangeMaximum.
Try using this:
    chart.setVisibleXRange(rangedaily,rangedaily);

A: I had the same problem and what helped me is the following simple addition
chart.fitScreen();

that should go before
chart.setVisibleXRangeMaximum(rangemonthly);
chart.moveViewToX(maxmonthly);

Use this three lines each time you change your data set (and notify the chart) to make the chart show you n entries (or all of them in case there are less entries than expected) counting from the end.
I have discovered that chart.fitScreen() same as chart.setVisibleXRange(rangedaily,rangedaily) (suggested by @Coalcandy) dont give the desired effect every time. It depends on the chart sliding. If user after scrolling through the chart values clicks to display another data set while the chart's sliding animation is still on, then no desired effect will be achieved. The way to make sure the chart shows n entries counting from the end each time the data set is changed, add this line
chart.setDragDecelerationEnabled(false);

The drawback is the chart scrolling will not be so smooth.

A: Change following code:
switch (mode) {
    case daily:
        Utils.logd(rangedaily + " " + maxdaily + " " + mindaily);
        chart.setVisibleXRangeMaximum(rangedaily);
        chart.moveViewToX(maxdaily);
        break;
    case monthly:
        Utils.logd(rangemonthly + " " + maxmonthly + " " + minmonthly);
        chart.setVisibleXRangeMaximum(rangemonthly);
        chart.moveViewToX(maxmonthly);
        break;
    case annual:

}

To
switch (mode) {
    case daily:
        Utils.logd(rangedaily + " " + maxdaily + " " + mindaily);
        chart.resetViewPortOffsets();
        chart.setVisibleXRangeMaximum(rangedaily);
        chart.moveViewToX(maxdaily);
        chart.invalidate();
        break;
    case monthly:
        Utils.logd(rangemonthly + " " + maxmonthly + " " + minmonthly);
        chart.resetViewPortOffsets();
        chart.setVisibleXRangeMaximum(rangemonthly);
        chart.moveViewToX(maxmonthly);
        chart.invalidate();
        break;
    case annual:

}


text:
Q: How can I export a Nextjs page as pdf? I have the following structure on a page:
export default function FichaTecnica(props) {
  const data = props.data;
  return (
    <>
      <Container>
        <TopData info={data} />
        <DataSheet datasheet={data} />
        <GraphBox history={data} />
        <MapButton hasMap={data.mapa} />
      </Container>
    </>
  );
}

export async function getServerSideProps(context) {
  const idIndicador = context.params.idIndicador;
  const res = await fetch(
    `${process.env.INDICADORES_BASE_URL}/indicadores/${idIndicador}`
  );

  const data = await res.json();
  if (res.status === 200) {
    return {
      props: { ...data },
    };
  } else {
    return {
      props: {
        data: [],
      },
    };
  }
}

Inside the custom component "" I have a a list of buttons to export the information of the page as Excel, Json, CSV and PDF. I've already done the first three buttons, but I don't know where to start to export my page as PDF.
The idea is to export it as it is, meaning that I want to have it with the same style it has with CSS and the Material UI components, for example, if the website looks like this:

The PDF file should look like that, I know I can make it a Canva and make something like Html > img > PDF but I want to allow the user to select the text of the page in the PDF.
I would really appreciate if you can give me ideas to start with!

A: There are couple of ways to do this

*

*An NPM Server side module - more options potentially

*Client side PDF object formation, lots of challenges - client side dependencies

*Use a service - cost

For #1 - try something like - https://www.npmjs.com/package/html-pdf?activeTab=readme
For #2 - https://github.com/parallax/jsPDF
For #3 - https://www.htmlpdfapi.com/

A: Utilizing the puppeteer on the server side could be a good option.
One could create an API in nextjs to generate the PDF and pass back to the client. Something like below should be a good starting point:
import { NextApiRequest, NextApiResponse } from 'next';
import puppeteer from 'puppeteer';

const saveAsPdf = async (url: string) => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto(url, {
      waitUntil: 'networkidle0'
    });

  const result = await page.pdf({
    format: 'a4',
  });
  await browser.close();

  return result;
};

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { url } = req.query; // pass the page to create PDF from as param

  res.setHeader(
    'Content-Disposition',
    `attachment; filename="file.pdf"`
  );
  res.setHeader('Content-Type', 'application/pdf');

  const pdf = await saveAsPdf(url as string);

  return res.send(pdf);
};


text:
Q: how to fix infinite loop in my java program i'm trying to write a program that can convert seconds into days, hours, minutes, seconds. But I am trying to make it loop so that once converted the program will prompt the user to enter another number of seconds, or if the number is negative end the program. So far, my problem seems to be with my while loop since the number of seconds isnt necessarily 0 it keeps trying to solve and prompt. Here is my code:
import java.util.*;
public class Probleme3
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.print("Input seconds :");
    int sec = in.nextInt();
    int min;
    int heure;
    int jour;

    while(sec != 0)
    {
        if(sec < 0)
        {
        }

        else
        {
        min = sec /60;
        sec = sec % 60;
        heure = min /60;
        min = min % 60;
        jour = heure /24;
        heure = heure % 24;

        System.out.println( jour + ":" + heure + ":" + min + ":" + sec);

        System.out.println("Input seconds :");
    }
    }
}
}

A: remove the while loop:
import java.util.*;

public class Probleme3 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("Input seconds :");
        int sec = in.nextInt();
        int min;
        int heure;
        int jour;

        min = sec / 60;
        sec = sec % 60;
        heure = min / 60;
        min = min % 60;
        jour = heure / 24;
        heure = heure % 24;

        System.out.println(jour + ":" + heure + ":" + min + ":" + sec);

        in.close();
    }
}

for multiple times, use this:

import java.util.*;

public class Probleme3 {
    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int sec;
        int min;
        int heure;
        int jour;
        while(true) {
            System.out.print("Input seconds :");
            sec = in.nextInt();

            if(sec<0) {
                break;
            }

            min = sec / 60;
            sec = sec % 60;
            heure = min / 60;
            min = min % 60;
            jour = heure / 24;
            heure = heure % 24;

            System.out.println(jour + ":" + heure + ":" + min + ":" + sec);

        }
        System.out.println("Program exits.");
        in.close();
    }
}

A: You are reading the user's input only once so the value of 'sec' never changes, since it never changes, it will create an infinite loop. This should do the work:
import java.util.*;
public class Probleme3
{
    public static void main(String[] args)
    {

    int sec = -1;

    while(sec != 0)
    {
      if(sec == 0)
      {
            return;
      }

      else
      {
            Scanner in = new Scanner(System.in);
            System.out.print("Input seconds :");
            sec = in.nextInt();
            int min;
            int heure;
            int jour;
            min = sec /60;
            sec = sec % 60;
            heure = min /60;
            min = min % 60;
            jour = heure /24;
            heure = heure % 24;

            System.out.println( jour + ":" + heure + ":" + min + ":" + sec);

            System.out.println("Input seconds :");
        }
    }
    }
}

A: Well, first of all, if you want to sequentially work with new inputs, you will have to move the input prompts into the loop.
Now the issue with your loop is, that you only set sec in the line sec = sec % 60 and then the loop stops if sec == 0. However this can only happen if is sec is devisable by 60. If I understand your question correctly, something like this should work:
import java.util.*;
public class Probleme3
{
public static void main(String[] args)
{
    Scanner in = new Scanner(System.in);
    System.out.print("Input seconds :");
    int min = 0;
    int heure = 0;
    int jour = 0;

    while(sec != 0)
    {
        System.out.println("Input seconds: ");
        sec = in.nextInt();
        if(sec < 0)
        {
            System.out.println("No values below zero allowed!");
            continue;
        }
        else
        {
            min = sec /60;
            sec = sec % 60;
            heure = min /60;
            min = min % 60;
            jour = heure /24;
            heure = heure % 24;
        }

        System.out.println( jour + ":" + heure + ":" + min + ":" + sec);
    }
}

A: You can do something like this for more clean solution and use java Time API if your using java 8 or above.
public static void main(String... args)
{
    int sec;
    Duration dur;
    Scanner in = new Scanner(System.in);
    while(true)
    {
            System.out.print("Input seconds :");
            sec = in.nextInt();
            if (sec < 0)
                break;

            dur = Duration.of(sec, ChronoUnit.SECONDS);
            System.out.println( dur.toDaysPart() + ":" + dur.toHoursPart() + ":" + dur.toMinutesPart() + ":" + dur.toSecondsPart());
    }
    in.close();
}


text:
Q: How to refactor correctly and effectively How to refactor effectively
I tried cleaning the code to ensure that it's more readable which didn't work out the way I intended it to

A: Make sure that the code you are refactoring is under test. Run the tests after each refactoring step.
Commit your refactored code to version control regularly - as soon as you find it hard to remember all you recent refactorings. The code repository is has a better memory than you do!
Use a good IDE (e.g. Eclipse, Intellij, VSCode) and as far as possible use its wizards to do the refactoring for you, e.g. renaming variables, making a method static, etc. It won't make mistakes!
If you have to make a more complicated change, that the IDE does not support (e.g. strength reduction of a loop) then first think carefully about whether the test coverage is adequate - tests that cover the original code might not cover your refactored code. If so, first add and commit the extra tests.


text:
Q: Is there an ideal number of network operations for iPhone OS? I'm using NSOperation and NSOperationQueue to handle all of my networking threads so my interface can remain responsive while handling data transfer over the internet.  Currently, I've got my operation queue set to a maximum concurrent operation count of 5, and it seems to work well.
I'm wondering, though, if there is a more ideal number of concurrent network operations that would best maximize the available resources without choking the hardware.  Are there any recommendations, or steps I might take to measure and find out for myself?

A: Given the iPhone (currently) runs a single core, I would guess 5 is around the right number.
But the only way to be sure would be to instrument it and find out what the usage looks like (CPU, Memory and Network).  Network usage you could get based on the data transferred - but its hard to know what a reaspnable usage would be.  I'm not sure if it is possible to get CPU/Memory statistics from the iPhone.
If you are doing large transfers, then more connections probably wont help much.  If you are doing lots of small transfers, then more connections will help work around the back and forth of setting up and tearing down the connection.


text:
Q: How to hide Nav bar in some react components I am trying to make a login flow using react. Routes are working as expected. But when I try to introduce nav bar, it is visible on all routes. I want to show nav bar only on selected components (only on profile and home route).
Any suggestions would be appreciated.
This is the Routes.js:

export default class Routes extends Component {
  render() {
    return (
      <Switch>
        <Route
          exact
          path='/*/home'
          component={Home}
        />
        <Route
          exact
          path='/*/login'
          component={Login}
        />
        <Route
          exact
          path='/*/profile'
          component={Profile}
        />
        <Route
          exact
          path='/'
          component={Main}
        />
        <Route
          exact
          path='/*/'
          component={Org}
        />
      </Switch>
    );
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

This is the App.js:

<div className="App">
  <Nav />
  <Routes />
</div>

A: Your Nav component is being rendered in every view because it's located outside your views. There are a couple of options here:

*

*Move Nav into home & profile only. This would make sense if you wanted to keep your Routes component the same.

*Build a higher-order component for rendering a view withNav. This would be the best option if you need to render more than just home & profile with a Nav on top. Let's say you have a modal that needs to have the exact same Nav (for some reason), it may make sense to build an HOC

*Change your component tree to reflect the structure that you need. If only home & profile need the Nav, it may make sense to declare those two routes in a separate component.

A: Here is the solution. Check useLocation hook in "react-router-dom"

function App() {
  const location = useLocation();

  return (
    <>
      {location.pathname === '/' ? null : <Navbar />}

      <Switch>
        <Route path='/' exact component={Home} />
        <Route path='/projects' component={Projects} />
        <Route path='/about' component={About} />
      </Switch>
    </>
  );
}

export default App;

A: You can try Hiding the navbar in css, and Just show in Specific Component Using React-Helmet
 <Helmet>
      <style type="text/css">{`
    .navbar {
        display: inline
    }

`}</style>
    </Helmet>

A: Below piece of code worked for me
 <style type="text/css">
      {`.navbar {display: none}`}
    </style>


text:
Q: removing rows from a matrix I am a new user of both python and R. I have begun using them to try and answer a scientific question that I have. What I am trying to do is the following:

*

*For a matrix, find the mean and standard deviation of each column.

*Remove all rows that contain any value outside of the column mean + or - 3 SD.

*After removing these rows, calculate a new mean and standard deviation and repeat this cycle until there are no longer any outliers.

This would be done with a matrix of approximately 1000 rows and 20 columns.
I would appreciate any guidance as I am really just learning. Thanks!

A: You could try in R:
  meanSDs <- apply(m1, 2, function(x) c(mean(x)+3*sd(x), mean(x)-3*sd(x)))
  any(m1 > meanSDs[1,][col(m1)] | m1 < meanSDs[2,][col(m1)])
  #[1] TRUE

Create a function
 fun1 <- function(mat,n){
                repeat{
                meanSDs <- apply(mat, 2, function(x)
                                   c(mean(x)+n*sd(x), mean(x)-n*sd(x)))
                indx <-mat > meanSDs[1,][col(mat)] | mat < meanSDs[2,][col(mat)]
                indx1 <- !rowSums(indx)
                mat <- mat[indx1,]
                if(all(indx1)) break
                   }
               return(mat)
             }

   m2 <- fun1(m1,3)

Checking the results
  meanSDs <- apply(m2, 2, function(x) c(mean(x)+3*sd(x), mean(x)-3*sd(x)))
  any(m2 > meanSDs[1,][col(m2)] | m2 < meanSDs[2,][col(m2)])
  #[1] FALSE

data
 set.seed(79)
 m1 <- matrix(rnorm(1000*20,1,8), ncol=20)


text:
Q: Шахматы, ходы коня Условия задачи:
Имеется шахматная доска, нам даны координаты коня (от 1 до 8) Нам нужно найти все координаты после 2 ходов конем.
Пример:
Ввод:
5
7
Вывод:
3 3
5 3
7 3
2 4
4 4
6 4
8 4
1 5
5 5
2 6
4 6
6 6
8 6
1 7
3 7
5 7
7 7
2 8
4 8
6 8
8 8

Вот мой код, но он почему то выводит два лишних варианта, не могу разобраться почему
idi=int(input())
idj=int(input())
moves=[[1,2],[1,-2],[-1,2],[-1,-2],
[2,1],[2,-1],[-2,1],[-2,-1]]
a=[]
q=0
for di,dj in moves:
    for ci,cj in moves:
        i=idi+di+ci
        j=idj+dj+cj
        if 0<i<=8 and 0<j<=8 and [i,j] not in a:
            a.append([i,j])
            q+=1
for i in range(len(a)):
    print(*a[i])
print(q)

A: Вроде у вас всё с кодом хорошо.
В любом случае, если бы, например, вам сказали просчитать ходы вплоть до четвёртого хода, вы бы использовали 4 вложенных цикла?
Я бы использовал рекурсию.
У меня переменная depth отвечает как раз за то, насколько глубоко нужно просчитать ходы.
Есть функция GetNextMoves. Она на вход принимает координаты коня, а возвращает лист возможных позиций коня спустя ход.
Также есть рекурсивная функция CalculateMoves, которая как раз "ходит" по древу всех вариантов.
В итоге всё записывается в лист globalArr. Однако в нём будут повторяющиеся позиции. Его следует почистить от повторений.
moves=[[1,2],[1,-2],[-1,2],[-1,-2], [2,1],[2,-1],[-2,1],[-2,-1]]
globalArr = []

def CalculateMoves(depth, i, j):

    arr = GetNextMoves(i, j)

    if depth > 1:

        for move in arr:
            CalculateMoves(depth - 1, move[0], move[1])

    else:

        globalArr.extend(arr)
        #на этом шаге наверное стоит почистить от повторений лист globalArr

def GetNextMoves(i, j):
    arr = []

    for dx, dy in moves:
        x = i + dx
        y = j + dy

        if 0 < x < 9 and 0 < y < 9 and [x, y] not in arr:
            arr.append([x, y])

    return arr

i = int(input())
j = int(input())

CalculateMoves(7, i, j) # глубина хода конём. в вашем случае 2, а не 7

print(globalArr)

A: Не вижу лишних вариантов. У меня те же 21 вариант получается вашим кодом. И если напечатать доску с вариантами всё выглядит нормально:
print(' ',end=' ')
for j in range(1,9):
  print(j, end=' ')
print()
for i in range(1,9):
  print(i,end=' ')
  for j in range(1,9):
    if [i,j] in a:
      c = 'K'
    else:
      c = '~'
    if i == idi and j == idj:
      c = '#'
    print(c, end=' ')
  print()

  1 2 3 4 5 6 7 8
1 ~ ~ ~ ~ K ~ K ~
2 ~ ~ ~ K ~ K ~ K
3 ~ ~ K ~ ~ ~ K ~
4 ~ ~ ~ K ~ K ~ K
5 ~ ~ K ~ K ~ # ~
6 ~ ~ ~ K ~ K ~ K
7 ~ ~ K ~ ~ ~ K ~
8 ~ ~ ~ K ~ K ~ K

P.S. Отсортировать как в примере можно вот так:
print('\n'.join(['{} {}'.format(x,y) for x,y in sorted(a, key=lambda x: (x[1],x[0]))]))

Вывод:
3 3
5 3
7 3
2 4
4 4
6 4
8 4
1 5
5 5
2 6
4 6
6 6
8 6
1 7
3 7
5 7
7 7
2 8
4 8
6 8
8 8

Но там скорее всего сортировка такая, потому что само решение было немного другое - перебирались все клетки доски и делалась проверка, дойдёт ли туда конь в два хода, т.е. в обратную сторону логика шла.


text:
Q: get domain and Computer name into updated by field I have a products table i like to set machine name or domain user Name in to [Updated By] field whenever records are updated using trigger. I want to store domain user name into [Updated By]
i tried to set [Updated By]=nt_username but not working how can i get network informations
CREATE TRIGGER [dbo].[UPDATED_DATE_UPDATED_BY]
    ON [dbo].[tableName]
    AFTER UPDATE
    AS
    BEGIN
     IF TRIGGER_NESTLEVEL() > 1
     RETURN

UPDATE T1
SET    [Updated Date] = GETDATE(),
       [Updated By]=nt_username

FROM   TIRES T1
     INNER JOIN inserted i ON T1.[Auto PN] = i.[Auto PN]
END

A: SQL Server has a built-in function to return the user name associated with the current system user.
CREATE TRIGGER [dbo].[UPDATED_DATE_UPDATED_BY]
    ON [dbo].[tableName]
    AFTER UPDATE
    AS
    BEGIN
     IF TRIGGER_NESTLEVEL() > 1
     RETURN

UPDATE T1
SET    [Updated Date] = GETDATE(),
       [Updated By]=suser_sname()

FROM   TIRES T1
     INNER JOIN inserted i ON T1.[Auto PN] = i.[Auto PN]
END

More on this function here: https://learn.microsoft.com/en-us/sql/t-sql/functions/suser-sname-transact-sql


text:
Q: Maximum size of a poset chain Let $m,n \geq 2$. Consider the poset $(\{1,...,m\}\times \{1,...,n\}, \rho)$ where $\rho $ is defined by $(i,j)\rho (k,l)$ if and only if $i \leq k$ and $j \leq l$.
What is the maximum size of a chain in this poset? What is the maximum size of an antichain in this poset?
I know that the maximum size would be include finding the size of minimum to the maximum or highest up maximal element.  As for the antichain, it would be finding the size of max element to second highest up maximal element.
Any tips?!

A: *

*length of the longest chain: $m+n-1$

*length of the longest antichain: $min\{m,n\}$

The poset is graded or ranked (via $f:(a,b)\to a+b$). Equivalently, every maximal chain has same length. example of a chain: $(1,1)\to (1,2)\to \dots \to (1,n)\to (2,n)\to (3,n)\to \dots \to (m,n)$.
The length of the antichain the largest whitney number (number of elements with a particular rank).
PS: Writing down the hasse diagram is the best way to get the idea. Although, I have used the facts about 'graded' poset, they easy to prove once the definition is known.


text:
Q: Github Windows 'Failed to sync this branch' I am using Github Windows 1.0.38.1 and when I click the 'Sync' button after committing, I get the error

How do I debug this problem? If in the shell, what should I do?
The sync works fine if i do a git push or git pull, but the next time I want to sync using Github windows, I get the same error.

A: I had the same problem when I tried from inside Visual Studio and "git status" in shell showed no problem. But I managed to push the local changes with "git push" via shell.

A: I had this problem and found it was to do with the proxy. I fixed the problem using this command:
 git config --global http.proxy %HTTP_PROXY%

A: This is probably an edge case, but every time I've got this specific error it is because I've recently mapped a drive in Windows, and powershell cannot find it.
A computer restart (of all things) fixes the error for me, as powershell can now pick up the newly mapped drive. Just make sure you connect to the mapped drive BEFORE opening the github client.

A: I had the same problem. In my case git could not find the global variable %HTTP_PROXY%, simply because Windows was not providing/using it.
I solved it by excluding the variable from the git config file (located in %USERPROFILE%\.gitconfig):
[http]
#   proxy = %HTTP_PROXY%

A: Have you changed your Windows password recently, or at least the one you use to connect to your proxy?
This was my problem, and git status couldn't help me. I had to change my login credentials in the ".git/config" file to get past this error.

A: This error comes because of a merge conflict in files. I faced it after I had updated my Maven Project's pom.xml but didn't commit it. Using
git status
error: Your local changes to the following files would be overwritten by merge:
<my project>/pom.xml
Please, commit your changes or stash them before you can merge.
Aborting

as the above post suggested helped finding any conflicting changes and you can decide to discard or commit.

A: When it says that, just open the shell and do git status. That will give you a decent idea of what could be wrong and the state of your repo.
I can't give you a specific error for this as it happens for many reasons in Github for Windows, like say some problem in updating submodules etc.

A: I had the same problem. It happened to me because of some conflicting changes. I removed the local repository of my project from my desktop and then cloned it again from the github website (using clone option in my account), the error was gone.

A: This error also occurs if the branch you're trying to sync has been deleted.
git status won't tell you that, but you'll get a "no such ref was fetched" message if you try git pull.

A: One more thing that can cause this is when you map a network drive or connect a VHD after GitHub Desktop has already been started.  The reason for this is that GitHub Desktop uses ssh-agent from the portable GIT install to establish connections, and never closes it... even if you uninstall the application.  The process starts with no knowledge of the new drive and never refreshes itself, and when it is used to run the GIT commands to work on your repo it fails because it doesn't understand the paths.
The solution in this instance is to close GitHub Desktop and use Task Manager to terminate the running ssh-agent before starting it again.  This will start a new instance of ssh-agent when needed which will pick up the new drive mappings, etc.

A: Make sure that the branch you are trying to push to isn't protected. I was trying to push to a protected branch and failed same as you.

A: check "git status" and "git pull" in the shell and find out what's wrong.
and my problem is http.proxy node in config, therefore Github Windows should much more smart like just pop the shell and give more tips after the error(s) emit.

A: Along the lines of the HTTP Proxy answers, this can also happen due to a VPN connection. Disconnecting my VPN connection solved it for me.

A: I had the same issue, and "git status" also showed no problem, then i just Restarted the holy GitHub client for windows and it worked like charm.

A: I had the same issue. I removed the repo from the GitHub Windows client (right-click menu) and re-added it. When I re-added, I noticed I had about 300 uncommitted changes and it was reporting a memory error. I discarded all the changes and then sync started working fine again. (Rookie Git user - I'm sure there are better ways to do this on the command line)

A: The debug log may provide some insight.  I'm using v3.3.4.0, your experience may differ but should be similar.  From the settings menu choose 'About Github Desktop...'.  Click the link to view the debug log.  In my case there was a very clear error:
*** fatal error - cygheap base mismatch detected - 0x1157408/0x1167408.
This problem is probably due to using incompatible versions of the cygwin DLL.
It even provided some helpful tips to solve the problem.
I'm not sure why this information isn't exposed in the error prompt, but at least it was available.

A: I tried with Android Studio to commit Changes and push it to master But Window Showed a popup that I have to enter Github Credentials (https://github.com). I did Signup with my Gmail account So I tried to enter my Gmail id along with its password, Obviously Git do not have my Gmail password and can't match it with what I'm providing, So I ended up canceling the push.
When I tried to sync my changes through GitHub GUI Window I encounter this error. On git status command Git Shell suggested to push changes as
Your branch is ahead of 'origin/master' by 1 commit.
  (use "git push" to publish your local commits)

I did the same as Git Shell suggested (git push) and everything is ok now.
Note: for someone who is new to git you have to change your path to the folder where your .git file is otherwise on Every Command you enter Git Shell will show error that its not a git repository.
fatal: Not a git repository (or any of the parent directories):

For example if your Project is in D drive in some folder you have to do something like below as you do in cmd to change directory.
cd D:\someFolder     // if your project is not deep in `D`

And if its within nested folder in D
cd D:\somefolder\someNestedFolder\nestedInNested     // if your project is not deep in `D`

If someone know how to login into Github popup from windows as I did signup with google account and here are 2 fields only Github username, password Please let me know. I have resolved the issue but with waste of some time so I want to know about login too.


text:
Q: Can someone explain how this transistor comparator works? I am looking to make a comparator using transistors and I stumble across this circuit claiming to be one:

Unfortunately, the description that came along with it leaves a lot to be desired, referencing components and points that aren't actually here - I assume due to typos but I can't actually work out how it is meant to work.
The purpose for this is I want to have a voltage reference of 1.8 - 2V, and then a supply rail connected to the other side. So long as the supply rail is higher than my reference voltage, it will allow power to be supplied to a component, but if not, it should remove power from it.
Any thoughts as to how this works and whether it is suitable for my application? Diagrams would help me to understand it more but any help would be appreciated.

Extra Information:
I want to use this 'comparator' in a circuit where I have a \$\mu\$C being powered by a current limited ~2V regulator. Currently, if the voltage output of this regulator drops below 2V the \$\mu\$C causes the rail to latch at 1.7V - 1.8V and won't allow it to  rise to 2V again which is a bit of an inconvenience if anything. (How can I get this PMOS to turn off? is another question of mine which contains more information on the issue I am currently having)
I currently have a delay switch that will allow my reservoir capacitor to fill enough to be able to handle the initial start-up current of the \$\mu\$C. There are some problems with this and I just thought I might be able to replace it with a simple comparator, have a ~2V reference on one pin and the rail to the \$\mu\$C on the other and if this falls below my reference, it will simply cut off the power completely - this will prevent it from latching at ~1.7V and will allow the reservoir capacitor to fill up again in order to provide the needed start-up current again.
It isn't something that would happen a lot, and realistically, once fully designed and programmed, the circuit would never cause this rail to drop below 2V - however, there are some circumstances that might cause it to happen so it is a 'just-in-case' type thing.

A: The circuit is a comparator and can be remarkably useful more or less as shown.
I have used a circuit essentially the same as that in production equipment to meet a requirement which was difficult to meet easily and cheaply by other means.
There are several ways to look at the circuit. The circuit does not care which way you look at it - but one or other visualisation can help your understanding.
This is known as a "long tailed pair" but in this case the "tail" is not very long in the sense originally meant. In an ideal version of this circuit the Re leg is a constant current source, always sinking current Ie.
Call lh transistor Q1 and rh transistor Q2
Call base voltages Vi1 and Vi2 OR Vil and Vir
Call collector voltages Vcl / Vcr or Vc1/Vc2
Call emitter voltage Ve (shared by Q1 & A2)
For now, assume that the combination of Ie, Re & Vee form an ideal constant current source of current Ie - this assumption can be revised later if desired - but makes it easier to follow operation initially and in many real world cases the assumption is "good enough.
RC1 = RC2 in most basic cases. In fact a special and useful case occurs when RC1 is substantially different to RC2 BUT for the basic differential amplifier assume they are equal. If "almost equal" with differences due to production tolerances it STILL works but with non-idealities. Assume identical for now.
Ideally Q1 and Q2 are matched in characteristics but, for many purposes they can just be two of the same type.
Assume transistors are matched to start with. This also can be revisited and is NOT essential.
In most cases Ie and Rc are arranged so the transistors do not saturate when both are at about the same current - even this is not hard and fast BUT start with it so.
Operation:
(1) Version 1:
Imagine that Vb1 = Vb1 and > Re such that current Ie divides in 2 equally (as transistors are matched) and Ie/2 flows in each transistor.
Vc1 = Vc2 as resistors and currents are equal.
Now increase Vb1 slightly. Q1 draws more current by say dIe.
But as total current is constant Q2 must decrease current by dIe.
Vc1 will fall by dIe x Rc1 and Vc2 will rise by an equal amount.
In practice the internal emitter resistance of Q1 falls with increasing current (Re ~= 26/Ima) and this effect increases the current gain of Q1 and reduces the gain of Q2 and increases the voltage difference BUT this does not need to be taken into account directly to understand operation (although the following paragraph is closely related).
If transistor action was linear with Ie ~+ Ic proportional to Vbe then a slowly increasing base voltage on Q1 would ramp up Iq1 and decrease Iq2 linearly. However, Ic increases exponentially with Vbe, without delving into transistor models a standard model states.

From Wikipedia - Bipolar junction transistor
Essentially this can be reduced to saying that Ic is proportional to Vbe (as above) plus a constant based on other "factors" which are not relevant here. (One of the "constants" is temperature which matters muchly in the real world but here can be ignored.)
The result of this is that for smallish increases of Vb1 relative to Vb2, Ic1 changes exponentially, decreasing the current flowing via Q2 and so causing Vc1 to dop and Vc2 to rise.
Plug the changes for typical voltages and currents into the above equation and you can plot gain and voltage swing.
For largish increases in Vb1, say tenths of a Volt. It can easily be arranged that Q1 saturates as Ib_Q1 x beta_q1 is > Ie. At this stage Q1 takes all the current, Q1 is turned hard on and Q2 turns off and Vc2 rises to Vcc. A surprisingly effective comparator can be achieved.
If Re/Ie is not a current source then increasing Vb1 increases I_Q1 so V_RE rises due to increased current. This reduces Vbe Q2 as Vb2 is constant and Ve has risen - so current share swings towards Q1 and Reinternal Q1 drops and Reinternal Q2 rises (which is part of another way of looking at the exponential VBe/Ic relationship) and differential action still happens.
More can (easily) be said but that's enough for niw.
(2) Version 2.
Q1 is an emitter follower.
RC1 does not strictly matter except that it helps maintain transistor performance matching.
When Vb1 = Vb2 then the voltage drop
"down from Q1b to Q1e matches the step up from Q2e to Q2b.
As Q1 is an emitter follower it will control Ve with Ve = Vb1 - Vbe1.
An increase in Vb1 raises Ve by the same amount (if Vbea remains constant(which is a good enough approximation for small Vb1 rises)).
Ve rising reduces Vbe2 by the same amount so reduces Ic2 as Ic1 increases due to exponential effect of increased Ic1 on gain.  And ...

*Version 3.
This is another look at version 2 (and 1 2 3 are, of course,  all the same in reality)

Q2 is a common base amplifier with base held at Vb2 and input voltage = Ve.
Changes in Ve caused by changes in Q1 emitter follower action are amplified in common base mode. (This is in fact essentially the same as common emitter mode but you stand in a different place to look, as it were).
Some playing with the above transistor equation and plugging in Boltzman's constant (k above) produces the astounding-to-many result that gain of Q2 = 38.4 x (Vcc-Vc2)
ie gain is 38.4 x drop across the collector resistor. As we vary Ve by say 0.1V then if V_RC2 initial = say 5VDC then Vc2 will change by 38.4 x 5V x 0.1V input change = 19.2V.
IF the supply is 10V say then a change of 19V cannot happen and Q2 will turn off and Q1 will turn fully on with much less than 0.1V change in Vb1.
This real world result is so contrary to common sense and what most people think that they know about transistors that putting on on flame suits about now may be a good idea :-).

Does it work:
I wished to measure the rotor speed of an exercise bicycle which used a 3 phase alternator as load - using alternator waveforms alone. This saved the client the cost of a reed or hall sensor and wiring and connection. Not vast, but worthwhile IF it could be done very cheaply. I used connections to 2 of the phase windings. (Using one only proved non viable).
I used 2 x BC337 transistors with 1M (AFAIR - about 14 years ago) to each base and maybe 1k as Re and RC = ? (1k, 10k?) Cct can be dug out if needed.
I fed in up to 200 VAC from 2 phases of an alternator (2 phase exercise bicycle) with 20 kHz PWM resistive loading. Alternator frequency I forget but probably hundreds of Hz depending on user pedaling rate. Suffice it to say the variable voltage and frequency, variable load, 20 kHz PWM, saturating laminations as speed increased, sinusoidal to trapezoidal waveform change and more made the input "a bit of a mess". Out of this with minimal filtering the "long tailed pair" extracted a beautifully clean rotor speed proportional signal. Transistors were not matched and bases had no resistors to ground - the 2 x 1M acted as current sources and each transistor in turn got less or more drive.
This was an extreme case - but the circuit is useful elsewhere. The various non-idealities I mentioned above tend to show up mainly as input offset voltage - one bases will be at a higher voltage than the other when the system is "at balance". If this is tolerable, and it often is, the result can be excellent.
A long tailed pair is far closer to an opamp than almost anything else you can do cheaply and easily without ICs.
Almost magic :-).

"Hyperphysics" Transistor Operation
How to Calculate the Collector Current of a Transistor


text:
Q: How to find out if numbers are different in pascal? i can't solve one pascal problem, first i have to enter N which is the number or mesurments, next i enter those mesurments (if N is 5 i enter 5 mesurments for exmaple 3 4 5 6 7). After that i enter Q which is the number of times i check the number of different numbers in a specific part of the row. For example you have input
5 (number of mesurments)
1 2 3 3 4 (mesurments)
3 (number of checkings)
1 3
3 4
1 5 (left number is the starting number from the row, if it's 1 you start from 1, if it's 4 you start from 3 because 3 is the fourth mesurment and the right number is the last number if it's 5 it would be 4 because 4 is the fifth in the row)
And for output you would get
3
1
4 (for the first checking you have number from 1 to 3 (1 2 3) and you have 3 different numbers, second mesurment from 3 to 4 (3 3) and it's 1 different number and last from 1 to 5 there are 4 different numbers)
Hope you understod me, and thanks if you can solve it, i am in highschool now and i am preparing my self for something more complicating :) thanks in advance

A: The inequality operator of Pascal is <>


text:
Q: Working with time-series data that is in LST timezone, WITHOUT daylight savings time. How can I convert this to PST8PDT? I am working in Pandas with NOAA hourly meteorological data, which is recorded in Local Standard Time (without regard for daylight savings time). How can I convert this to LST with Daylight Savings?
So far I have tried adding an 8 hour offset to the tz naive datetime data, localizing to UTC, then converting back to PST8PDT, but that did not work.
import pandas as pd
import datetime as dt
from datetime import timedelta
Date_time = pd.to_datetime(df.DATE) + pd.Timedelta('8 hours')
Date_time = Date_time.dt.tz_localize('UTC')
Date_time = Date_time.dt.tz_convert('PST8PDT')

EDIT: Thank you for all the help! I localized with the fixed offset (UTC-8), but when I convert to 'America/Los_Angeles' or 'PST8PDT' it seems like all the datetimes are off by -8 or -7 hours, unless I am misunderstanding the datetime conventions.
To illustrate the problem:
Here's the raw time data
Here's the datetime data after I localize to UTC with fixed offset
And here's the datetime data after I convert to "America/Los_Angeles" time zone.
As you can see, it applies Daylight Savings Time, however I am confused by the fact that all the datetimes say "-08:00" or "-07:00". Does that mean that 8 or 7 hours is being subtracted from each displayed datetime? Or am I misinterpreting that?
Either way, the good news is I found that if I just leave the data in UTC timezone with the fixed offset, I am able to work with it without any issues.


text:
Q: Ignore new lines in regex That is my pattern:
^[ A-Za-z0-9ığüşöçİĞÜŞÖÇ_.,#:&+-]*$

it accepts those chracters and spacse.
But i also want to have new lines.User can enter new lines such as
asdasda
asdasda

asdasdsa

What should i do?
this is my regex
https://regex101.com/r/N3Dbrz/3
I want to accept new lines but want all string as without new lines. In the link it is accepting without new lines.
So, the example should be recorded as
asdasda asdasda asdasdsa

not with new lines
I am using javascript, angularjs. in my javascript, it is like this:
vm.addressTextPattern = /^[ A-Za-z0-9ığüşöçİĞÜŞÖÇ_.,/#:&+-]*$/;
<textarea rows="5" ng-disabled="true"
         name="billingCompanyAddress"
         ng-model="vm.model.billingAddress.line1"
         ng-required="true"
         ng-minlength="15"
         ng-pattern="vm.addressTextPattern"
         maxlength="255"
         md-maxlength="255"></textarea>

A: A regex cannot "skip" parts of a string within one match operation. So, what you need is a multi-step approach:

var s = "asda sda\nasdasda\n\n\nasdasdsa";
var re = /^[ A-Za-z0-9ığüşöçİĞÜŞÖÇ_.,#:&+-]*$/;
console.log("Original string:", s);
var isValid = s.split("\n").every(function (t) {return re.test(t); });
console.log("Valid:",isValid);
if (isValid) {
 console.log("Record with no LF and empty:", s.split("\n").filter(Boolean).join(" "));
}

Note you may use a regex like
/^[ A-Za-z0-9ığüşöçİĞÜŞÖÇ_.,#:&+-]*(?:\n+[ A-Za-z0-9ığüşöçİĞÜŞÖÇ_.,#:&+-]*)*$/

to validate the whole multiline input. See its demo. Then, you'd replace isValid code part to
var isValid = /^[ A-Za-z0-9ığüşöçİĞÜŞÖÇ_.,#:&+-]*(?:\n+[ A-Za-z0-9ığüşöçİĞÜŞÖÇ_.,#:&+-]*)*$/.test(s);

Still, you will have to replace the line breaks after that with spaces. s.split("\n").filter(Boolean).join(" ") may be replaced with a regex like
s.replace(/\n+/g, " ")

NOTE: To support \r\n, \r, and \n line break styles, replace split("\n") with split(/\r\n?|\n/), \n+ with (?:\r\n?|\n)+.


text:
Q: Spring Security 3 no-xml role restriction doesnt work I'm using spring security in a new application and I configured the WebSecurityConfigurerAdapter. Everything with the filters works fine, but the problem comes on the distinction of two holes I have: Usuario(User) and Administrador(admin). The problem comes when I login with the User role and I access the path I restricted for that(/restricted) -- everything works fine, filter applyed --, but when I access as Admin, I can only manage to access the user path (/restricted), and not the /admin path, which I would like to.
Here bellow is the configuration as I did.
@Override
protected void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests()
     .antMatchers("/resources/**", "/includes/**", "/cadastrar", "/logout", "/login", "/", "/home").permitAll()
     .antMatchers("/admin/**").hasRole("ADMINISTRADOR")
     .anyRequest().authenticated().antMatchers("/restricted/**").hasRole("USUARIO")
     .anyRequest().authenticated().and().formLogin()
    .loginPage("/login").defaultSuccessUrl("/success-login", true)
    .loginProcessingUrl("/login").failureUrl("/login?error=true").permitAll().and()
    .logout().logoutUrl("/logout").logoutSuccessUrl("/");
}

Does anybody here knows whats wrong?
Thanks much

A: Resolved. I've just changed to authority instead of hole. Everything works fine now.
@Override
protected void configure(HttpSecurity http) throws Exception {
     http.authorizeRequests()
     .antMatchers("/admin/**").hasAuthority("ADMINISTRADOR")
     .antMatchers("/restricted/**").hasAnyAuthority("USUARIO", "ADMINISTRADOR")
     .antMatchers("/resources/**", "/includes/**", "/cadastrar", "/logout", "/login", "/", "/home").permitAll()
     .and().formLogin()
    .loginPage("/login").defaultSuccessUrl("/restricted/teste", true)
    .loginProcessingUrl("/login").failureUrl("/login?error=true").permitAll().and()
    .logout().logoutUrl("/logout").logoutSuccessUrl("/");
}


text:
Q: YAJSW Java beginner examples Can anyone help me in either providing me some right direction towards using yajsw using java language to use java application as service or just provide me some basic code of hello world application which i can run as service. I googled it but could not find any thing useful.
Thanks in advance

A: YAJSW's documentation provides everything you need here. http://yajsw.sourceforge.net/
The easiest way to get running is to execute your jar with your own start script. Then you need to figure out what PID that java process is running as. Once you have the pid all you need to do is run either ./yajsw/yajsw##someversion##/bat/genConfig.bat or if your in linux run the ./yajsw/yajsw##someversion##/bin/genConfig.sh .
If successful this will create a wrapper.conf that is targeted towards your executable jar. This is plenty to get you going and off the ground. After that you can tweak the heck out of it for your own customizations.
The (genConfig.bat or genConfig.sh)'s argument is the PID. So run genConfig.bat #PID# !
PS: The config generator will add the classpath of each jar .. when it is easier just to add one classpath as wrapper.java.classpath.1 = .\lib\* instead.

A: Ok, you can start by downloading JBoss 5.x  and using this wrapper script I wrote to get it running.  This serves just as an example for you.  You would have to edit it to run whatever your application happens to be.
I also wrote a script for JBoss 7 servers.


text:
Q: $scope not updated from async error callback I am trying to update the $scope from an promise error callback as follows:
 var reportErrors = function (error) {
      $scope.state['save-mappings']='update';
      ...
 }

 myService.myMethod().then(postProcess).catch(reportErrors);

However, the $scope is not updated properly and the corresponding ng-if does not update...
<div ng-if="state['save-mappings'] === 'update'">

Can someone please help?
edit: postProcess function:
var postProcess = function (data) {
    var associateMediasPromise = function () {
        return SupplierImportService.associateMedias($scope.getLink($scope.ngDialogData.import.links, 'associate-medias'));
    };
    var matchArticlesPromise = function () {
        return SupplierImportService.matchArticles($scope.getLink($scope.ngDialogData.import.links, 'match-articles'));
    };
    var updatePostProcessPromise = function () {
        $rootScope.$broadcast('init-headers');
        $rootScope.$broadcast('update-import', data.data);
        $rootScope.$broadcast('change-articles-page');
        $rootScope.$broadcast('update-statistics');
        $scope.setPopinState('save-mappings', 'done');
    };
    return associateMediasPromise()
        .then(matchArticlesPromise)
        .then(updatePostProcessPromise);
};

from myMethod:
var myMethod = function () {
 return $http.post(...);
};


text:
Q: Processing HTTP Get response using ajax in html I am writing a html to make a REST GET call to underlying service and display the JSON result in tabular format. Below is my attempt at that

    Rides Dashboard View

         <form name="submitform" id="submitform">
               <input type="submit" value="Refresh">
         </form>

When I perform submit action, I expect that the resultant JSON data to be alerted but nothing happens.
Also here is the sample JSON output data
{
  "data": [
    {
      "requestId": 40,
      "customerId": 123,
      "requestTime": 1502652408000,
      "status": 2,
      "driverId": 1
    },
    {
      "requestId": 41,
      "customerId": 342,
      "requestTime": 1502652425000,
      "status": 2,
      "driverId": 2
    }
    ]
}

I want to display it in the tabular format like below
RequestId |  CustomerId | RequestTime  | Status | DriverId
40        |     123     |1502652408000 |   2    |    1
So can someone help me with processing the resultant data from GET request in this tabular format ?

A: The issue is  before closing  tag at HTML.

A: you can create table from json like this,


text:
Q: Is there an SQL Clause to check if all multiple Values exists instead of using multiple AND? Instead of typing
... WHERE transaction = 1 AND transaction = 2 AND transaction = 3 AND transaction = 4 AND transaction = 5
Is there any Clause to check it once In one simple set like this?
... WHERE transaction HAS(1, 2, 3, 4, 5)

A: Use group by and having:
SELECT name
FROM table
WHERE aid IN (1, 2, 3, 4, 5)
HAVING COUNT(DISTINCT aid) = 5;


text:
Q: C# EventHandler to catch calling to Console.WriteLine() function I'm using CefSharp.OffScreen (63.0.3) in my project.
This package sometimes prints messages to the console by calling Console.WriteLine(), there is a way to stop it by defining LogSeverity.Disable but they have an open issue of this bug (it's still printing).
I want, in my project, to catch any calls to Console.WriteLine() and decide whether to ignore it or print it.  Is there is a way to do that?
• Edit:
Any prints that came from the external package start with "[" symbol, So I just need to catch any print and check if the string starting with "[" to know if I want to print it or not...


text:
Q: log4j 1.2 to log4j 2 migration not working I am trying to migrate log4j from 1 to 2 and logs are not generated.
I removed actual path of writing and application able to write the logs the mentioned path since logs are not printing after upgrade only
Legacy code contains
Parent Pom
<!--
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
-->

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-1.2-api</artifactId>
    <version>2.16.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.16.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.16.0</version>
</dependency>

Child POM: - Updated version only
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <!-- <version>1.7.5</version> -->
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-ext</artifactId>
    <!--  <version>1.7.5</version> -->
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-jcl</artifactId>
    <!-- <version>1.7.5</version> -->
    <version>1.7.25</version>
</dependency>

<!--
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.5</version>
    </dependency>
-->
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.17.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-nop</artifactId>
    <!-- <version>1.7.5</version> -->
    <version>1.7.25</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <!-- <version>1.7.5</version> -->
    <version>1.7.25</version>
</dependency>

log4j -> xml
<log4j:configuration>
    <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{ISO8601}] [%t] %-5p %c{1}: %x - %m%n" />
        </layout>
        <filter class="org.apache.log4j.varia.LevelRangeFilter">
            <param name="LevelMin" value="DEBUG" />
            <param name="LevelMax" value="INFO" />
            <param name="AcceptOnMatch" value="true" />
        </filter>
    </appender>

    <appender name="errout" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.Err" />
        <param name="Threshold" value="WARN" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{ISO8601}] [%t] %-5p %c{1}: %x - %m%n" />
        </layout>
    </appender>

    <appender name="userLog" class="com.test.RollingFileAppender">
        <param name="File" value="userlogs.log" />
        <param name="Threshold" value="INFO" />
        <param name="MaxFileSize" value="50MB" />
        <param name="MaxBackupIndex" value="5" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m | [%d{ISO8601}] | [%t]%n" />
        </layout>
    </appender>

    <appender name="errorLog" class="com.test.RollingFileAppender">
        <param name="File" value="error.log" />
        <param name="Threshold" value="ERROR" />
        <param name="MaxFileSize" value="50MB" />
        <param name="MaxBackupIndex" value="10" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%d{ISO8601}] [%t] %-5p %c{1}: - %m%n" />
        </layout>
    </appender>

    <category name="REQUEST_LOG" additivity="false">
        <priority value="INFO" />
        <appender-ref ref="userLog" />
    </category>

    <root>
        <priority value="INFO" />
        <appender-ref ref="errorLog" />
    </root>

</log4j:configuration>

We initialized log4j programatically
import java.io.File;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

import ApplicationContext;
import ResourceUtility;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.LogManager;

public class Initializer implements Startable {

    private static Log logger = null;
    private static boolean logsPathSet = false;

    private static String logsPath = "";

    static {
        BasicConfigurator.configure();
        logger = LogFactory.getLog(Initializer.class);
    }

    public static void initialize() {
        logsPath = System.getProperty("log4j.configuration","");
        logsPathSet = (logsPath != null && !logsPath.equals(""));
        initializeLogging();
        ApplicationContext.getInstance();
    }

    public static void initializeLogging() {
        String configFile = "";
        URL aURL  = null;

        if ( logsPathSet ) {
            configFile  = logsPath;
            aURL = ResourceUtility.geUrlResource(configFile);
        }

        if ( (!logsPathSet) || ( logsPathSet && aURL == null) ) {
            configFile = ApplicationContext.getInstance().getStringProperty("logging", "log4j", "configFile");
            aURL = ResourceUtility.geUrlResource(configFile);
        }
        DOMConfigurator.configure(aURL);
        logger = LogFactory.getLog(Initializer.class);
        logger.info("Configured Logging from: " + aURL);
    }
}

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;

import ApplicationContext;
import Initializer;
import ResourceUtility;

    public class Startup extends HttpServlet {

        private static Log logger = LogFactory.getFactory().getInstance(Startup.class);
        public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
        public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}

        public void init() throws ServletException {
            super.init();
            ApplicationContext.getInstance();
            Initializer.initialize();
            String loggingProperty = "/" + ApplicationContext.getInstance().getProperty("logging", "log4j", "configFile");
            loggingFile = ResourceUtility.getFileResource(loggingProperty);
            PropertyConfigurator.configure(loggingFile.toString());
        }

    }

I tried with couple of approach.
Approach 1 -> Migrating log4j 1 to 2 directly and updated log4j connfig
System.out -> SYSTEM_OUT -> tried with bith target
Updated log4j xml file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Appenders>
        <Console name="console" target="System.out">
            <PatternLayout pattern="[%d{ISO8601}] [%t] %-5p %c{1}: %x - %m%n" />
            <LevelRangeFilter minLevel="DEBUG" maxLevel="INFO" onMatch="ACCEPT" onMismatch="NEUTRAL" />
        </Console>
        <Console name="consoleError" target="System.Err" follow="true">
            <PatternLayout pattern="[%d{ISO8601}] [%t] %-5p %c{1}: %x - %m%n" />
            <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="NEUTRAL" />
        </Console>

        <RollingFile name="userLog" fileName="/userlogs.log"  filePattern="/userlogs.log.%d{yyyyMMdd}">
            <PatternLayout pattern="%m | [%d{ISO8601}] | [%t]%n" />
            <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY" />
        </RollingFile>

        <RollingFile name="errorLog" fileName="/error.log"  filePattern="/error.log.%d{yyyyMMdd}">
            <PatternLayout pattern="[%d{ISO8601}] [%t] %-5p %c{1}: - %m%n" />
            <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY" />
        </RollingFile>
    </Appenders>

    <Loggers>
        <Logger name="REQUEST_LOG" additivity="false">
            <AppenderRef  ref="userRequestLog" level="INFO" />
        </Logger>
        <Root  level="INFO">
            <AppenderRef  ref="errorLog"/>
        </Root >
    </Loggers>
</Configuration>

Updated Initalizer class
//BasicConfigurator.configure();
Configurator.initialize(new DefaultConfiguration());

// DOMConfigurator.configure(aURL);

LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
loggingFile = ResourceUtility.getFileResource(configFile);
context.setConfigLocation(loggingFile.toURI());
context.reconfigure();

ConfigurationFactory.setConfigurationFactory(new XmlConfigurationFactory());
Configurator.reconfigure(loggingFile.toURI());

Updated startup into
// PropertyConfigurator.configure(loggingFile.toString());
        ConfigurationFactory.setConfigurationFactory(new XmlConfigurationFactory());
        LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
        //Configurator.reconfigure(loggingFile.toURI());
        context.setConfigLocation(loggingFile.toURI());
        context.reconfigure();

Logs are not generated for the above approach
Approach 2 ->
Same changes by adding bridge jar -> skipped log4j xml changes
Thanks in advance for any recommendation or changes or approach or can you please share steps you followed while migrate the same or share the approach with minimal code changes.

A: I'd advise to follow the second approach, but you have to use log4j 2.17.2+ version. The bridge jar has big issues in previous versions, but the devs made an effort at the start of this year to fix it. I would have made this a comment rather than an answer, but have low reputation.
In my case it was possible to make a simple jar file and overwrite the existing log4j
version 1 jars with it on 200 running apps without changing any config files in the apps or on app server. How is that for an "approach with minimal code changes" :)


text:
Q: How do I earn honor in America's Army? Specifically, respect and personal courage; those are my two lowest stats.

A: From the manual for Americas Army:

*

*Respect is scoring based on following orders and showing respect for others. Respect points are earned by actions such as completing leader-assigned objectives and securing enemy Soldiers.

*Personal Courage is scoring based on courageous behavior by a Soldier. Players earn Personal Courage points from activities such as neutralizing enemies and completing objectives while badly wounded.

For the sake of completion, I'll list the rest of the categories as well:

*

*Loyalty is teamwork based scoring. Assisting teammates completing objectives, neutralizing enemies, and other actions earns you points in Loyalty. To earn Loyalty points you must be linked to a teammate when they achieve a scoring opportunity.

*Duty is mission and objective based scoring and is earned when a player wins missions and completes objectives.

*Selfless Service is scoring based on helping others and doing the right thing. Players gain Selfless Service points through such actions as performing medical care on fellow Soldiers, responding to injured and incapacitated Soldiers quickly and performing triage on fellow soldiers in the correct order.

*Honor is the average of all other Army values. When you achieve enough points in your Army Values scores, your Honor level increases. An increase in your Honor level earns a Soldier advancement points and increases the Soldier's rank.

*Integrity is the only Army Value which can cause points to be lost as well as gained. Integrity points are lost by harming fellow Soldiers, damaging military equipment, or harming incapacitated enemy Soldiers.


text:
Q: Think Python 2nd Edition Exercise 7-1 "Square Roots" loop:
while True:
    y = (x+ a/x) / 2
    if y == x:
        return x
    x = y

Copy the loop from "Square Roots" and encapsulate it in a function called mysqrt that takes a as a parameter, chooses a reasonable value of x, and returns an estimate of the square root of a.
To test it, write a function named test_square_root that prints a table like this:
a   mysqrt(a)     math.sqrt(a)  diff
-   ---------     ------------  ----
1.0 1.0           1.0           0.0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0.0
4.0 2.0           2.0           0.0
5.0 2.2360679775  2.2360679775  0.0
6.0 2.44948974278 2.44948974278 0.0
7.0 2.64575131106 2.64575131106 0.0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0           3.0           0.0

Here's what I wrote:
import math

def mysqrt(a):
    x = a/5
    while True:
        y = (x+ a/x) / 2
        if y == x:
            return x
        x = y

def test_square_root():
    a = 1.0
    print('a', repr(mysqrt(a)).rjust(6), repr(math.sqrt(a)).rjust(12), 'diff'.rjust(10))
    print("-      ---------            ------------          ----")
    while a < 10.0:
        print(a, "  ", mysqrt(a), "  ", math.sqrt(a), "  ", abs(mysqrt(a)-math.sqrt(a)))
        a += 1

test_square_root()

Here's what I got:
a    1.0          1.0       diff
-      ---------            ------------          ----
1.0    1.0    1.0    0.0
2.0    1.414213562373095    1.4142135623730951    2.220446049250313e-16
3.0    1.7320508075688772    1.7320508075688772    0.0
4.0    2.0    2.0    0.0
5.0    2.23606797749979    2.23606797749979    0.0
6.0    2.449489742783178    2.449489742783178    0.0
7.0    2.6457513110645907    2.6457513110645907    0.0
8.0    2.82842712474619    2.8284271247461903    4.440892098500626e-16
9.0    3.0    3.0    0.0

As you can see, the array is not neatly aligned. How can I print an array if the elements do not have the same length? Thank you!

A: Try this code, it results in a format closest to what you require:
import math
epsilon= 0.00000000001

def mysqrt(a):
  x= a/2
  while True:
      y = (x + a/x) / 2
      if abs(y-x) < epsilon:
        return y
        break
      x = y

def right_digit(n):
  '''Takes a floating point number and returns its right
  most digit in 'str' format'''
  trunc= f'{n:.11f}'
  dig= trunc[len(trunc)-1]
  return dig

def test_square_root(n):
  print('a', ' '*1, 'mysqrt(a)', ' '*3, 'math.sqrt(a)', ' diff')
  print('-', ' '*1, '-'*9, ' '*3, '-'*12, ' ' + '-'*4)

  for i in range(9):
    x= i+1

    print(f'{x:0.1f}', end=' ')

    if mysqrt(x)- int(mysqrt(x)) < 0.001:
      y=1
    elif right_digit(mysqrt(x)) == '0':
      y=10
    else:
      y=11

    print(f'{mysqrt(x):<13.{y}f}', end=' ')
    print(f'{mysqrt(x):<13.{y}f}', end=' ')

    diff= math.sqrt(x) - mysqrt(x)
    print(f'{diff:.12g}')

test_square_root(9)

The resulting table looks something like this:
a   mysqrt(a)     math.sqrt(a)  diff
-   ---------     ------------  ----
1.0 1.0           1.0           0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0
4.0 2.0           2.0           0
5.0 2.2360679775  2.2360679775  0
6.0 2.44948974278 2.44948974278 0
7.0 2.64575131106 2.64575131106 0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0           3.0           0

I have used f-strings to format this table but you can also use .format() method. There are 2 special cases that you have to keep in mind:

*

*Any number that is a perfect square must result in a single decimal point in its square root (applicable for 1,4,9)

*The leftmost decimal digit can't be zero (applicable for 5)

You can see in the code above that there are 3 conditional statements included in test_square_root function to take care of these issues.

A: Adjust the print statement to print each element to a fixed number of decimal places using {0:.8f} {0:.10f} and {0:.4f} respectively, or your desired coloumn width.

A: You can use the tab \t in the print statement:
print("\t", a, "\t", y, "\t", square_method, "\t" "diff:", diff,)

A: here is my code which looks good:
from decimal import *
import math

def mysquare_root(a):
     x = 1
    while True:
        #print(x)
        y = (x + a/x) / 2
        if x == y:
            break
        x = y
    return (x)

def square_root(a):
    x = math.sqrt(a)
    return x
def difference(a):
    d = square_root(a) - mysquare_root(a)
    return d

# the below function prints the table, but the alignment is not good.
def list_func():
    for a in range(1, 10):
         print(float(a), " " * 20, f"{mysquare_root(a)}", " "*20, f"{square_root(a)}"," "*20,f"{difference(a)}")
list_func()

# by using the below functions ("dec_1, dec_2") we are fixing the decimals after point to
#..........'15' numbers for uniform alignment.
# the 1st function is for square_root which is built in function
# 2nd is for alignment of difference after built_in_ function values.
def dec_1(a):
    d = Decimal(mysquare_root(a))
    #print(d)
    d1 = round(d, 15)
    #print(d1)
    #print(d1)
    return Decimal(d1)

def dec_2(a):
    d = Decimal(square_root(a))
    #print(d)
    d1 = round(d, 15)
    #print(d1)
    return Decimal(d1)

def print_it():
    for a in range(1, 10):
         print(float(a), " " * 20, f"{dec_1(a)}", ' '*9, f"{dec_2(a)}", ' '*9, f"{difference(a)}")

print_it()

here is the solution what i got:
1.0       1.000000000000000           1.000000000000000           0.0
2.0       1.414213562373095           1.414213562373095           2.220446049250313e-16
3.0       1.732050807568877           1.732050807568877           0.0
4.0       2.000000000000000           2.000000000000000           0.0
5.0       2.236067977499790           2.236067977499790           0.0
6.0       2.449489742783178           2.449489742783178           0.0
7.0       2.645751311064591           2.645751311064591           0.0
8.0       2.828427124746190           2.828427124746190           4.440892098500626e-16
9.0       3.000000000000000           3.000000000000000           0.0

A: Here is the perfect solution that I figured out:
from decimal import *
import math
# below function is used to find the square roots of a number using the newton's method(i.e; using formula)
def mysquare_root(a):
    x = 1
    while True:
        y = (x + a/x) / 2
        if x == y:
            break
        x = y
    return x

# below function is used to find the square roots of a number using the built_in function
def square_root(a):
    x = math.sqrt(a)
    return x

# below function gives the difference between thr toe functions above
def difference(a):
    d = square_root(a) - mysquare_root(a)
    return d

# Normally we can print the values as usual by giving selected no. of spaces between one and other values
# but, because of different float values, it is not possible to print uniformly as a table.
# In below function we use the decimal to over come the possibility.

def dec_1(a):

    # this function is to print the values of function 'mysquare_root()' uniformly as a table.
    # in order to access the decimals of a value we use 'Decimal' in_built function and we can round it off.
    d = Decimal(mysquare_root(a))
    #print(d)
    # here we are rounding off the decimal values to '15' after point.
    d1 = round(d, 15)
    #print(d1)
    # if we round off all the values, even perfect square will have '15' zeros after point. we don't want it.
    # so, we are rounding off the perfect square values to '0' decimal values after point
    if d1 - Decimal(mysquare_root(a)) == 0:
        d1 = round(d, 0)
        #print(d1)
        # in order to get one decimal value after point, simply we return a float value
        return float(d1)
    #print(d1)
    # we are return value which is rounded to certain values after point.
    return (d1)
#print(dec_1(2))

# the below function works same as above function, but for in_built method to find square root.
def dec_2(a):
    # This function is working for to print the values of function 'square_root()'
    d = Decimal(square_root(a))
    #print(d)
    d1 = round(d, 15)
    if d1 - Decimal(mysquare_root(a)) == 0:
        d1 = round(d, 0)
        return float(d1)
    #print(d1)
    return Decimal(d1)
#print(dec_2(2))

def print_it():
    # below two print statements arranged as per requirement.
    print("numbers", " "*14, 'mysquare_root', ' '*8, 'square_root', ' '*10, "difference")
    print("-------", " " * 14, '-------------', ' ' * 8, '-----------', ' ' * 10, "----------")
    for a in range(1, 10):
        # here we are going to print square roots 1-9
        # here we are giving the 18 spaces between the one float value to another in table.
        # if there is only 15 decimal values after point, we already covered 14 position after float value, so we will give 4 spaces
        # here to do spacing between values, we just comparing float value and int value to get how much space is needed.

        print(float(a), " " * 18, f'{dec_1(a)}', " "*18 if dec_1(a) == int(dec_1(a)) else " "* 4, f'{dec_2(a)}', " "*18 if dec_1(a) == int(dec_2(a)) else " "* 4, f"{difference(a)}")

print_it()

here is my output
numbers                mysquare_root          square_root            difference
-------                -------------          -----------            ----------
1.0                    1.0                    1.0                    0.0
2.0                    1.414213562373095      1.414213562373095      2.220446049250313e-16
3.0                    1.732050807568877      1.732050807568877      0.0
4.0                    2.0                    2.0                    0.0
5.0                    2.236067977499790      2.236067977499790      0.0
6.0                    2.449489742783178      2.449489742783178      0.0
7.0                    2.645751311064591      2.645751311064591      0.0
8.0                    2.828427124746190      2.828427124746190      4.440892098500626e-16
9.0                    3.0                    3.0                    0.0

I tried to give you the clarity on this code. I hope you will get it.

A: Here is a solution based solely on topics covered in previous chapters of the book.
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Think Python Chapter 7

# exercise 7-1

import math

def mysqrt(a):
    '''calculates square root using Newtons method
    '''
    x = a / 2
    while True:
        y = (x + a / x) / 2
        if x - y < 0.00001:
            break
        x = y
    return y

def diff(a):
    '''calculates difference my function for square root and standard function
    '''
    d = mysqrt(a) - math.sqrt(a)
    return d

def test_mysqrt(a):
    '''prints list of values and differences for
    calculating square root my way and python way
    '''
    print(
        "a", " " * 2,
        "mysqrt(a)", " " * 11,
        "math.sqrt(a)", " " * 8,
        "diff"
        )  # topline
    while a > 1:
        a = a-1
        len_a = 3 - len(str(a))  #calculate extra spaces
        len_my = 20 - len(str(mysqrt(a)))
        len_ma = 20 - len(str(math.sqrt(a)))
        print(
            a, " " * len_a,
            mysqrt(a), " " * len_my,
            math.sqrt(a), " " * len_ma,
            diff(a)
            )
    return

test_mysqrt(10)

Hope this helps.