text:
Q: Is it possible in Azure DevOps Pipelines to wait for enough agents to run the job We are running into the following issue:
We have a job in our pipeline that runs tests. The number of tests need to be distributed over 4 agents to run optimal. It can happen that only one agent is available and the job will start to run all the load on that specific agent, which can then time-out because it takes too long for other agents to become available in time to share in the load.
In essence, if we run with 4 agents, the job will run with optimal efficiency.
My question: is it possible to let a job wait for a specific number of agents to become available before starting the tasks in the job?

A: That`s not possible through out-of-box features.... But you may create a simple PowerShell script that will query your agents statuses: https://learn.microsoft.com/en-us/rest/api/azure/devops/distributedtask/agents/list?view=azure-devops-rest-7.1
and use includeAssignedRequest
GET  https://dev.azure.com/{organization}/_apis/distributedtask/pools/{poolId}/agents?includeAssignedRequest={includeAssignedRequest}&api-version=7.1-preview.1
if you see assignedRequest, your build agent is busy...


text:
Q: I want a simple red line in my nvd3 charts I made a nvd3 chart. I have a problem. I want to draw a simple red line along y axis. Example: x:i y:180. But I do not want to treat as a data, than has value. So as a simple line.
Sourcecode:
  vm.fhrOptions = {
            chart: {
                type: 'lineChart',
                useInteractiveGuideline: true,
                height: 300,
                forceY:([60,200]),

                lineY:([120,180]),
                fitScreen: true,
                margin : {

                    left:70,
                    bottom:0

                },
                transitionDuration: 1000,
                xAxis: xAxisOptions,
                yAxis: {
                    axisLabelDistance:50,

                            lines: {value: 120},

                    color : { pattern:['#1f77b4', '#aec7e8']},
                    axisLabel: 'FHR [pulzus/perc]',
                    tickFormat: function(d){
                        return d===null?'NaN':d3.format('d')(d);
                    },
                    rotateYLabel: -45,
                    showMaxMin: false,
                    domain:([80, 160]),
                    showLegend:true
                }

            }
        };

A: Use the following to draw a single line across your chart, change parameters as necessary and change '#chart svg' to your selector name.
                        d3.select('#chart svg')
                        .append('line')
                        .attr({
                        x1: 500 + chart.xAxis.scale()(0),
                        y1: 35 + chart.yAxis.scale()(10),
                        x2: 57 + chart.xAxis.scale()(3),
                        y2: 35 + chart.yAxis.scale()(10)
                        })
                        .style("stroke", "#FF0000")
                        .style("fill", "#ff0000");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Villager not breeding still Not sure if people are on here, and not sure if it's been answered but my 9 villagers are not breeding they have plenty of crops and food (Some not harvested) and I've traded with them I also have 64+ doors so I don't know why they aren't breeding. The top of my doors are 3 blocks below where the villagers are
Any help appreciated

A: The issue seems to be you have too many doors without sufficient space "in front of the door/inside the house" and "behind the door/outside the house" for each of the doors in the underground area. None of these are really considered a house for villager breeding purposes.
As @fabian indicates, the mechanics of villager breeding is more complicated than placing a sufficient number of doors. What you need to accomplish is to trick minecraft into thinking you have created a village. Only then will the villagers start breeding.
Here is a link that may help you: https://minecraft.gamepedia.com/Villager#Breeding. There are also a number of videos online that will explain how to create a working villager breeder.
(FYI the mechanics of villager breeding changed with different versions of Minecraft, and are likely dependent on which platform you are running on, so if you are reading this in the future, your mileage may vary).

A: Out of personal experience, I'd say the following should help in 2021, as of version 1.16.5:

*

*Build houses (at least 3x3 on the inside).

*

*Put beds in there.

*Building a large house with 3x3 rooms also works.

*Give bread to your villagers, just throw it on the floor next to them, they will pick it up (you want mob griefing turned on for that).

*Have a trade with them. You can farm a lot of emerald selling carrots to most farmers. You can spend it on silly things, villagers tend to sell much better items when they level up.

And that's pretty much it. This should be sufficient for normal gameplay unless you want to build some crazy farm of some sort.

A: If you have composters, then you need those to turn them into farmers to farm.


text:
Q: Globally mocking data using Vue test utils I have a component in Vue which contains an img tag where the value of src is coming from props.
<template>

</template>

Similarly, this img tag is present in many of my components. For mocking it globally, I made a jest.init.js file where my code goes something like this
import VueTestUtils from "@vue/test-utils";

VueTestUtils.config.mocks["img"] =  {src: "rytui"};

But it is not working. How should I do it?

A: some where. You need add setupFiles config in your jest.config.js like this
{
  setupFiles: ["<rootDir>/jest.init.js"],
}


text:
Q: Magento 1.9.1 on option change additional information is not change In Magento 1.9.1 whenever I will change the product option (configuration option) from the dropdown the product price and availability will change but the additional information is not changed.
I want if user change the drop-down then the additional information of that particular product also change.

Can any one tell me why it will not change and how to find the solution of my problem?


text:
Q: When twitter goes down, elements on my site breaks as well. How to prevent this? As we know Twitter.com was down in yesterday(2012/07/26) some period of time. In that time my website home page somewhat unresponsive. The homepage was trying to load the twitter feed and failing, and thus other page elements in my site appears broken, like a jquery slider has trouble loading correctly, because its trying to load the twitter API.
Hove to fix this to homepage  ignore twitter feed if the site notices that it is down, and displaying a short error notice in place of the feed?
I am using following customize twitter widget (got from here) to show latest 2 twitts in Home page.

A: You should delay load your twitter feed. The rest of your page will load right away and if/when twitter goes down it won't block the rest of your page. It's good practice to do this anyway.
See https://dev.twitter.com/discussions/3369 for a discussion with some examples on using jquery to do this.


text:
Q: http4s Received premature EOF error for 2 per of request we are doing performance testing for our application. we are getting org.http4s.InvalidBodyException: Received premature EOF error.
The problem is we are getting only for 1-2 per of requests. The percentage will increase if we will increase rps.
The architecture of Performance application:

The issue can happen in 3 parts:

*

*When we send requests from prod application to Kafka

*In the performance application client who is firing the requests

*Som issue in our application

If someone faces a similar issue, please let me know.

A: we are using some libraries to send requests from the forwarder. After investigation, we found that some requests are truncate in between. When our client read the request from Kafka it reads in bytes so these are incomplete requests and our server thought it will get a new stream but it will never get and the request did not complete. it throws timeout on the client and eof on the server side. I am doing more investigation. I will update if I found something else.


text:
Q: Microsoft Graph subscription notifications not being pushed Been working with subscriptions for the past few months and haven't had issues. Today our service has been down because changes made for Contacts and Events are not issuing a notification to our API. I have resubscribed several times in different environments to no avail. Code base has not changed for the past couple days.
The URL for the POST is: https://graph.microsoft.com/beta/subscriptions
This is the request payload (2018-12-13T14:40:48.321209 PST):
{
:changeType=>"created,updated", :notificationUrl=>"https://da532483.ngrok.io/office365/subscription/notification", :resource=>"/me/calendars/AQMkADAwATY3ZmYAZS1lZmRkAC1lOTZhLTAwAi0wMAoARgAAA6PhSGdMGt9Nkwdvvtt9NrIHAD-_YGH8PpRIvfFpb45sC10AAAIBBgAAAD-_YGH8PpRIvfFpb45sC10AAtZPfToAAAA=/events",
:expirationDateTime=>"2018-12-16T21:10:48+00:00",
:clientState=>"clientState"
}
And the response payload (2018-12-13T14:40:49.339139 PST):
{
"@odata.context":"https://graph.microsoft.com/beta/$metadata#subscriptions/$entity",
"id":"d07de8ab-2c6c-447c-90d1-2b583318c597",
"resource":"/me/calendars/AQMkADAwATY3ZmYAZS1lZmRkAC1lOTZhLTAwAi0wMAoARgAAA6PhSGdMGt9Nkwdvvtt9NrIHAD-_YGH8PpRIvfFpb45sC10AAAIBBgAAAD-_YGH8PpRIvfFpb45sC10AAtZPfToAAAA=/events",
"applicationId":"0e8eebe4-55dc-4bd6-91ac-c13f91bb145d",
"changeType":"created,updated",
"clientState":"clientState",
"notificationUrl":"https://da532483.ngrok.io/office365/subscription/notification",
"expirationDateTime":"2018-12-16T21:10:48Z",
"creatorId":"00067FFEEFDDE96A"
}
Any help would be greatly appreciated.

A: Sorry about the issues you experienced with Microsoft Graph webhook notifications.
Here is what happened:
We experienced a capacity issue that resulted in a delayed deliveries for a subset of notifications. Some subscriptions were affected more than others, with some subscribers seeing a significant drop in notifications delivered. The time period for this issue was between 2AM on 12-12-2018 and 6PM 12-13-2018 (PST).
What we are going to do:
1.We are investigating the root cause and will take steps to prevent this from occurring in the future.
2.We recognize that our outage communications for Graph notifications are lacking. We are working on improving our comms with the goal of pro-actively publishing service degradation info to our customers as soon as we realize they occur.
We appreciate your usage of Graph and our webhook notification framework. Sorry about the trouble!


text:
Q: How to set input value to current day in reflex? I am using reflex-platform with obelisk.
This is my frontend code to get the current date
pb <- getPostBuild
postBuildTime <- performEvent $ pb $> liftIO getCurrentTime
let today = Text.pack . formatTime defaultTimeLocale "%F" <$> postBuildTime

I can confirm that this works by putting
dynText =<< holdDyn "loading" today

which does not even display "loading" for a split second but instead shows "2021-03-26" as expected in the browser (Google Chrome).
However, trying to put the today event into an <input> doesn't work. This is the code:
foo <- inputElement $ def & inputElementConfig_setValue .~ today

The <input> stays blank.
Even weirder: In my actual code the <input> has an initial value via inputElementConfig_initialValue .~ "BAAAR", which doesn't show either. Yet a dynamic text created like
dynText =<< holdDyn "" foo

DOES show "BAAAR" for a split second.

And to calm any paranoia, I tested the inputElementConfig_setValue with a simple button, which worked fine. I.e. I can set the value of <input> by clicking on a button.
So the postBuildTime event works and the inputElementConfig_setValue works, but the combination of the two leaves the <input> blank.
EDIT
Minimal example including instructions on how to run and screenshot of the result:
https://github.com/rubenmoor/reflex-bug-pbtime

A: https://github.com/reflex-frp/reflex-dom/commit/93f0f4bd00e1dc871d193d7d53d5d7f2dbb518af
Looks like this was a bug, that has been fixed in reflex-dom.


text:
Q: Send email with attachment , that attachement will be uploaded in the same FORM where from the mail gets triggered Send email with attachment,that attachement will be uploaded in the same FORM where from the mail gets triggered.
BACKGROUND:
i.e. I have an FORM that will take name, address etc details from a FROM. After filling the details user would be allowed to a browse and upload an attachment. Onclicking the Upload button the file will get uploaded to the server.
After doing all of the above action when the users clicks on SUBMIT button in this FROM, it should trigger a email with all the details entered in  the FORM and With the uploaded file attached in it.
Now, the problem I am facing is : when I click on UPLOAD button, the file is getting uploaed but all the inputs entered gets disappeared.
Any resolution around this will be appreciated.
N.B: We are not using any free ware like for mail functioanlity. Mail is send by a vbscript function.
below is the logic how i/p fields values are getting captured:
ssr_imo = sql_ship_friendly(request.form("ssr_imo"),10)
ssr_ship_name = sql_ship_friendly(request.form("ssr_ship_name"),100)
ssr_ins_nr = sql_ship_friendly(request.form("ssr_ins_nr"),20)
ssr_ins_date = sql_date_friendly(request.form("ssr_ins_date"),30)
port_name = sql_ship_friendly(request.form("port_name"),50)
ssr_port_id = sql_ship_friendly(request.form("ssr_port_id"),20)
opStat = sql_ship_friendly(request.form("opStat"),20)

subEmail = sql_ship_friendly(request.Form("ssr_sub_email"),200)
subName = sql_ship_friendly(request.Form("ssr_sub_name"),70)

ssr_q2 = validate_q_ssr(request.form("ssr_q2"))
ssr_q3 = validate_q_ssr(request.form("ssr_q3"))
debugNote "<b> TEST = </b>" & ssr_q3
ssr_q4 = validate_q_ssr(request.form("ssr_q4"))
ssr_q5 = validate_q_ssr(request.form("ssr_q5"))
ssr_q6 = validate_q_ssr(request.form("ssr_q6"))
ssr_q7 = validate_q_ssr(request.form("ssr_q7"))
ssr_q8 = validate_q_ssr(request.form("ssr_q8"))
ssr_q9 = validate_q_ssr(request.form("ssr_q9"))
ssr_q10 = validate_q_ssr(request.form("ssr_q10"))
ssr_q11 = validate_q_ssr(request.form("ssr_q11"))
ssr_q12 = validate_q_ssr(request.form("ssr_q12"))
ssr_q13 = validate_q_ssr(request.form("ssr_q13"))
ssr_qa = validate_q_ssr(request.form("ssr_qa"))
ssr_qb = validate_q_ssr(request.form("ssr_qb"))

A: Once you change your form enctype to "multipart/form-data" you can no longer retrieve input values with Request or Request.Form, you have to use the method/function that is part of the upload component or script that you are using.
For example:

*

*In Persit's AspUpload you use obj.Form("inputName") In ChestySoft's

*csASPUpload you use obj.Value("inputName")
(In both cases obj is the name of your upload component object instance and inputName is the name of your form element)
Edit: Using the ASP class you are using for uploading you should use Uploader.Form instead of Request.Form to retrieve input values.


text:
Q: Using CMDeviceMotion and CMAttitude to isolate vertical or horizontal acceleration I'm trying to isolate either a vertical or horizontal acceleration component assuming device orientation may be continuously changing.
Prior to having gyroscope data and CMAttitude, this was impossible because we only had the acceleration data. Now that we have both acceleration is userAcceleration and orientation via CMAttitude, it seems it should be possible to adjust the acceleration data by the attitude data in order to isolate a particular absolute direction of acceleration. This is a bit different from using a reference frame because I'm expecting the device orientation to be constantly changing. Think armband, etc... In my case,
I'd like to be able to capture either strictly vertical, or strictly horizontal acceleration values regardless of how the device orientation may be changing. The geometry for this is a little beyond me and I'd appreciate some advice.

A: I'm not familiar with the iOS APIs but I can give the math answer.

*

*Determine the orientation with gyroscope+accelerometer sensor fusion. I hope iOS has an API for that as it's relatively complicated (if not let us know and I will elaborate). This seems to be what you call CMAttitude. The orientation should be expressed as a quaternion or a matrix, it represents the rotation between a fixed reference frame (most probably North-East-Down, but it depends on the API) and the local reference frame attached to your device.

*Take the vector read from the accelerometer (in the local reference frame), and rotate it with the opposite rotation of your orientation. The opposite of a rotation is the quaternion conjugate or the matrix transpose. Rotating a vector is done via quaternion multiplication or matrix multiplication. This gives you the acceleration vector in the fixed reference frame.

*The Z-component of the acceleration in the fixed reference frame is the vertical acceleration. The norm of the XY-components (sqrt(x^2+y^2)) is the horizontal acceleration. Don't forget to subtract the gravity from vertical acceleration. This assumes a North-East-Down reference frame again, but most other fixed reference frames would only require you to swap X,Y,Z appropriately.

The implementation shall be trivial if iOS has the right APIs. If you have the choice prefer quaternions over matrices as the implementation would run faster. Let us know how it goes.

A: I just implemented marcv81 answer.
-(void)isolateHorizontalMotionFromMotionData:(CMDeviceMotino *)newMotion
{
    //Quaternion Conjugation
    CMQuaternion quaternion = newMotion.attitude.quaternion;
    GLKQuaternion original_quaternion = GLKQuaternionMake(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
    GLKQuaternion conjugated_quaternion = GLKQuaternionConjugate(original_quaternion);

    //Rotation of Accelerometer vector with quanternion
    GLKVector3 acceleromationVector = GLKVector3Make(newMotion.userAcceleration.x, newMotion.userAcceleration.y, newMotion.userAcceleration.z);

    GLKVector3 accelerometionVector_toReferenceFrame = GLKQuaternionRotateVector3(conjugated_quaternion, acceleromationVector);

    //Horizontal Acceleration
    float horizontalAcceleration = sqrtf(powf(accelerometionVector_toReferenceFrame.x,2)+powf(accelerometionVector_toReferenceFrame.y,2));
}


text:
Q: How to count the battery cycles using rain flow counting using python I have SOC (state of charge of a battery) when SOC 1st half cycle (0 to 100%) and 2nd half cycle (100% to 0) considering as full cycle see this figure

in my data there is no full cycles present there is half cycles and quarter cycles are there how to count the battery full cycles with data here is my SOC data attached google spread sheet https://docs.google.com/spreadsheets/d/126sV3E5EuqCEdrtWIWEPhUJ8-2zPHPTyJhY0WWIIoNQ/edit?usp=sharing
My script:
import rainflow
list_x=list(df["SOC"])
len(list_x)
from scipy.interpolate import splrep, splev
fig= plt.figure(figsize=(19,6))
bspl = splrep(t,list_x,s=130000)
bspl_y = splev(t,bspl)
plt.plot(t,list_x)
plt.plot(t,bspl_y)
rainflow.count_cycles(bspl_y)

is not able to count the cycles from above algorithm. Is there any to solve the problem like this? Thanks in regards

A: To find the peaks, you can use the find_peaks function from SciPy insted of rainflow. For further details, take a look at the docs.
Here is the code:
import numpy as np
from matplotlib import pyplot as plt
from scipy.signal import find_peaks

data = np.loadtxt("SOC data - Sheet1.csv")

upper_peaks, _ = find_peaks(data, distance=500)
lower_peaks, _ = find_peaks(-data, distance=500)

plt.plot(data)
plt.plot(upper_peaks, data[upper_peaks], "x", c="red")
plt.plot(lower_peaks, data[lower_peaks], "x", c="red")
plt.show()

The upper_peaks and lower_peaks arrays consist of the peak indices.

EDIT
Regarding the rainflow library, all the details are provided in the documentation:

Full information about each cycle, including mean value, can be obtained using the extract_cycles function

So, for instance:
data = np.loadtxt("SOC data - Sheet1.csv")
t = np.arange(len(data))
spline = splrep(t, data, s=1.3e5)
data_approx = splev(t, spline)

for rng, mean, count, i_start, i_end in rainflow.extract_cycles(data_approx):
    print(rng, mean, count, i_start, i_end)

The output is the following:
17.65289793762279 54.10071414477933 0.5 0 443
25.807399155539528 58.177964753737704 0.5 443 836
27.120471015563403 57.52142882372577 0.5 836 1224
26.171554867156964 75.25703620717142 1.0 1763 2020
0.15602752160933164 61.70248949691576 1.0 2308 2346
53.98760289880129 70.95499476534471 0.5 1224 1388
26.087835226468783 59.921344374733856 1.0 3545 3860
39.56063119775213 65.70767718686292 1.0 2650 3166
54.215085367144695 70.84125353117301 0.5 1388 2516
45.21289541377841 66.34015855448988 0.5 2516 4002
30.237861475461948 73.8276755236481 0.5 4002 4477
2.421086187342951 59.9192878795886 0.5 4477 4551


text:
Q: Button on click save objects to database So I have an event that is when you click a button I want to send an int, string, datetime and bool to my database.
Right now it will get the input from my webform for the "Company" and the "DayNumber". I want to get the value of my CheckBox01 as the boolean for WeatherRain and the input from the Date. You should be able to choose the date not just take it from "now".
I don't know what would be the best way to get this done, I do have around 100 different fields to get user input from.
protected void btnTryck_Click(object sender, EventArgs e)
{
    Dagbok bok = DagbokFactory.CreateNew();

    bok.Company = String.Format(TextBox1.Text);
    bok.DayNumber = Convert.ToInt32(TextBox19.Text);
    bok.WeatherRain = false;
    bok.Date = DateTime.Now;
}

A: In order to get the boolean from your CheckBox01 use its Checked property.
bok.WeatherRain = CheckBox01.Checked;

As for the date problem, I'd suggest using a DateTimePicker control to let the user select the date and get its value with the Value property.

A: Use Checkbox's checked property for this as shown below:
protected void btnTryck_Click(object sender, EventArgs e)
{
    Dagbok bok = DagbokFactory.CreateNew();

    bok.Company = String.Format(TextBox1.Text);
    bok.DayNumber = Convert.ToInt32(TextBox19.Text);
    bok.WeatherRain = CheckBox01.Checked;
    bok.Date = DateTime.Now;
}


text:
Q: What is the canonicity of Lego Star Wars (TV Episodes)? There was a series of Lego Star Wars episodes that aired on Cartoon Network a few years ago - "The Padawan Menace", "The Empire Strikes Out", and "The Yoda Chronicles".
While these episodes are indeed full of the classic Lego Star Wars humor (Yoda did not likely sit on Mace's lap and say "An awkward, this moment is"), does the larger theme of events have any place in Star Wars canon?

A: The Lego Star Wars series is treated as a licensed property and as such, totally non-canon.
Although it and the Family Guy specials can be found on the official Star Wars site, it is important to stress that the studio does not consider it in any way canonical, indeed there are multiple instances (Yoda meets the droids before ESB, for example) that flatly contradict the events of the films.
Michael Price, senior writer for all six of the recent animated features stated this in an interview for Club Jade;

Michael: That is actually incredibly freeing — that and the understanding that these LEGO Star Wars shows are most definitely NOT
  CANON.  So we were free to make up an imaginary back story for Han
  Solo in The Padawan Menace and, in this show, invent entire events
  that never took place – including the kind of awkward and tense
  reunion (or, I guess, first ever meeting) of Darth Vader and his
  "step-brother" Darth Maul.   And the fact that both LEGO and Lucasfilm
  have been supportive of my narrative sidetracks, the mixing and
  matching characters and places from the various films, and our
  satirical swipes at some of the Star Wars sacred cows just has made
  the whole experience very fun.

A: I would guess that these fall under parody, much like the Family Guy parodies do (Blue Harvest, etc.)


text:
Q: Append to sub-directory inside squashfs file Suppose we have filesystem.squashfs,
we can append to it by:
mksquashfs somefile filesystem.squashfs

which appends somefile to root of squashfs file. appending directory:
mksquashfs somedir/ filesystem.squashfs

would append files and directories inside somedir/ to the root of squashfs file. and if a directory or file exist in the tree of squashfs then mksquashfs would rename new files, not changing old files and directories. well it make sense the phrase of "append".
I'm aware of unsquashfs which decompress the squashfs, but I'm curious if perhaps there is a way to add a new file or directory to existing sub-directory inside squashfs tree without decompressing?

A: Of course ;it is possible to append directory or file to a squashfs_file.
One has to understand the way mksquashfs works :
 Roughly speaking it is incrementally adding compression blocks of data in similar way as growisofs writes to dvd ; and at the end update the TOC ,kind of table contents of the image.
 You cannot "clear" the old directory of course, because incremental
writing only cares about future and not the past !!!!
But there is a very simple way of modifying a squashfs file without unsquashfs  the whole image ( which could take a lot of space on ram or storage device ... think of dvd_iso 3-5 GB image ! ).
  The guiding idea works like this :
1 mount  squashfs_file /mnt ( mounting is far less using storage than unsquashfs )
2  Re build squashfs_file by excluding the directory to modify then append the new directory we want.
Details ex:

*

*cp /mnt/specific_dir $home  ##modify $home/specific_dir as needed

*mksquashfs /mnt new_squashfs_file -wildcards -e specific_dir

*mksquashfs $home/specific_dir new_squashfs_file -keep-as-directory

*umount /mnt  # cleanup
of course all other options for mksquashfs  can be added as ususal (block size;compression scheme ....-b 1048576 -comp xz  ....)
The example show one directory modification for clarification purpose ;
but on a rootfs you can exclude etc usr ....then append the modified etc usr in 2nd line append mechanism .
This is the way to go if you need to remaster a whole livecd ubuntu on a
4GB ram "windows10 laptop" without any touching on ntfs original partition .
HopeThatHelp, wangji.

A: When trying something as to remaster a live-CD, the reproducing and excluding of folders can only go so far (in my case, I had to touch /etc, /lib and /usr, which amounts almost to unpacking all).
BUT, using the idea of recompressing without uncompressing, and adding to that the beauty of overlayfs, I came eventually up with the following:
SQFS=/path/to/my.sqfs
ADD=/path/to/additional/files/

mkdir /tmp/lower /tmp/upper /tmp/work /tmp/joined
mount $SQFS /tmp/lower
mount -t overlay none -olowerdir=/tmp/lower,upperdir=/tmp/upper,workdir=/tmp/work  /tmp/joined
rsync -a $ADD /tmp/joined
mksquashfs /tmp/joined ${SQFS}_new -comp xz -b 1M -noappend
umount /tmp/joined /tmp/lower
rm -rf /tmp/lower /tmp/upper /tmp/work /tmp/joined
mv ${SQFS}_new $SQFS

It still needs to create a new SQFS, but nothing of the old SQFS needs to be unpacked, and the overlay takes care of new files in old directories, etc.
P.S. I had hoped, it would also be faster than uncompressing the SQFS first and recompressing, but that isn't the case. After all, it still needs to read through the entire old SQFS in order to create the new one.


text:
Q: oracle.jdbc.ReadTimeout and Socket read timed out Sometimes I'm getting the below error on my application running on jboss 7 with DBCP .
I would like to understand : does it means oracle.jdbc.ReadTimeout is configure on my application or not ? how can I check what is oracle.jdbc.ReadTimeout value ?
Caused by: oracle.net.ns.NetException: Socket read timed out
            at oracle.net.ns.Packet.receive(Packet.java:320)
            at oracle.net.ns.DataPacket.receive(DataPacket.java:103)
            at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:230)
            at oracle.net.ns.NetInputStream.read(NetInputStream.java:175)
            at oracle.net.ns.NetInputStream.read(NetInputStream.java:100)
            at oracle.net.ns.NetInputStream.read(NetInputStream.java:85)
            at oracle.jdbc.driver.T4CSocketInputStreamWrapper.readNextPacket(T4CSocketInputStreamWrapper.java:122)
            at oracle.jdbc.driver.T4CSocketInputStreamWrapper.read(T4CSocketInputStreamWrapper.java:78)
            at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1179)
            at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1155)
            at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:279)
            at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:186)
            at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:521)

A: The answer to your first question is yes. If you're seeing this exception, then the read timeout property must be set. By default there is no read timeout and so you would never see this exception.
The answer to your second question is 'it depends'. The read timeout can be set as a system property with -D in the command line. It can also be set through a DataSource property. Try to grep for oracle.jdbc.ReadTimeout in your scripts.


text:
Q: moving platform with gameplay kit Creating a 2d game, and want to add moving platforms where I can control the pattern and rotation of the platform.
Example:

I want this platform to move in a clockwise motion, also when it reaches the top and bottom I want it to rotate accordingly as if it is facing the direction it is going (so the platform would essentially rotate 180 degrees as it arches at the top and bottom).
I can't use SKActions because I need the physics to work properly.
My idea is that I can use an Agent with behaviors and goals to do this. Not sure if I will need path finding as well.
I'm researching how to use these features, but the documentation and lack of tutorials is hard to decipher. I'm hoping someone could save my some time of trial and error by providing an example of how this would work.
Thanks in advance!

A: Using SKActions or adjusting the position manually will be sucky to get working the way you want, BUT it's always worth a shot to give it a go, since it would take 2 minutes to mock it up and see...
I'd suggest doing something like a Path class that sends velocity commands to the platform every frame ...
Actually, this could be a good exercise in learning the state machine..

MOVE RIGHT STATE: if X position > starting position X + 200, enter state "move down"
MOVE DOWN STATE: if Y position < starting position Y - 200, enter state "move left"
MOVE LEFT STATE: if X position < starting position X, enter state "move up"
MOVE UP STATE: if Y position > starting position Y, enter state "move right"

.. there are ways you could figure out to give it more curvature instead of just straight angle (when changing direction)
Otherwise you would have to translate that into a class / struct / component and give each platform it's own instance of it.
///
Another option is to take the physics out of the equation, and create a playerIsOnPlatform property... then you manually adjust the position of the player each frame... (or maybe a SKConstraint)
This would then require more code on jumping and such, and turns things to spaghetti pretty quickly (last time I tried it)
But, I was able to successfully clone this, using proper hit detection going that route:
https://www.youtube.com/watch?v=cnhlFZeIR7Q
UPDATE:
Here is a working project:
https://github.com/fluidityt/exo2/tree/master
Boilerplate swift stuff:
import SpriteKit
import GameplayKit

// Workaround to not having any references to the scene off top my head..
// Simply add `gScene = self` in your didMoveToViews... or add a base scene and `super.didMoveToView()`
var gScene = GameScene()

class GameScene: SKScene {

  override func didMove(to view: SKView) {
    gScene = self
  }

  var entities = [GKEntity]()
  var graphs = [String : GKGraph]()

  private var lastUpdateTime : TimeInterval = 0

  func gkUpdate(_ currentTime: TimeInterval) -> TimeInterval {
    if (self.lastUpdateTime == 0) {
      self.lastUpdateTime = currentTime
    }

    let dt = currentTime - self.lastUpdateTime

    for entity in self.entities {
      entity.update(deltaTime: dt)
    }

    return currentTime
  }

  override func update(_ currentTime: TimeInterval) {
    self.lastUpdateTime = gkUpdate(currentTime)
  }
}

Here is the very basic component:
class Platforms_BoxPathComponent: GKComponent {

  private enum MovingDirection: String { case up, down, left, right }

  private var node: SKSpriteNode!

  private var state: MovingDirection = .right

  private lazy var startingPos: CGPoint = { self.node.position }()

  @GKInspectable var startingDirection: String = "down"
  @GKInspectable var uniqueName: String = "platform"
  @GKInspectable var xPathSize: CGFloat = 400
  @GKInspectable var yPathSize: CGFloat = 400

  // Moves in clockwise:
  private var isTooFarRight: Bool { return self.node.position.x > (self.startingPos.x + self.xPathSize) }
  private var isTooFarDown:  Bool { return self.node.position.y < (self.startingPos.y - self.yPathSize) }
  private var isTooFarLeft:  Bool { return self.node.position.x < self.startingPos.x }
  private var isTooFarUp:    Bool { return self.node.position.y > self.startingPos.y }

  override func didAddToEntity() {
    print("adding component")
    // can't add node here because nodes aren't part of scene yet :(
    // possibly do a thread?
  }

  override func update(deltaTime seconds: TimeInterval) {
    if node == nil {
      node = gScene.childNode(withName: uniqueName) as! SKSpriteNode

      // for some reason this is glitching out and needed to be redeclared..
      // showing 0 despite clearly not being 0, both here and in the SKS editor:
      xPathSize = 300
    }

    let amount: CGFloat = 2 // Amount to move platform (could also be for for velocity)

    // Moves in clockwise:
    switch state {

    case .up:
      if isTooFarUp {
        state = .right
        fallthrough
      } else { node.position.y += amount }

    case .right:
      if isTooFarRight {
        state = .down
        fallthrough
      } else { node.position.x += amount }

    case .down:
      if isTooFarDown {
        state = .left
        fallthrough
      } else { node.position.y -= amount }

    case .left:
      if isTooFarLeft {
        state = .up
        fallthrough
      } else { node.position.x -= amount }

    default:
      print("this is not really a default, just a restarting of the loop :)")
      node.position.y += amount
    }
  }
}

And here is what you do in the sks editor:


text:
Q: Is it possible to see only community wiki questions (as if it were a tag?) Hi! I'm wondering, is it somehow possible to filter to only view community wiki questions, as if community-wiki were a tag? Thanks!

A: This is possible using the search:

wiki:1 views:0

(the "views:0" part is to make sure that we're only searching questions, not answers)


text:
Q: Can logstash extract log saving in oracle? My application use oralce as DB server, and all logs of the application store in oracle too.
I install logstash in my oracle server and config as shipper.
How can I config logstash to extract logs in oralce? Is there any plugin for that?

A: So far, there is no any input plugin for oracle. You can write a program to query out the logs and then save to a file. Then you use logstash input file to import the logs to logstash.
For example, you can write Java program with oracle api to get the logs


text:
Q: is missing in props validation react/prop-types
*

*i am new to js.

*fixed other lint errors not able to fix only props lint errors

*i am getting a below lint error, googled for the error not able to figure whats the problem.
17:20  error    'playerLaughing' is missing in props validation     react/prop-types

*provding the code below

*can you guys tell me how to fix it

C:\workspace\sports-dia-dashboard\src\components\sample-player\player-section.jsx
  17:20  error    'playerLaughing' is missing in props validation     react/prop-types
  17:40  error    'id' is missing in props validation           react/prop-types
  23:9   warning  Unexpected var, use let or const instead      no-var
  23:53  error    'jumping' is missing in props validation     react/prop-types
  28:32  warning  There should be no space before '='           react/jsx-equals-spacing
  28:32  warning  There should be no space after '='            react/jsx-equals-spacing
  30:37  error    'flying' is missing in props validation        react/prop-types
  33:21  warning  Empty components are self-closing             react/self-closing-comp
  44:3   error    Expected indentation of 4 spaces but found 2  indent

import React from 'react';

class Swimming extends React.Component {
    constructor(props) {
        super(props);
        this.playerLaughing = this.playerLaughing.bind(this);
    }

    playerLaughing() {
          //console.log("playerLaughing");
         // debugger;
        this.props.playerLaughing(this.props.id);
    }

    render() {
          //console.log("render");
          //console.log("accordion / the ExpandCollapse Section component");
        var className = 'player-section' + (this.props.jumping ? ' jumping' : '');

        return (

                        {this.props.flying}

                    {this.props.children}

        );

  }

}

export default Swimming;

A: You should add propTypes to your component:
For example:
// this goes outside the class deceleration
Swimming.propTypes = {
    playerLaughing: PropTypes.func,
    jumping: PropTypes.bool,
    //... other props you will use in this component
};

If you want it inside the class deceleration you can use a static class field like so:
// this goes inside the class deceleration
static propTypes = {
        playerLaughing: PropTypes.func,
        jumping: PropTypes.bool,
        //... other props you will use in this component
    };
};

You should install and import PropTypes.  see the Docs
npm install --save prop-types
import PropTypes from 'prop-types'; // ES6
var PropTypes = require('prop-types'); // ES5 with npm

A: You need to set the static property 'propTypes' on the component to satisfy this lint error.
Here is some info about React's PropTypes: React Docs
You would add a section similar to this:
import React from 'react';
import PropTypes from 'prop-types';

class Swimming extends React.Component {
 static propTypes = {
   jumping: PropTypes.bool,
   playerLaughing: PropTypes.func
 };
 constructor(props) {
 ...
}

You'll need to install the 'prop-types' npm package.


text:
Q: May I call a virtual function to initialize a base-class sub-object? I know that virtual functions should not be called either directly or indirectly in a constructor, but this code runs fine.
Is what I have here safe?
#include <iostream>
#include <string>

struct A {
    A (const std::string& name) {std::cout << name << std::endl;}
    virtual std::string tag() const = 0;
};

struct B: A {
    B() : A (tag()) {}
    virtual std::string tag() const override {return "B";}
};

int main() {
    B b; // Output gives "B\n"
}

If not, would the following (based on a comment) be a correct workaround?
// Replacement for class B:

struct B: A {
    B() : A (name()) {}
    virtual std::string tag() const override {return name();}
private:
    static std::string name() {return "B";}  // use static function
};

A: Invoking virtual members in the constructor and/or destructor is generally ok.
It's a different game in the ctor initializer though, before all bases are initialized:

12.6.2 Initializing bases and members [class.base.init]
[...]
  14 Member functions (including virtual member functions, 10.3) can be called for an object under construction.
  Similarly, an object under construction can be the operand of the typeid operator (5.2.8) or of a dynamic_cast (5.2.7). However, if these operations are performed in a ctor-initializer (or in a function called directly or indirectly from a ctor-initializer) before all the mem-initializers for base classes have completed, the result of the operation is undefined.


text:
Q: How to select variant column with one csv row as multiple columns in Snowflake? I got a table TABVAR in snowflake which has column Var_Col which is VARIANT type. I load there each row from some csv, so values are like 'val1;val2;val3'.
I know that i can query it as columns directly from csv, but i have to do it other way.
The question is how to query Var_Col to obtain something like:
select firstValFromVar_Col, secondValFromVar_Col, thirdValFromVar_Col
from  TABVAR

I mean the query like above and result be like:
Col1 Col2 Col3
val1 val2 val3

Output of Select * from TABVAR :
Var_Col
val1;val2;val3

A: It can be done with:
select   split_part("Var_Col", ';',  1)
, split_part("Var_Col", ';',  2)
, split_part("Var_Col", ';',  3)
from "TABVAR"


text:
Q: Insert into Parquet file generates 512 MB files. How to generate 1 GB file? I am testing Parquet file format and inserting data into Parquet file using Impala external table.
Following is the parameter set that may affect the Parquet file size:
NUM_NODES: 1
PARQUET_COMPRESSION_CODEC: none
PARQUET_FILE_SIZE: 1073741824

I am using following insert statement to write into Parquet file.
INSERT INTO TABLE parquet_test.parquetTable
PARTITION (pkey=X)
SELECT col1, col2, col3 FROM map_impala_poc.textTable where col1%100=X;

I want to generate file size of approximately 1 GB and partitioned data accordingly so that each partition has little less than 1 GB of data in Parquet format. But, this insert operation doesn't generate single file of more than 512 MB. It writes 512 MB of data into one file and then creates another file and writes rest of the data to another file. What can be done to write all the data into single file?

A: try setting parquet size in the same session you are executing the query
 set PARQUET_FILE_SIZE=1g;
 INSERT INTO TABLE parquet_test.parquetTable ...


text:
Q: Codeigniter Sessions Checking from a header view file I am fairly new and just started to use Codeigniter, and have come across some confusion regarding sessions.
What I want to achieve is, like in regular php, I want to check if a user is logged in by using a header include file which checks the session data. I dont want to check/write that checking code in every controller while passing data to the view file.
Can someone please show me how it can be done?
Ex. I don't want to do the following in every controller:
//Controller:
if($this->session->userdata('loggedin'){
$data['loggedin'] = $this->session->userdata('loggedin');
}
//I dont want to check the above on every function in every controller
$this->load->view('some_view_file', $data);

//some_view_file
if(isset($loggedin)){
echo "You are logged in!";
}
else
{
echo "Please log in!";
}

Instead, I want something to like the following:
//some view file
if(isset($loggedin))
{
echo "your logged in";
}
else
{
echo "please log in";
}

And also, how can I use native php sessions instead of CI Sessions. Any help will be much appreciated. Thanks.

A: Firstly, theres no reason you can't just write something like this in your view:
<? echo ($this->session->userdata('loggedin')) ? "Logged In": "Not Logged In"; ?>

Then your controllers don't need any of that code.
However if the check is more complex or something, then theres a few places you can do it.
1) In the constructor of a custom controller: create a new file application/core/MY_Controller.php, and override the constructor with something like:
class MY_Controller extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        if($this->session->userdata("loggedin")) {
            // do something
        }
    }
}

then make all your controllers extend MY_Controller.
2) Or in a post_controller_constructor hook. http://codeigniter.com/user_guide/general/hooks.html (this is more transparent, and probably easier if you have tons of controllers already)
You can use native sessions with this:
http://codeigniter.com/wiki/Native_session/

A: I think using a construct on your controller would be the smartest approach.
I also recommend encrypting your session cookie.

class Blog extends CI_Controller {

       public function __construct()
       {
            parent::__construct();
            //always check if session userdata value "logged_in" is not true
            if(!$this->session->userdata("logged_in"))
            {
                 redirect('login');
            }

       }
}


text:
Q: Data type in RDD appears to be java.lang.Long, but map function gives a type mismatch error This confusion is probably due to my Scala ignorance.
scala> spark.range(2).toDF("number").rdd.map(x => x(0).getClass).collect
res155: Array[Class[_]] = Array(class java.lang.Long, class java.lang.Long)

Apparently the types are Longs. Unfortunately, when I try to map a function, map() seems to want a String:
scala> spark.range(2).toDF("number").rdd.map(x => x(0)+22).collect
<console>:25: error: type mismatch;
 found   : Int(22)
 required: String
   spark.range(2).toDF("number").rdd.map(x => x(0)+22).collect
                                                   ^

What is going on? A colleague pointed me to the Spark documentation, where we have,

... in Spark 2.0, DataFrames are just Dataset of Rows in Scala and Java API. These operations are also referred as "untyped transformations" in contrast to "typed transformations" come with strongly typed Scala/Java Datasets.

This doesn't seem to be related to the problem, however, because the result of getClass() appears to be java.lang.Long.

A: The problem is that accessing elements in a Row (the x in the map function) using only x(0) will result in Any as data type. Instead, tell Spark that it is a Long when accessing the value using getAs:
spark.range(2).toDF("number").rdd.map(x => x.getAs[Long](0)).collect

You can use the column name instead of the index to make it clearer:
spark.range(2).toDF("number").rdd.map(x => x.getAs[Long]("number")).collect

Even better would be to convert the dataframe to a dataset and not an rdd:
spark.range(2).toDF("number").as[Long].collect

A:
map() seems to want a String:

map doesn't want a String, + does. As Ramesh's answer says, x(0) has type Any. While you can't add a number to Any, you can add a String. There have been requests to remove this conversion over time because it's quite rarely actually desired, but it's still there.


text:
Q: How can I remove legends with 0 value Highcharts? I want to remove from the legend list the series that have 0 value....I've tried
function(chart) {
  $.each(chart.series, function(i, series) {
      if (series.data[0].y === 0) {
        series.hide();
      }
})};

but no luck, it hides all of the legend items...any help I would really appreciate...thanks!!

A: You can iterate by each serie / points, check if is 0 value and remove legend group in SVG.
http://jsfiddle.net/hz2PN/
var flag = false;
        $.each(chart.series,function(i,serie){

            $.each(serie.data,function(j,data){

                if(data.y === 0){
                    flag=true;

                }
            });

            if(flag)
               serie.legendGroup.destroy();

        });


text:
Q: Has there been an instance where the Tricorder was used to heal? I have been reading about the Tricorder on Memory Alpha:

A tricorder was a multifunction hand-held device useful for data sensing, analysis, and recording, with many specialized abilities which made it an asset to crews aboard starships and space stations as well as on away missions. [...]
Tricorders were often useful for recording entries in personal or official logs.

Also,

In the final draft script of TOS: "Miri", a tricorder was used by Spock to ascertain that McCoy wasn't dead.

I remember seeing it being used to treat an injury (it was used to heal a fracture temporarily, but I could be mistaken); though it has been a long time since I have watched Star Trek. It was definitely from Star Trek - The Next Generation.
Could I have been mistaken? Maybe it was in another sci-fi movie, like After Earth, perhaps?

A: Starfleet medical personnel regularly used medical tricorders to assess injuries and illness, often with a detachable hand scanner that was run over the affected area, but this was only used for diagnosis, not treatment. I do not know of any examples from Star Trek of a tricorder being used to actively treat injuries. You may be thinking of another franchise or remembering a different device being used.


text:
Q: How does an LRU cache fit into the CAP theorem? I was pondering this question today. An LRU cache in the context of a database in a web app helps ensure Availability with fast data lookups that do not rely on continually accessing the database.
However, how does an LRU cache in practice stay fresh? As I understand it, one cannot garuntee Consistency along with Availibility.  How is a frequently used item, which therefore does not expire from the LRU cache, handle modification? Is this an example where in a system that needs C over A, an LRU cache is not a good choice?

A: First of all, a cache too small to hold all the data (where an eviction might happen and the LRU part is relevant) is not a good example for the CAP theorem, because even without looking at consistency, it can't even deliver partition tolerance and availability at the same time. If the data the client asks for is not in the cache, and a network partition prevents the cache from getting the data from the primary database in time, then it simply can't give the client any answer on time.
If we only talk about data actually in the cache, we might somewhat awkwardly apply the CAP-theorem only to that data. Then it depends on how exactly that cache is used.
A lot of caching happens on the same machine that also has the authoritative data. For example, your database management system (say PostgreSql or whatever) probably caches lots of data in RAM and answers queries from there rather than from the persistent data on disk. Even then cache invalidation is a hairy problem. Basically even without a network you either are OK with sometimes using outdated information (basically sacrificing consistency) or the caching system needs to know about data changes and act on that and that can get very complicated. Still, the CAP theorem simply doesn't apply, because there is no distribution. Or if you want to look at it very pedantically (not the usual way of putting it) the bus the various parts of one computer use to communicate is not partition tolerant (the third leg of the CAP theorem). Put more simply: If the parts of your computer can't talk to one another the computer will crash.
So CAP-wise the interesting case is having the primary database and the cache on separate machines connected by an unreliable network. In that case there are two basic possibilities: (1) The caching server might answer requests without asking the primary database if its data is still valid, or (2) it might check with the primary database on every request. (1) means consistency is sacrificed. If its (2), there is a problem the cache's design must deal with: What should the cache tell the client if it doesn't get the primary database's answer on time (because of a partition, that is some networking problem)? In that case there are basically only two possibilities: It might still respond with the cached data, taking the risk that it might have become invalid. This is sacrificing consistency. Or it may tell the client it can't answer right now. That is sacrificing availability.
So in summary

*

*If everything happens on one machine the CAP theorem doesn't apply

*If the data and the cache are connected by an unreliable network, that is not a good example of the CAP theorem, because you don't even get A&P even without C.

*Still, the CAP theorem means you'll have to sacrifice C or even more of A&P than the part a cache won't deliver in the first place.

*What exactly you end up sacrificing depends on how exactly the cache is used.


text:
Q: Determining the cause of "class file for oracle.javatools.annotations.Exported not found" error (trying to use Glide to display SVGs) I am using the Glide samples to add SVG support to my application (Glide uses AndroidSVG for parsing the SVG).
See

*

*https://github.com/bumptech/glide/tree/v4.10.0/samples/svg

*https://bigbadaboom.github.io/androidsvg/
I took Glide's sample and put it in a basic application and it works perfectly.
I then added the same changes into my existing product application which is quite large and now my application fails to compile.  The error is
error: cannot access Exported
  class file for oracle.javatools.annotations.Exported not found
cannot access Exported

I have no additional information from IntelliJ about this issue.  I'm thinking it must be a conflicting dependency issue but I can not figure how to find out what.
I have searched the internet and StackOverflow and I can not see anything similar to this query.
Has anyone else seen an issue like this?
The working sample app's app build.gradle deps
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation "androidx.fragment:fragment:1.5.4"

// SVG SUPPORT
implementation 'com.caverock:androidsvg:1.2.1'

// GLIDE
implementation 'com.github.bumptech.glide:glide:4.10.0'
implementation 'com.github.bumptech.glide:annotations:4.10.0'
// Skip this if you don't want to use integration libraries or configure Glide.
annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'

My product application's dependencies
implementation group: 'commons-lang', name: 'commons-lang', version: '2.6'
// force specific version of dependency in 'constraints'
constraints {
    implementation('commons-io:commons-io:2.4') {
        because 'Must be 2.4 as later versions of commons-io break login on API < 27'
    }
}

implementation 'com.android.volley:volley:1.2.1'
implementation 'commons-fileupload:commons-fileupload:1.4'
implementation 'org.apache.httpcomponents:httpmime:4.3.6'

implementation "com.google.android.exoplayer:exoplayer-ui:$exoplayer_version"
implementation "com.google.android.exoplayer:exoplayer-dash:$exoplayer_version"
implementation "com.google.android.exoplayer:exoplayer-core:$exoplayer_version"
implementation "com.google.android.exoplayer:exoplayer-smoothstreaming:$exoplayer_version"
implementation "com.google.android.exoplayer:extension-okhttp:$exoplayer_version"

implementation 'androidx.webkit:webkit:1.4.0'

implementation 'androidx.legacy:legacy-support-v13:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.1.0'
implementation 'androidx.annotation:annotation:1.3.0'
implementation 'androidx.recyclerview:recyclerview:1.2.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.appcompat:appcompat:1.4.2'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'

implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.google.guava:guava:29.0-android'
implementation "com.squareup.okhttp3:okhttp-urlconnection:$okhttp_version"
implementation "com.squareup.okhttp3:okhttp:$okhttp_version"
implementation 'com.squareup:otto:1.3.8'
implementation 'com.squareup.okio:okio:2.10.0'
implementation 'com.jakewharton:disklrucache:2.0.2'
implementation 'com.google.firebase:firebase-analytics:18.0.3'
implementation 'com.google.firebase:firebase-config:20.0.4'
implementation 'com.google.firebase:firebase-messaging:21.1.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'androidx.lifecycle:lifecycle-process:2.4.1'
implementation 'androidx.lifecycle:lifecycle-runtime:2.4.1'
implementation 'androidx.lifecycle:lifecycle-common-java8:2.4.1'

implementation 'com.github.bumptech.glide:glide:4.10.0'
implementation 'com.github.bumptech.glide:annotations:4.10.0'
// The following is needed as we want to configure Glide to make use of SVGAndroid
annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'
// support for SVGs (https://bigbadaboom.github.io/androidsvg/)
implementation 'com.caverock:androidsvg-aar:1.3'

implementation 'org.apache.commons:commons-lang3:3.10'
implementation "io.reactivex.rxjava3:rxandroid:3.0.0"
implementation 'net.openid:appauth:0.11.1'

// and some additional deps of jars from our own code base


text:
Q: Windows Backup failure creating system image On a UEFI W10 computer Windows Backup fails to create a system image, there's some VSS (Volume Shadow Service) errors logged with detail "the requested system device could not be found".
I can't understand what device it's taking about.
Here's the system log export:
https://drive.google.com/file/d/1B4qnFjiSSB9OkPObfj1tmUFVuIlDJDbp/view?usp=drivesdk
Maybe it fails to access the system reserved EFI partition, there's some solutions for this just for MBR disks, not for GPT.
Any suggestions?
Regards

A: Realistically, you are wasting your time.
Windows Backup is deprecated. Microsoft has stopped its development
and is recommending using third party software for backups.
We are seeing on this site an increasing number of errors with
Windows Backup both in creating the backup and (much more worryingly)
with restoring the data. Several posts on our site bear testimony.
Microsoft has removed the option to use this alongside their file history,
because of errors caused when scheduling both.
I suggest following Microsoft's recommendation and using a
third-party product. My favorite is
AOMEI Backupper Freeware,
but there are other
alternatives.


text:
Q: Why not use a ferrite bead around an RS-232 cable? This is from the instruction manual of a printer:

As you can see, one is not supposed to wrap the supplied bead around the serial cable. What is the reason for this?

A: I honestly can't think of  a valid electrical reason not to use the ferrite on the RS-232 cable. The ferrite acts as a common-mode choke that prevents RF interference from travelling along the cable, primarily in its shield.
At first, I thought it might have something to do with the fact that USB and Ethernet use balanced signals and RS-232 uses unbalanced signals, but then they tell you to put the ferrite on the parallel printer cable, which also uses unbalanced signals, so that isn't consistent.
Also, the speed of signaling on both RS-232 and the printer port are about the same (on the order of 100 kHz max.), so that wouldn't explain the difference, either.
I'd go ahead and use the ferrite on the RS-232 cable, too.

A: The bead may have a higher reactance than resistance at low frequencies, which could cause things like undershoot spikes to increase rather than decrease. Most likely these spikes will cause the higher voltage 12V signal to go beyond acceptable limits for RS232 and possible damage the devices. The other connection are all at lower voltages.


text:
Q: Python: How may I coerce a row of a pandas dataframe a dataframe? I have a pandas dataframe:
type(df_s1)
Out[362]: pandas.core.frame.DataFrame

This is one rows of it. It is a series, not a dataframe. But I want it to be a dataframe. How may I do it?
type(df_s1.iloc[(j+2), 0:n_s])
Out[363]: pandas.core.series.Series

It's not a problem for more than one rows in the dataframe.
type(df_s1.iloc[(j-1):(j+2), 0:n_s])

Out[364]: pandas.core.frame.DataFrame

A: You can use Series.to_frame method to convert a series into the dataframe.
Use:
sf = df_s1.iloc[(j+2), 0:n_s].to_frame()
print(type(sf))

This prints:
<class 'pandas.core.frame.DataFrame'>


text:
Q: Function to find all combinations with repetitions I have this function:
    void permutate (const string & s, std::vector<int>& index, std::size_t depth, int & count)
    {
        if (depth == s.size())
        {
            ++count;
            for (std::size_t i = 0; i < s.size(); ++i)
            {
                cout << s[index[i]];
            }
            cout << "\n";
            return;
        }

    for (std::size_t i = 0; i < s.size(); ++i)
    {
        index[depth] = i;
        permutate(s, index, depth + 1, count);
    }
}

To print all combinations I use this:
void print(string s) {

    if (s.find_first_not_of(s.front()) == string::npos)
    {
        cout << "Only 1 combination exists";
        return;
    }

    sort(s.begin(), s.end());

    cout << s << "\n**********\n";

    vector<int> index(s.size());
    int count = 0;

    permutate(s, index, 0, count);

    cout << "\nTotal combinations with repetitions: " << count;
}

Functions work great but I need specific combinations. For example, if I write
print("ABC");
I get: AAA, AAB, AAC, ABA, ..., CCA, CCB, CCC. So, I get overall 27 combination. But what if I need to make combination which size is not as the one of original set (in this case, size of original set is 3)?
For example, if I have a string "ABC" (or a set S = {A, B, C}) and I want combinations of size 2, I should get exactly 9 combinations: AA, AB, AC, BA, BB, BC, CA, CB, CC.
Please suggest changes that should be made in order to achieve my goal. Thank you.
 !!! Edit:   I want the same result as here but in C++.

A: I think the best solution is typeing new code in with you use backtrack for permutations.
I typed something like that you should provide vector V with chars you want for combinations and call the function bactrack like bactrack(0,length_of_expected_string).
You will got permutations in set S in alphaetical order.
You can uncommet code for typenig combinations on a screen.
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<queue>
#include<string>
#include<stack>
#include<list>
#include<vector>
#include<math.h>
#include<iomanip>
#include<fstream>
#include<cstdlib>
#include<ctime>
#include<map>
#include<set>
using namespace std;

vector<char> V;
vector<char> combination;
set<vector<char> > S;
void backtrack(int depth,int expected_length)
{
if(depth<expected_length)
{
    for(int i=0;i<V.size();i++)
    {
        combination.push_back(V[i]);
        backtrack(depth+1,expected_length);
        combination.pop_back();
    }
}
else
{
    /*for(int i=0;i<combination.size();i++)
    {
        cout<<combination[i];
    }
    cout<<endl;*/
    S.insert(combination);
}
}

int main()
{
backtrack(0,3);
for(auto it=S.begin();it!=S.end();it++)
{
    /*
    for(int i=0;i<(*it).size();i++)
    {
        cout<<(*it)[i];
    }
    cout<<endl;*/
}
}


text:
Q: Solution of homogeneous Fredholm equation of 2nd kind with non-symmetric Gaussian kernel I need to determine the eigenfunctions of the following kernel:
$$k\left(x',x\right)=\frac{1}{\sqrt{2\pi ax}}\exp\left(-\frac{\left(x'-x\right)^{2}}{2ax}\right)$$
where $a>0$ is a positive real parameter and $x$ goes from $0$ to $1$. Specifically, I need to determine the eigenfunctions with eigenvalue 1. That is, I need to find the functions $f(x)$ that are solutions of the following equation:
$$f(x') = \int_0^1 k(x',x)f(x)\mathrm d x$$
Note that the kernel is not symmetric, $k(x,x') \ne k(x',x)$. Also, we need to impose a regularity condition at $x\rightarrow 0$. We require that $|k(x',x)f(x)|^2 \le A$, where $A$ is a positive constant.


text:
Q: LocationManager does not stop PendingIntent based requests when app is force stopped I've been dealing with locations on Android for a long time, but recently I've decided to focus more on PendingIntents for processing updates. From the docs, I tried to understand the edge cases, mainly, what would happen to my requests in case my app was terminated by either the system or force closed by the user. Unfortunately, the docs aren't very detailed about this, so I created a test app..
To my surprise, if I request location updates using a PendingIntent and then terminate my app my request isn't cancelled. This means that if I start a GPS request, and then decide to swipe away my app from the "recents" list, the GPS will keep trying to get a lock forever (or until the device is reboot) even though my app is no longer running. I've even tried Force Stopping the app which didn't help, and then manually stop the process which was still around in the list of cached processes but to my dismay not even that was able to stop the request!
I know that my app's process may still be restarted by the system when an update becomes available because my receivers are registered on a manifest level, but what surprises me is that I would expect the location manager to terminate my request given that as far as I can tell I have no way whatsoever to clean after my app in these situations.
What I mean by that is:

*

*Imagine I just started a background single GPS request (I'm working on a background lib, so we're not tied to any activity or UI context) expecting to timeout it after 30 seconds if none was available.

*The user decides to swipe my app away or force stop it at that time.

*I get absolutely no guaranteed warning that I can hook up to, to clean my state and stop the GPS from trying to stay on forever. By that I mean that not even a service's onDestroy method is guaranteed to be called (it isn't really) in these situations.

I could always set a timeout beforehand on the alarm manager but that's just wrong, the request should stop with my app and not after a set period of time, wasting battery in the meantime for no good reason. Also, with GPS it really is hard to always specify a timeout beforehand, and with continuous update requests it becomes impossible. If I do get an update, I can then check if my app hasn't been killed in the meantime and stop the requests then..but what do I do if I never get an update like in a GPS while inside scenario?
Has anybody already found a proper/standard way to deal with this situations?
Tested on a Nexus 5 w/ 4.4.2
Update:
I'm still unable to work around this issue and have found that previous versions of Android (Galaxy Nexus 4.3) behave identically. If I request location updates using the PendingIntent method my requests do not stop if I force stop my app.


text:
Q: How can I text-indent the start of a every paragraph apart from the first in css? As the title says I have a p element and I want to text-indent the start of every paragraph apart the the first paragraph where I don't want any text-indent. How can I do this in css?

A: You can give your first paragraph a class and then can do the following:
p:not(.first){
  text-indent:30px
}

Please refer to this link:https://jsfiddle.net/n5pjgev6/400/

A: CSS
p > span {
  margin: 5px;
  display: inline-block;
}
p > span:first-child {
  text-indent: 25px;
}

JSFIDDLE

A: You can do this simply by applying a text-indent property to your paragraphs as so:
p {
    text-indent: 50px;
}

The text-indent property specifies how much horizontal space text should be moved before the beginning of the first line of the text content of an element. Spacing is calculated from the starting edge of the block-level container element.

Excerpt from CSS Tricks.

A: DEMO
    p{
  text-indent:40px
}
p:first-child{
  text-indent:0;
}

A: Another option which wouldn't require adding any additional markup or classes to your page:
http://codepen.io/panchroma/pen/jyaOJL
p{
  text-indent:20px;
}

body p:first-child{
  text-indent:0;
}

Good luck!

A: you can use this:
p:not(:first-child) {
   text-indent:30px;
}


text:
Q: Server authentication issue I am in the process of learning ASP .NET with Blazor. So, I started the creation of a small project with a connection to an administrator account to be able to dynamically change the content of the site. So I use a REST API to make the connection with the database.
My problem is that when I create the Claims on the server side in order to be able to authenticate myself as admin, they are not taken into account and User.Identity.AuthenticationType is null. Yet, I am sure that the code containing the creation of ClaimsPrincipal is executed.
I post here the code of UserController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Portfolio.API.Attributes;
using Portfolio.API.Contexts;
using Portfolio.Models;

namespace Portfolio.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly PortfolioContext _context;

        public UserController(PortfolioContext context)
        {
            _context = context;
        }

        [HttpGet("{login}/{hashedPassword}")]
        public ActionResult<User> GetUser(string login, string hashedPassword)
        {
            hashedPassword = BCrypt.Net.BCrypt.HashPassword(hashedPassword);
            if (_context.Users.Count() != 0)
            {
                var result = _context.Users.FirstOrDefault(el => el.Login == login && el.Password == hashedPassword);

                if (result == null)
                {
                    var result2 = _context.Users.FirstOrDefault(el => el.Login == login);
                    if (result2 != null)
                    {
                        result2.NumberConnectionTry++;
                        _context.Users.Update(result2);
                    }
                    return null;
                }
                else if(result.NumberConnectionTry == 3)
                {
                    return null;
                }
                result.NumberConnectionTry = 0;
                _context.Users.Update(result);
                return result;
            }
            return null;
        }

        [HttpPost("loginuser")]
        public async Task<ActionResult<User>> LoginUser(User user)
        {
            User loggedUser = await _context.Users.Where(u => u.Login == user.Login && u.Password == user.Password).FirstOrDefaultAsync();
            if(loggedUser != null)
            {
                var claim = new Claim(ClaimTypes.Name, loggedUser.Login);
                var claimsIdentity = new ClaimsIdentity(new[] { claim }, "serverAuth");
                var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
                await HttpContext.SignInAsync(claimsPrincipal);
            }

            return await Task.FromResult(loggedUser);
        }

        [HttpGet("logoutuser")]
        public async Task<ActionResult<String>> LogoutUser()
        {
            await HttpContext.SignOutAsync();
            return "Success";
        }

        [HttpGet("getcurrentuser")]
        public async Task<ActionResult<User>> GetCurrentUser()
        {
            User currentUser = new User();
            Console.WriteLine(User.Identity.IsAuthenticated.ToString());
            Console.WriteLine(User.Identity.AuthenticationType);
            if (User.Identity.IsAuthenticated)
            {
                Console.WriteLine("toto");
                Console.WriteLine("Toti : " + User.FindFirstValue(ClaimTypes.Name).ToString());
                currentUser.Login = User.FindFirstValue(ClaimTypes.Name);
            }
            return await Task.FromResult(currentUser);
        }

    }
}

And here the code of Startup.cs:
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;
using Portfolio.API.Contexts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Portfolio.API
{
    public class Startup
    {
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
                                  });
            });

            services.AddRazorPages();

            services.AddDbContext<PortfolioContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllers(options => options.SuppressAsyncSuffixInActionNames = false);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Portfolio.API", Version = "v1" });
            });

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Portfolio.API v1"));
            }

            app.UseCors(MyAllowSpecificOrigins);

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapRazorPages();
            });

        }
    }
}

If you need more info on the subject, don't hesitate to ask me!
Thanks for taking the time to read my problem.
UPDATE :
When I set a breakpoint on top of LoginUser I have the following User :

And now if I set a breakpoint right after HttpContext.SignInAsync, I have the following User and ClaimPrincipal :


text:
Q: Is there a tool that automatically saves incremental changes to files while coding? One of my favorite features of Google docs is the fact that it's constantly automatically saving versions of my document as I work. This means that even if I forget to save at a certain point before making a critical change there's a good chance that a save point has been created automatically. At the very least, I can return the document to a state prior to the mistaken change and continue working from that point.
Is there a tool with an equivalent feature for a Ruby coder running on Mac OS (or UNIX)?
For example, a tool that will do an automatic Git check-in every couple of minutes to my local repository for the files I'm working on. Maybe I'm paranoid, but this small bit of insurance could put my mind at ease during my day-to-day work.

A: VIM
Some may hate my response to this, but I use VIM quite often when coding and it has an auto-save feature, albeit an auto-save to a swap file. It is also extensible so that automatic commits can be done.
To see how extensible VIM is, check out this post: How can I script vim to run perltidy on a buffer?

A: The Netbeans IDE has a local history, which is enabled by default. Each time you save the file (ctrl-s), an entry is added to the file's history. As for the other supported VCSs, you can browse the history, see the diffs, and revert to a previous state.
Plus, Netbeans is known for having a really good support for Ruby developpment.

A: RubyMine automatically saves as you type and automatically saves a history of local changes. As far as I know, it won't automatically commit to Git, but it does integrate with Git. RubyMine works quite well on Mac OS X.

A: If you go down this "autocommit" road, always be sure to keep such history local. As Russell Steen commented, automatic checkpoints are not something that belongs in any kind of published, advertised branch. It is fine to keep for local reference, but otherwise it is just an ungroomed mess unfit for publication.
It is not too hard to write a simple script that will 'autocommit' to an specified branch. The linked script is not one that I use, just one that I found. It is a bit ugly in that it forcibly changes branches, so you would have to make sure it does not run if you are doing stuff manually. Also, it uses 'porcelain' Git commands instead of sticking to the lower-level (but correspondingly, more interface-stable) 'plumbing' commands.
You might also be interested enough to review a recent thread on the Git mailing list that covered some of this ground.
In particular, it references another script that does not "steal the current branch" and does a better job of using plumbing commands (but inexplicably, still uses git add instead of git ls-files and git update-index).
All in all, writing a script to do what you want is not terribly difficult. Doing it right (using plumbing, not stomping on the active branch (which is easy when you using plumbing), etc.) is a bit more effort, but worth it for the bits of Git that you will learn along the way.
You could even use the old shell implementation of git-commit as a starting point (and a good example of the plumbing and how to use it).
To get a checkpoint on a regular basis, just a stick script like ones of these it in a crontab.

A: Also Vim :) But what I use is much different from what kzh wrote.
I don't use a version control system for my automatic backup files, I rather
want to see all versions of all files in my ~/vim_backup directory. (Note:
of course I do use git for version controlling my source files, but now we are
talking about automatic backups.) The following lines in my .vimrc will make
Vim create a backup file each time the file is saved. The name of the backup
file is the name of the normal file plus the current date and time.
The following lines are in my .vimrc file:
if v:version >= 700
    " If I have a ~/vim_backup directory, let that be the backup          "
    " directory; otherwise do not back up.                                "
    " (Vim version earlier than 7.0 do not have the finddir function.)    "
    if finddir("~/vim_backup") != ""
        set bdir=~/vim_backup/
        set backup
    else
        set nobackup
    endif
endif

" We set the 'backupext' option to contain the current date and time, so  "
" that the name of the backup file will be the concatenation of the name  "
" of the normal file and the current date and time.                       "
function! HRefreshBackup()
    execute ":set backupext=" . strftime(".%y%m%d_%H%M")
    " You may want to have %H%M%S instead of %H%M if you want to have the "
    " possibility of having multiple backups in a minute.                 "
endfunction

" Refresh the backup file name before each "save"                         "
au BufWritePre * call HRefreshBackup()

Example of how my ~/vim_backup directory looks like:
$ ls -ltr ~/vim_backup | head
total 105692
-rwx--x--x 1 hcs hcs     252 2009-12-19 06:49 Sync_flash.091222_0902
-rwxr-xr-x 1 hcs hcs     819 2009-12-19 06:49 hk.091229_1637
-rwxr-xr-x 1 hcs hcs     507 2009-12-19 06:49 FOLLOW_LINK.091220_0802
-rwx--x--x 1 hcs hcs     212 2009-12-19 06:49 Cut.091230_2113
-rwxr-xr-x 1 hcs hcs  275320 2009-12-19 06:51 margitka.100116_1949
-rw-r--r-- 1 hcs hcs      80 2009-12-19 06:51 localrc_dorsu.vim.100101_1112
-rwx--x--x 1 hcs hcs   10335 2009-12-19 06:51 Video.091222_1754
-rwxr-xr-x 1 hcs hcs    1255 2009-12-19 06:51 Update.091222_1754
-rwxr-xr-x 1 hcs hcs     716 2009-12-19 06:51 SshMaker.091222_1754

This wastes some disk space, since all versions of all files are stored
. So it may be worth to periodically archive and compress them. I tried several
tools to compress the set of backup files, and "rar" with the "-s" option was
the best. 100 megabytes of backup files were created in the last three month,
and "rar -s" compressed it to 3 MB.

A: I use the Eclipse IDE for several languages and for all projects which do not have a GUI. One nice bonus is a local history and the ability to compare the current version with any previous version, either completely replacing the current version with any given previous version, or copying across some changes and ignoring others.
Have a look at this for using Ruby in Eclipse - http://www.ibm.com/developerworks/opensource/library/os-rubyeclipse/


text:
Q: How to do dynamic transclusion/child composition in Angular2? I have the following product details component in which the user can type a product SKU. This SKU can be a book, digital product, drink, TV or a Game Console. Based on that SKU, the details will be shown. The SKU can belong to only one type.
The details component is composed of many different product type components. Instead of including all the child product type components in the details component, is it possible to inject the child product type component dynamically when the user enters the SKU and click show details?
Why I want to inject the child component is due to when a new product type like microwave is added, I just have to create that component and not modify the product details parent component.
<product>
    <input [value]="productSKU" (input)="productSKU = $event.target.value">
    <button (click)="showProductDetails()">Show Product Details</button>
</product>
<details>
    <notfound></notfound>
    <book></book>
    <digital></digital>
    <drink></drink>
    <tv></tv>
    <gameconsole></gameconsole>
</details>

A: The Angular2 has ComponentFactoryResolver which can create dynamic components.


text:
Q: Why do some floating point numbers appear with a trailing 0 Does anyone know why the numbers 0.001 to 0.009 are rendered to a String with a trailing 0 but other numbers do not. e.g. numbers 0.01 to 0.09 do not.
System.out.println(Locale.getDefault());
for (int i = 0; i <= 20; i++)
    System.out.println(i / 1e3);

prints
en_GB
0.0
0.0010
0.0020
0.0030
0.0040
0.0050
0.0060
0.0070
0.0080
0.0090
0.01
0.011
0.012
0.013
0.014
0.015
0.016
0.017
0.018
0.019
0.02

EDIT The code for DecimalFormat doesn't appear to be locale dependant. If I run
for (Locale l : Locale.getAvailableLocales())   {
    Locale.setDefault(l);
    System.out.println(l + " " + 1 / 1e3);
}

on Java 6 update 26 on Ubuntu 11.04 I get
ja_JP 0.0010
es_PE 0.0010
en 0.0010
... many locales with the same result ...
sv_SE 0.0010
da_DK 0.0010
es_HN 0.0010

on Java 7 on same system I get
ms_MY 0.001
ar_QA 0.001
is_IS 0.001
... many locales with the same result ...
el_CY 0.001
hu 0.001
fr_FR 0.001

A: For those interested, here is a diff between the FloatingDecimal class responsible for creating the string representation of the double. As you can see from the diff, the patch fixes the special case encountered when the exponent is -3 in the dtoa() method.

A: This was identified as a bug in Java 1.3 - Java 6:  http://bugs.java.com/view_bug.do?bug_id=4428022
EDIT:  As to why this happens, here's the fix referred to in the bug report that was ported from OpenJDK 6: http://hg.openjdk.java.net/jdk6/jdk6/jdk/rev/8159687b6316
Turns out it's an off-by-one error.  (The fix changes <= to <).


text:
Q: How can I get HTML element with jQuery through a variable? Sometimes I run in to situations where I have the ID of a HTML element in a variable.
For example  var activePage = frontPage. How can I use this to get the DIV element with jQuery?
Because this is not working: var div = $('#'+activePage+'footer li a').
I know I can use document.getElementById(activePage) - but I don't know how I can use this together with jQuery.

A: You need a space in there. var div = $('#'+activePage+' footer li a'). Without the space, jQuery looks for the ID of frontPagefooter


text:
Q: Connection-Specific variables in nodeJS/Socket.io I am developing an application in nodeJS which uses socket.io for interactive gameplay. Inside the socket.on('connection') callback block, I have declared several variables. From what I can tell, these variables are connection-specific and there will be an instance for each callback fired on a socket connection for each client.
During my tests, I tried in two browsers and was able to play two independent game sessions at the same time which lead me to confirm this view of those variables.
However, when in a more live environment, I was noticing other players actions appearing as actions on my screen. I don't use broadcast anywhere, just simple emits inside the connection block, so I am perplexed why I see this happening.
Is my assumption about connection-specific variables incorrect? Or is there a more subtle application-specific reason this might be happening?

A: Your assumption is correct - the variables are local to the per-socket connection event. There is something else going on which is causing you issues.


text:
Q: What is ($\Pi^1_1$-CA)${}+{}$BI? And what is ID${}_\omega$? What is the formal system ($\Pi^1_1$-CA)${}+{}$BI? And what is ID${}_\omega$, the formal theory of $\omega$-times iterated inductive definitions?
They are both mentioned in the following paper without any further explanations:
W. Buchholz, An independence result for (Pi^1_1-CA)+BI, Annals of Pure and Applied Logic 33, 131-155, 1987.
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.573.420&rep=rep1&type=pdf

A: $\Pi^1_1$-CA + BI is the system $\Pi^1_1$-CA (a subsystem of second order arithmetic called $\Pi^1_1$ comprehension axiom, which is studied in reverse mathematics ) plus BI which stays for Bar Induction schema
Suppose $\prec$ is a two-place relation symbol defined on a set $X$ and $F(a)$ is an arbitrary $\mathcal{L}_2$-formula. We define:
$Prog(\prec; F) := \forall x[\forall y(y \prec x \rightarrow F(y)) \rightarrow F(x)] \text{(progressiveness)}$
$TI(\prec; F) := Prog(\prec; F) \rightarrow \forall xF(x) \text{(transfinite induction)}$
$WF(\prec) := \displaystyle (\forall S \subseteq X)[S\neq \emptyset \implies (\exists m\in S)(\forall s\in S)\lnot (s\prec m)]\text{(well-foundedness)}$
In other words well-foundedness means that every non-empty subset $S \subseteq X$ has a minimal element with respect to $\prec$.
Bar Induction  is the axiom schema consisting of all formula with the form
$WF(\prec)\rightarrow TI(\prec,F)$
where $\prec$ is an arithmetical relation and $F(a)$ is an arbitrary $\mathcal{L}_2$-formula.
I took this definition from the PhD thesis of Ian Alexander Thomson: Well-Ordering Principles and $\Pi^1_1$-Comprehension + Bar Induction (In this document well-foundedness is defined as $WF(\prec) := \forall YTI(\prec;Y)$, I don't know this definition and I cannot say much about it)
For additional information you can check wikipedia and also this link where they provide a definition of bar induction in terms of finite sequences of natural numbers and infinite tree.
ID$_\omega$ is one example of Systems of iterated inductive definitions, a class of formal systems. Check this link for more details.
You can also check the following book:
Buchholz, Feferman, Pohlers and Sieg: Iterated inductive definitions and subsystems of analysis: recent proof-theoretical studies, Lecture Notes in Mathematics 897 (1981)
ID$_\omega$ is proof theoretic equivalent to $\Pi^1_1$-CA + BI (and also to KPl, which is the KP (Kripke–Platek set theory) asserting "the universe is a limit of admissible sets").
Their proof theoretic ordinal is the Takeuti-Feferman–Buchholz  ordinal $\psi_0(\varepsilon_{\Omega_{\omega}+1})$ expressed with the Buchholz's psi collapsing function.
This ordinal is also the limit of the Buchholz's psi collapsing function notation.


text:
Q: Why is Hibernate generating a duplicate primary key on my table I am using Hibernate version 4.3.11 with H2 database version 1.3.172
I had this error
org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.jthink.songkong.db.SongChangesCache.saveMatchedToRelease(SongChangesCache.java:29)
at com.jthink.songkong.analyse.analyser.SongSave.saveSongChangedDetailsToDb(SongSave.java:416)
at com.jthink.songkong.analyse.analyser.SongSave.call(SongSave.java:163)
at com.jthink.songkong.analyse.analyser.SongSave.call(SongSave.java:73)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.SONGCHANGES(ID)"; SQL statement:
insert into SongChanges (id, field, newValue, originalValue, recNo, reportId, type, version) values (null, ?, ?, ?, ?, ?, ?, ?) [23505-172]

I have never seen this error before, my songchanges table use the standard
way to generate primary keys
@Id
@GeneratedValue
private Integer      id;

My Session is not shared between threads, but there are mutiple threads that could be writing to the songchanges table with their own session but why should that matter ?
My configuration is as follows
private static void addEntitiesToConfig(Configuration config) {
    config.addAnnotatedClass(MusicBrainzReleaseWrapper.class);
    config.addAnnotatedClass(MusicBrainzReleaseGroupWrapper.class);
    config.addAnnotatedClass(MusicBrainzArtistWrapper.class);
    config.addAnnotatedClass(DiscogsReleaseWrapper.class);
    config.addAnnotatedClass(AcoustidWrapper.class);
    config.addAnnotatedClass(PuidWrapper.class);
    config.addAnnotatedClass(Song.class);
    config.addAnnotatedClass(CoverImage.class);
    config.addAnnotatedClass(CoverArt.class);
    config.addAnnotatedClass(MatchedToMusicBrainz.class);
    config.addAnnotatedClass(MatchedToAllMusicGuide.class);
    config.addAnnotatedClass(MatchedToDiscogs.class);
    config.addAnnotatedClass(SongProcessed.class);
    config.addAnnotatedClass(SongChanges.class);
    config.addAnnotatedClass(DeleteDuplicates.class);
    config.addAnnotatedClass(AcoustidRecordingIdPair.class);
    config.addAnnotatedClass(ITunesTrack.class);
    config.addAnnotatedClass(Report.class);
}

public static Configuration getInitializedConfiguration() {
    Configuration config = new Configuration();
    config.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    config.setProperty("hibernate.connection.url", "jdbc:h2:" + Db.DBFOLDER + "/" + Db.DBNAME + ";FILE_LOCK=SOCKET;MVCC=TRUE;DB_CLOSE_ON_EXIT=FALSE;CACHE_SIZE=50000");
    config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    System.setProperty("h2.bindAddress", InetAddress.getLoopbackAddress().getHostAddress());
    config.setProperty("hibernate.connection.username", "******");
    config.setProperty("hibernate.connection.password", "******");
    config.setProperty("hibernate.c3p0.numHelperThreads", "10");
    config.setProperty("hibernate.c3p0.min_size", "20");
    config.setProperty("hibernate.c3p0.max_size", "200");
    config.setProperty("hibernate.c3p0.timeout", "300");
    config.setProperty("hibernate.c3p0.maxStatementsPerConnection", "50");
    config.setProperty("hibernate.c3p0.idle_test_period", "3000");
    config.setProperty("hibernate.c3p0.acquireRetryAttempts", "10");
    addEntitiesToConfig(config);
    return config;
}

I get a session like this
  public static Session beginTransaction() {
        Session hibernateSession = getSession();
        hibernateSession.beginTransaction();
        return hibernateSession;
    }

SongChanges class is as follows
package com.jthink.songlayer;

import org.hibernate.annotations.Table;

import javax.persistence.*;
import java.util.Date;

/**
 *
 */

@Entity
@org.hibernate.annotations.Table(appliesTo="SongChanges",indexes =
@org.hibernate.annotations.Index(name = "IDX_SONG_CHANGES_REPORTID_RECNO",
        columnNames = {"reportId", "recNo"})
)
public class SongChanges
{
    @Id
    @GeneratedValue
    private Integer      id;

    @Column(nullable = false)
    @org.hibernate.annotations.Index(name = "IDX_SONG_CHANGES_REPORTID")
    private Integer      reportId;

    @Column(nullable = false)
    @org.hibernate.annotations.Index(name = "IDX_SONG_CHANGES_RECNO")
    private Integer      recNo;

    private SongFieldKey field;

    @Column(length = 10000)
    private String       originalValue;

    @Column(length = 10000)
    private String       newValue;

    @Version
    private int version;

    private SongChangeType      type;

    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public Integer getReportId()
    {
        return reportId;
    }

    public void setReportId(Integer reportId)
    {
        this.reportId = reportId;
    }

    public Integer getRecNo()
    {
        return recNo;
    }

    public void setRecNo(Integer recNo)
    {
        this.recNo = recNo;
    }

    public SongFieldKey getField()
    {
        return field;
    }

    public void setField(SongFieldKey field)
    {
        this.field = field;
    }

    public String getOriginalValue()
    {
        return originalValue;
    }

    public void setOriginalValue(String originalValue)
    {
        this.originalValue = originalValue;
    }

    public String getNewValue()
    {
        return newValue;
    }

    public void setNewValue(String newValue)
    {
        this.newValue = newValue;
    }

    public SongChangeType getType()
    {
        return type;
    }

    public void setType(SongChangeType type)
    {
        this.type = type;
    }
}

A: What is happening is that your id is not being generated as your can see in you log file the value null.
There are plenty of ways to approach this and one of them is creating a sequence.
You can do that by adding the strategy to your @GeneratedValue. You will have something like that:
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SONG_CHANGES_SEQ")
@SequenceGenerator(sequenceName = "SONG_CHANGES_SEQ", allocationSize = 1, name = "SONG_CHANGES_SEQ")
private Integer id;


text:
Q: Clean Architecture: Must gateway to gateway communication go via a use case? In my application the network implementation (particularly a HTTP request interceptor) requires an authorization token stored in local persistent storage.
Now, following clean architecture, both network implementation and persistent storage are in the outer most, the framework layer.
The access token can be retrieved via a repository (where the implementation is in the gateway/interface adapters layer and the repository interface is in the inner-most/entity layer.
How should the control flow be in my scenario? Should it go

*

*via a use case, since, in the ring diagram, the use case layer entirely encapsulates the entity layer

*via the repository interface and skip the use case layer?

As counter arguments of 1 I see that

*

*I require a "get access token" use case, which is not a real use case from the user perspective.

*If the use case layer always encapsulates the entity layer, is it ok that the repository interface is in the entity layer but the implementation only in the interface adapters layer (skipping the use case layer)?

As counter argument of 2 I see that the use case layer is only between entities and user facing interfaces (controllers, presenters) but not between entities and data gateways - meaning the use cases layer does not actually fully encapsulate the entity layer, which would mean the ring representation of the layers is not accurate.

A: As I understand Clean architecture and have realized it in my applications the repository interfaces are always in the use case layer not in the entities layer.
Furthermore I would keep access token handling in the adapters layer if access token handling is not part of your applications core business logic.