Error writing a file - it gets doubled

Question: Sorry for how unclear the title may sound, I just don't know how to explain it.
So, I'm trying to read some lines frome a File, modify them and then add them to another file.
This is the original file:
line number one
line number two
line number three

And so on...
But when it comes to print it into another file, I get this:
line number one
line number one line number one
line number one line number one line number two
line number one line number one line number two line number two

This is my code
This is the part that reads the original file
try {
   File f = new File(path);
   try (FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr)) {

   while ((aux=br.readLine())!=null) {

       //easyDecryp is the method that modifies the line.
       //there's nothing wrong with it.

       output += easyDecryp(aux)+"\n";
       aux="";
   }
   br.close();
   fr.close();
}

} catch(IOException e) {
System.out.println("Error: "+e.getMessage());
}

And HERE I write into the new one
try {
   File f = new File(path);
   try (FileWriter fw = new FileWriter(f); PrintWriter pw = new PrintWriter(fw)) {
       pw.println(output);
   }
} catch(IOException e) {
   System.out.println("Error: "+e.getMessage());
}

Output is the variable that holds the lines. All of them.
It should read line by line and then be written into the new file, like this:
output = line1
//New line added
output = line1 \n line2

//Note the new line tag between every line

Comment: the code you have doesn't show where you write the file.  What is the "output" variable?
Comment: Post the code how you write the content into another file. Are you using **output** variable, which is append line content. **output += easyDecryp(aux)+"\n";**
Comment: You don't need explicit `Closeable.close()` at the end of try-with-resources, BTW.
Comment: easyDecryp(aux) inserts the duplicate lines. Please verify it in  debug mode.
Answer: I think easyDecryp(aux) is returning the line, and then you are doing += on top of that. This is why your line is getting duplicated.

Error writing a file - it gets doubled


"301 Moved Permanently" when trying to curl a local k8s service

Question: Background:

kubectl version- 1.24
Docker version- 20.10.17
MacOS Monterey v12.4

Question:
I'm following this tutorial, trying to set up a local k8s deployment + service.  I successfully ran the following commands:
$ kubectl config use-context docker-desktop
Switched to context "docker-desktop".

$ kubectl get nodes
NAME             STATUS   ROLES           AGE    VERSION
docker-desktop   Ready    control-plane   154m   v1.24.1

$ kubectl create deployment simple-webapp \
  --image training/webapp \
  --replicas=2 \
  --port=5000
deployment.apps/simple-webapp created

$ kubectl get deployments
NAME            READY   UP-TO-DATE   AVAILABLE   AGE
simple-webapp   2/2     2            2           3m23s

$ kubectl create service loadbalancer simple-webapp \
  --tcp=80:5000
service/simple-webapp created

$ kubectl get services
NAME            TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)        AGE
kubernetes      ClusterIP      10.96.0.1       <none>        443/TCP        156m
simple-webapp   LoadBalancer   10.109.168.49   <pending>     80:30582/TCP   9m34s

However, when I try to run curl http://localhost as mentioned in the tutorial, instead of getting the expected output (Hello world!), I get:

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.21.2

I'm brand-new to k8s and have no idea where to start diagnosing the problem.  Not sure if this is useful info, but I ran docker ps and it looks like there are two k8s-related docker containers currently running:
$ docker ps
CONTAINER ID   IMAGE             COMMAND           CREATED          STATUS          PORTS     NAMES
411b7110b315   training/webapp   "python app.py"   11 minutes ago   Up 11 minutes             k8s_webapp_simple-webapp-5d47556b5-jkvsc_default_9893ef1a-4bc5-43f3-80ac-151d567a89f6_0
9752c12315cc   training/webapp   "python app.py"   11 minutes ago   Up 11 minutes             k8s_webapp_simple-webapp-5d47556b5-269s8_default_5c50b3f8-57a9-4066-bd66-498cd30c758c_0

I do see nginx referenced in the curl output, does this mean that the 301 redirect is coming from inside the training/webapp process from the Docker container?  If so, how would I fix this?
EDIT: I tried creating both the deployment and service on a different port (5001 instead of 5000), since when I followed part 1 of the tutorial I ran into problems with port 5000 already being in use.  That worked for part 1 of the tutorial, however unfortunately it didn't solve my problem for part 2- I ran into the same 301 redirect problem when using both port 5000 and 5001.
EDIT 2: When I run kubectl get pods, I see the following:
$ kubectl get pods
NAME                            READY   STATUS    RESTARTS   AGE
simple-webapp-5d47556b5-sg9h4   1/1     Running   0          32s
simple-webapp-5d47556b5-xw2nh   1/1     Running   0          32s

I continue to see the 301 redirect even after running curl to confirm the pods are up.
EDIT 3: I do notice that when I run kubectl get nodes, the single node has a role of control-plane, not control-plane,master as noted in the tutorial.  I also notice that running kubectl get services shows that the EXTERNAL-IP of the loadbalancer is pending, not localhost as expected from the tutorial.  Are either of these facts relevant?
EDIT 4: Further down in the tutorial, we delete both the deployment and service that were previously created, and we re-create them using deployment.yml and service.yml files, alongside the commands kubectl apply -f deployment.yml and kubectl apply -f service.yml.  When I copy/paste the YAML from the tutorial into new files with the specified filenames, I get the same 301 Redirect error.
EDIT 5: In this Hacker News comment thread, I saw that Kubernetes had removed support for Docker as of v1.24.  I had previously upgraded my kubectl Homebrew version to 1.24 because my prior version didn't support the --replicas flag.  When I read this thread, I downgraded to v1.22 (the previous version), verified the version was correct via kubectl version, deleted/recreated the previously-created deployment and service, and tried curl again.  I still get the 301 redirect error.
EDIT 6: Here's the full output of curl -v http://localhost:
curl -v http://localhost
*   Trying 127.0.0.1:80...
* Connected to localhost (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> Host: localhost
> User-Agent: curl/7.79.1
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Server: nginx/1.21.2
< Date: Mon, 25 Jul 2022 04:53:40 GMT
< Content-Type: text/html
< Content-Length: 169
< Connection: keep-alive
< Location: https://localhost/
<

<title>301 Moved Permanently</title>

301 Moved Permanently

nginx/1.21.2

* Connection #0 to host localhost left intact

Looks like it's trying to redirect from http to https?  Could this be some setting within the training/webapp Docker image?
Also, here's the result of sudo lsof -i -P | grep LISTEN | grep :80:
$ sudo lsof -i -P | grep LISTEN | grep :80
nginx     3582   richiethomas    6u  IPv4 0x63a69bc74912e747      0t0    TCP *:80 (LISTEN)
nginx     3582   richiethomas    7u  IPv6 0x63a69bbdb3ebcbe7      0t0    TCP *:80 (LISTEN)
nginx     3701   richiethomas    6u  IPv4 0x63a69bc74912e747      0t0    TCP *:80 (LISTEN)
nginx     3701   richiethomas    7u  IPv6 0x63a69bbdb3ebcbe7      0t0    TCP *:80 (LISTEN)

Comment: use `netstat -alp` to figure who is listening at port 80. Also, the `301` response will have a `Location` header, whats the value ?
Comment: @YK1 I posted the output of `curl -v`.  As for who is listening on port 80, I wasn't able to get `netstat` to produce the output you asked for, but I've also updated the question to include the result of `lsof`.
Answer: It looks like you already have nginx running on port 80(and 443) on your system. Likely, another docker container outside kubernetes, or directly on your system. It already has taken port 80, hence your LoadBalancer is in pending state.
Either stop that nginx service or use another port like 8080 for your LoadBalancer:
$ kubectl create service loadbalancer simple-webapp \
       --tcp=8080:5000

The training/webapp does not use nginx.
Comment: Changing the port from `80` to `8080` did the trick!  Thank you!
Answer: You should be able to access the service using http://nodename/nodeip:30581
simple-webapp   LoadBalancer   10.109.168.49   <pending>     80:30582/TCP   9m34s

Note; Change the service type to NodePort from Loadbalancer. Loadbalancer only works on cloud providers like AWS, Azure etc.


Affine Curvature

Question: I was reading a paper related to convex curves, and encountered the following quantity:
Let $\gamma$ be a convex curve and $k(\cdot)$ be its curvature (with respect to arc length). The author is using the following highly ambiguous (at least to me) notation: $$\int_\gamma k(s)^\frac{1}{3} ds$$ and calling this quantity the affine curvature. My question is:
$\textbf{What does this notation mean?}$
First of all, what exactly is $k(s)?$ Secondly, what does it mean to integrate $k(s)$ with respect to $s$ along the curve $\gamma$?
Any help will be greatly appreciated!
Comment: $k(s)$ probably stands for the curvature as a function of the arc length $s$. Integrating over $ds$ means summing up all the quantity over the curve itself.
Comment: Is there a rigorous definition of the integral?
Comment: It's just the usual line integral of a scalar function...
Answer: As stated by me and Anthony Carapetis in the comments, $k(s)$ is just some scalar function and integrating it over $ds$ means that you are integrating along the curve. Hence, this is a line integral, more rigorously speaking.
Essentially what you are doing is summing up all cubic roots of the curvature $k(s)$ alongside the curve $s$.
Notice that to calculate the integral you would need a parametrization $s(t)$ and then integrate $k(s)$ wrt $t$.

Affine Curvature


Javascript TypedArray performance

Question: Why are TypedArrays not as fast as regular arrays? I want to store some precalculated integer values, and I need the access to the array to be as fast as it can be.
http://jsperf.com/array-access-speed-2/2
Preparation code:
 Benchmark.prototype.setup = function() {
   var buffer = new ArrayBuffer(0x10000);
   var Uint32 = new Uint32Array(buffer);
   var arr = [];
   for(var i = 0; i < 0x10000; ++i) {
     Uint32[i] = (Math.random() * 0x100000000) | 0;
     arr[i] = Uint32[i];
   }
   var sum = 0;
 };

Test 1:
sum = arr[(Math.random() * 0x10000) | 0];

Test 2:
sum = Uint32[(Math.random() * 0x10000) | 0];

PS: May be my perf tests are invalid feel free to correct me.
Comment: Very, very strange that they would have disappeared like that! All of them... Particularly strange in light of [this FAQ entry](http://jsperf.com/faq#test-availability). I've searched in case the URL changed or something, and...nothing. I can find other tests of array performance, but not Sukhanov's and mine. I've raised an [issue for it](https://github.com/mathiasbynens/jsperf.com/issues/197). Of course, it probably wouldn't hurt if more of us [donated to jsPerf](http://jsperf.com/faq#donate) (and I just did...for the first time *ducks head*).
Comment: Did you delete the jsperf tests? I can't access them any more
Comment: No, i've not removed it. This is strange.
Answer: Modern engines will use true arrays behind the scenes even if you use Array if they think they can, falling back on property map "arrays" if you do something that makes them think they can't use a true array.
Also note that as radsoc points out, var buffer = new ArrayBuffer(0x10000) then var Uint32 = new Uint32Array(buffer) produces a Uint32 array whose size is 0x4000 (0x10000 / 4), not 0x10000, because the value you give ArrayBuffer is in bytes, but of course there are four bytes per Uint32Array entry. All of the below uses new Uint32Array(0x10000) instead (and always did, even prior to this edit) to compare apples with apples.
So let's start there, with new Uint32Array(0x10000): http://jsperf.com/array-access-speed-2/11 (sadly, JSPerf has lost this test and its results, and is now offline entirely)

That suggests that because you're filling the array in a simple, predictable way, a modern engine continues to use a true array (with the performance benefits thereof) under the covers rather than shifting over. We see basically the same performance for both. The difference in speed could relate to type conversion taking the Uint32 value and assigning it to sum as a number (though I'm surprised if that type conversion isn't deferred...).
Add some chaos, though:
var Uint32 = new Uint32Array(0x10000);
var arr = [];
for (var i = 0x10000 - 1; i >= 0; --i) {
  Uint32[Math.random() * 0x10000 | 0] = (Math.random() * 0x100000000) | 0;
  arr[Math.random() * 0x10000 | 0] = (Math.random() * 0x100000000) | 0;
}
var sum = 0;

...so that the engine has to fall back on old-fashioned property map "arrays," and you see that typed arrays markedly outperform the old-fashioned kind: http://jsperf.com/array-access-speed-2/3 (sadly, JSPerf has lost this test and its results)

Clever, these JavaScript engine engineers...
The specific thing you do with the non-array nature of the Array array matters, though; consider:
var Uint32 = new Uint32Array(0x10000);
var arr = [];
arr.foo = "bar";                            // <== Non-element property
for (var i = 0; i < 0x10000; ++i) {
  Uint32[i] = (Math.random() * 0x100000000) | 0;
  arr[i] = (Math.random() * 0x100000000) | 0;
}
var sum = 0;

That's still filling the array predictably, but we add a non-element property (foo) to it. http://jsperf.com/array-access-speed-2/4 (sadly, JSPerf has lost this test and its results) Apparently, engines are quite clever, and keep that non-element property off to the side while continuing to use a true array for the element properties:

I'm at a bit of a loss to explain why standard arrays should get faster there compared to our first test above. Measurement error? Vagaries in Math.random? But we're still pretty sure the array-specific data in the Array is still a true array.
Whereas if we do the same thing but fill in reverse order:
var Uint32 = new Uint32Array(0x10000);
var arr = [];
arr.foo = "bar";                            // <== Non-element property
for (var i = 0x10000 - 1; i >= 0; --i) {    // <== Reverse order
  Uint32[i] = (Math.random() * 0x100000000) | 0;
  arr[i] = (Math.random() * 0x100000000) | 0;
}
var sum = 0;

...we get back to typed arrays winning out — except on IE11: http://jsperf.com/array-access-speed-2/9 (sadly, JSPerf has lost this test and its results)
Comment: Interesting, thanks. Things gets more complicated in real-use case, where continous allocation/disallocations of various objects/arrays leads to memory fragmentation, and processing time explodes if memory is not pre-allocated. In real life Typed Array will cost less since they're pre-allocated (Rq : js Arrays might be preallocated also...)
Comment: Writing pre-calced int32 values to typed array is fast. The array does not contain holes (yeah, holes are fast but…). The array is preallocated. So creating and initialization typed array is fast. But when you try to read from Uint32Array the value should be converted to double (see my answer below). You should use Int32Array (on x64) or Int16Array (on x86) (see my answer below again).
Answer: var buffer = new ArrayBuffer(0x10000);
var Uint32 = new Uint32Array(buffer);

is not the same thing as:
var Uint32 = new Uint32Array(0x10000);

not because of the new ArrayBuffer (you always get an array buffer: see Uint32.buffer in both cases) but because of the length parameter: with ArrayBuffer you have 1 byte per element, with Uint32Array you have 4 bytes per element.
So, in the first case (and in your code), Uint32.length = 0x1000/4 and your loops are out of bounds 3 out of 4 times. But sadly you will never get errors, only poor performances.
Using new ArrayBuffer, you have to declare Uint32 like this:
var buffer = new ArrayBuffer(0x10000 * 4);
var Uint32 = new Uint32Array(buffer);

See jsperf with (0x10000) and jsperf with (0x10000 * 4).
Comment: It's a shame that people accept answers basing on the content size, but not on correctness.
Comment: @MorrisLiang, that's what I thought as well, but then I realised this answer was posted over half a year after the question.
Comment: @MorrisLiang: Note that my answer *always* used `new Uint32Array(0x10000)` to compare apples with apples length-wise, and still revealed speed differences. But I didn't call out the difference the way radsoc did above.
Answer: In your case the reason of bad performance is you try to read outside the array when using Uint32Array because of bug with array length.
But if it wouldn't be the real reason then:
Try to use Int32Array instead of Uint32Array. I think in V8 variables cannot have uint32 type but can have int32 / double / pointer. So when you assign uint32 type to variable it will be converted to slower double.
If you use 32-bit version of V8 then variables can have int31 / double / pointer type. So int32 will be converted into double too. But if you use usual array and all values are int31 then conversion is not needed so usual array can be faster.
Also using int16 can require some conversions to get int32 (because of sign and ones' complement).
Uint16 will not require conversion because V8 can just add zeros in the left.
PS. You may be interested pointers and int31 (or int32 on x64) are the same things in V8. This also means that int32 will require 8 bytes on x64. Also this is reason why there's no int32 type on x86: because if we would used all 32 bits for storing integer we wouldn't have any space to save pointers anymore.

Javascript TypedArray performance


For which blocks is there a difference in actual mining speed between diamond pickaxe with efficiency 4 and 5?

Question: According to what I found on this subject, the calculation of mining speed for stone would go like this:

stone has hardness of 1.5
base mining time is 1.5 times hardness in seconds - 2.25 s.
diamond pickaxes has a mining speed factor of 8
efficiency 4 adds 1+4*4=17 to this factor,
while efficiency 5 adds 1+5*5=26
2.25 seconds divided by 8+17=25 is ~0.09, divided by 8+26=34 is ~0.065
actual time it takes to break a block is always rounded up to next increment of 50ms, so in both cases we get 10 blocks per second

Since producing pickaxes with efficiency 4 is significantly faster than efficiency 5, I am trying to establish the practical difference between the two. Obviously, efficiency 5 has the advantage of instamining stone when combined with beacon 5, but other than this it seems the gains are limited.
I am playing on a multiplayer survival with a small community. I obtained villagers for dirt cheap diamond gear and experience, I am supplying those to the other players. If I was my own customer, I would have always wanted to buy the best gear, but efficiency 5 tools require a little bit more time to make and I just realized their benefits are very circumstantial.
Basically, assuming you're not using a beacon with haste, no of the common blacks that people may want to remove in large batches to create corridors or large spaces can be mined faster with diamond pickaxe eff5 rather than eff4, am I right? But maybe some of the construction blocks are actually removed faster when you're redoing some space?
I am playing on Java Edition 1.16.4, in case game version is a factor please point out the difference. As an additional question, perhaps there are some common scenarios involving beacon, other than the case of stone?
Answer:
with Haste II (from a beacon), the difference is crucial: stone, granite, andesite, diorite can be insta-mined (1 gametick/block so 20 blocks per second). No so with Eff4.
Terracotta can be insta-mined with Eff5 and Haste I (using beacon with small base or a conduit).
there will be a small difference for nearly all blocks that take longer than 0.4s to mine with an eff4 pick (but pick is the right tool to mine them). That includes obsidian, endstone, ancient debris, nether brick, enderchests, also a lot of more common blocks in situations when mining speed is reduced (under water, levitating, swimming, under mining fatigue, hanging in cobweb, etc.) There are some exceptions e.g. mining speed of iron blocks remains reduced the same amount.
for great most blocks that can be mined in 0.4s (cobble, stone, and generally majority of building blocks) without haste there is no difference.

Essentially, any speed improvement that would result in breaking time shorter than 0.4s but longer than 0.05s (instamine) gets capped at 0.4s. In practice, that means the difference will be minor for players mining obsidian, endstone and nether brick, crucial for users of beacons, and mostly insignificant for the rest.


type casting or array indexing bug in HLSL (Unreal Engine 4)

Question: I have the following piece of code in my HLSL shader which works on Windows x64 but fails to run when deployed to Android using UE4:
// calcScale() returns a value between 0.0f and 7.0f, inclusive
float Scale = calcScale();

const float3 Values[] =
{
    { 0.0f, 0.0f, 0.0f },
    { 0.0f, 1.0f, 1.0f },
    { 0.0f, 0.0f, 1.0f },
    { 0.0f, 1.0f, 1.0f },
    { 1.0f, 1.0f, 0.0f },
    { 1.0f, 1.0f, 0.0f },
    { 1.0f, 0.0f, 1.0f },
    { 0.0f, 1.0f, 1.0f },
    { 1.0f, 1.0f, 1.0f }
};

int index = int(Scale);
OutDeviceColor = lerp(Values[index], Values[index + 1], Scale);

If I replace the last line with literals, it works:
OutDeviceColor = lerp(Values[0], Values[1], Scale); //works

I have even tried setting:
int index = 0; // does not help

I do not get any error messages in UE4Log. I tried having a cursory look at logcat too but didn't find anything suspicious. My output is a screen with the lower left portion of the screen black and green, yellow and red interpolated in the upper right portion for the screen which is what I'm guessing is an indication of a shader failing at runtime.
Comment: Afaik you can use your float variable `Scale` directly for accessing the array, without converting it to an int. Did you tried this? I looked through the HLSL documentation, but unfortunately didn't found a reference. But I'm pretty sure, that under the former DX9 HLSL reference, such an option have been described.
Comment: I think that would be highly compiler dependent if it worked. To be safe, it would be preferable to cast it to an int or uint before using it as an index.
Answer: Hi your code is confusing: lets say scale gives you 6.5, then your int would be 6.
PS: casting in hlsl is:
int index = (int) Scale;

So you are accessing element 6 and 7, and lerp it with 6.5? Is that really what you want?
Maybe you want to write:
// calcScale() returns a value between 0.0f and 8.0f, inclusive
float scale = calcScale();

const float3 Values[] =
{
    { 0.0f, 0.0f, 0.0f },
    { 0.0f, 1.0f, 1.0f },
    { 0.0f, 0.0f, 1.0f },
    { 0.0f, 1.0f, 1.0f },
    { 1.0f, 1.0f, 0.0f },
    { 1.0f, 1.0f, 0.0f },
    { 1.0f, 0.0f, 1.0f },
    { 0.0f, 1.0f, 1.0f },
    { 1.0f, 1.0f, 1.0f } // YOU HAVE 9 ELEMENTS! Shouldn't scale be between 0-8???
};

int lowIndex = (int) floor(scale);
int highIndex = (int) ceil(scale);
float factor =  frac(scale); //for 6.5 frac gives you 0.5

OutDeviceColor = lerp(Values[lowIndex], Values[highIndex], factor);

//or better all in one function
OutDeviceColor = lerp(Values[floor(scale)], Values[ceil(scale)], frac(scale));

One thing to say. Try to avoid using ints. HLSL can access every array or vector with floats. Graphic devices are not very good in working with ints. Maybe your compiler is optimizing that anyway, but you don't know that for sure.
Keep in mind: Everything is optimized for using floats.
Good Luck
Comment: Well the point I was trying to make is that the code fails to produce any output at all. There are some changes in the code above like the lerp actually happens for Scale - (float)index instead of Scale. I am not looking for help with the logic in this case. I am trying to understand why the compiler seems to not accept the float value at all. Again, this works perfectly on Windows.
Comment: is OutDeviceColor a float3? normal output color is float4, maybe some error here? Are you sure, your scale function is within the range? maybe negative?


Terraform: How can I read a value from a json file?

Question: I have the json file (map.json):
[
  {
    "QueueName": "queue1",
    "TypeName": "type1"
  },
  {
    "QueueName": "queue2",
    "TypeName": "type2"
  },
  {
    "QueueName": "queue3",
    "TypeName": "type2"
  }
]

which I can load into the following variable:
locals {
  maps = jsondecode(file("maps.json"))
}

How can I read the TypeName value for QueueName = "queue2"?
Answer: I think you are looking at something like this:
type = [for el in local.maps : el["TypeName"] if el["QueueName"] == "queue2"]

Output
$ terraform console
> local.response
[
  "type1",
]

Logically this will return a list of elements, but if you want to retrieve only the first result, then you can use:
response = [for el in local.maps : el["TypeName"] if el["QueueName"] == "queue1"]
type     = length(local.response) > 0 ? local.response[0] : ""

Outputs
$ terraform console
> local.type
"type1"
>

Or just:
type = local.maps[index(local.maps.*.QueueName, "queue1")]["TypeName"]

But this will throw an exception if the element queueName does not exist, something like this:
Call to function "index" failed: item not found


Can docker containers share a directory amongst them

Question: Is it possible to share a directory between docker instances to allow the different docker instances / containers running on the same server directly share access to some data?
Answer: You can mount the same host directory to both containers docker run -v /host/shared:/mnt/shared ... or use docker run --volumes-from=some_container to mount a volume from another container.
Answer: Yes, this is what "Docker volumes" are.  See Managing Data in Containers:

Mount a Host Directory as a Data Volume
[...] you can also mount a directory from your own host into a container.
$ sudo docker run -d -P --name web -v /src/webapp:/opt/webapp training/webapp python app.py
This will mount the local directory, /src/webapp, into the container as the /opt/webapp directory.
[...]
Creating and mounting a Data Volume Container
If you have some persistent data that you want to share between containers, or want to use from non-persistent containers, it's best to create a named Data Volume Container, and then to mount the data from it.


Loop-invariant, Hoare logic

Question: What is the loop-invariant for this problem? The only invariant I can think of is x=(x-y)+y but it feels wrong since it doesn't say much more than x=x.
EDIT: Is the invariant just ⊤?
Comment: Please use mathjax to write your question.  This is short; no need to say more in an image, than you did through typing.
Answer: $x\geq y$ looks like a good invariant to me.

Loop-invariant, Hoare logic


ubuntu 18.04 resolution issue

Question: I am using lenovo ideapad z470.
Here is the spec if it helps
https://www.cnet.com/products/lenovo-ideapad-z470/specs/
During ubuntu installation I had to give 'nomodeset' to boot in, but now I am having issue with resolution, it is stuck on 1024 X 768.

also my laptop say it has nvidia geoforce, but I don't see it here, probably it is something to do nomodeset
When I remove nodemodeset during boot ubuntu doesn't even come to login screen.
Answer: My laptop's inbuilt graphics card was incompatible to run 16.04, going back to 14.04.
Windows 10 runs smoother though, but it lacks the performance ubuntu gives.

ubuntu 18.04 resolution issue


How do I open the Minecraft Forge installer?

Question: When I try to open the Minecraft Forge 1.12.2 installer that I downloaded, my computer doesn't open it normally but asks me to open it with another application. How can I open the installer? I haven't found out anything about how to fix this whether something is wrong with my permissions on downloads on my computer or if it's just the download itself.
Answer: You need to open it with Java. If it's not showing up in the list of apps to use, you might not have it installed.
If not, go to https://www.java.com/en/download/ and install Java.


Thunderbird Mails (not enough disk space)

Question: I am using thunderbird mail and the partition in which mails are stored is of 470gb from which only 64gb is used.
Now the problem is whenever i start thunderbird it generate a error message which says "There is not enough disk space to download new messages. Try deleting old mail, emptying the trash folder, and compacting the mail folders, and then try again.
Comment: Are you using 32bit or 64bit Ubuntu?
Comment: Can you confirm the mail box location (it will be somewhere in the settings in your account, called "local folder") ?
Comment: It may be an inodes problem. What does `df -i` tell you?
Comment: It is 32 bit and mail box location mean to say where mails are stored?
Answer: In my case;
I am using Ubuntu 12.04. My inbox size was 4GB (I think limitation of os), so i created a new archives directory like 2013 and moved all old mails on date 2013 from Inbox.
Also you can check your box size from your thunderbird folder:

cd /home/username/.thunderbird/axxmjtdv.default/Mail/pop.googlemail.com/
ls -all
Answer: This worked for me:
I had just a few messages in my Inbox folder but its associated file ocuppied way more than 3 Gb (near the 4 Gb file size limit), so I compacted it to remove obsolete information, and it's now less than 50 Mb.
New messages are now well downloaded.
More info:
From MozillaZine Knowledge Base about compacting and file size:

When you delete messages in an email client such as Thunderbird they aren't physically deleted. Even emptying the Trash does not get rid of them. Instead they are marked for deletion and hidden from view. They are not physically removed until you "compact" the folder. This is a tradeoff done to improve performance in large folders.

And the same site about file size limit:

Prior to version 3.1 the maximum folder size is 4GB, or as limited by your file system [...]
  Thunderbird 3.1 added a a 64-bit offset to the .msf file allowing imap folders larger than 4GB, if the file system permitted large files [...]
  This change did not help non-imap folders, for example those in Local Folders, including any offline storage.

So pop email folders file size is still limited.


What's a good design for an intermediate triple-relation model?

Question: I'm new to Rails and don't grasp yet all the possibilities with associations. Here's my problem:
I have a couple of models like apple and lemon.
Then there's the model 'relation' that holds triples of relations:
subject | relation | object
apple | is sweeter than | lemon
The migration for 'relations' is this:

create_table :relations do |t|
  t.references :subject,  :polymorphic => true
  t.string     :relation
  t.references :object,   :polymorphic => true
  t.timestamps
end

this should store relations like
subject_id = 1
subject_type = apple
relation = is sweeter than
object_id = 2
object_type = lemon
In reality I have more than just 2 models, so I thought I need to make the subject and object column model-agnostic by using the polymorphic option.
How would you set the associations in the model classes of apple, lemon and relation? Is the table design of relations good like this?
Thanks so much for your help!!
-Alex
Answer: Give the db schema you described, seems like it should be fairly straightforward:
class Relation < ActiveRecord::Base
  belongs_to :object, :polymorphic => true
  belongs_to :subject, :polymorphic => true
end

And your other classes would look like this
class Apple < ActiveRecord::Base
  has_many :object_relations, :class_name => 'Relation', :as => :object
  has_many :subject_relations, :class_name => 'Relation', :as => :subject
end

class Orange < ActiveRecord::Base
  has_many :object_relations, :class_name => 'Relation', :as => :object
  has_many :subject_relations, :class_name => 'Relation', :as => :subject
end

Comment: awesome, it's 80% of what I needed => OK!
(my description was quite simplified, the real case is/was more complex)

tha-hanx!
Answer: Polymorphic IS PAIN:
Unless you need it badly, use somethimng like SingleTableInheritance:
class Fruit < ActiveRecord::Base
   has_many :relations
   has_many :related_objects, :through => :relation, :class_name => 'Fruit'
   has_many :relating_subjects, :through => :relation, :class_name => 'Relation'
end
class Relation < ActiveRecord::Base
   belongs_to :object, :class => 'Fruit'
   belongs_to :subject, , :class => 'Fruit'
   validate_presence_of :object_id
   validate_presence_of :subject_id
   validate_presence_of :relation
end

And then like:
class Apple < Fruit
   ...
end

I hope that helps, (I did not tested this code)


Select all columns matching a specific values which can be empty

Question: I want to make a query which have multiple input parameter, and some of them can be empty.
This query is used to get the data from the database, depending on the values that the user enters.
For example, he can only choose the beginning and the finishing date with the hour, or just choose the product, etc...
SELECT
    cl.checklist_id AS id,
    cl.checklist_indice AS indice,
    cl.checklist_produit_id AS produitId,
    cl.checklist_personne_id AS personneId,
    cl.checklist_date AS date,
    cl.checklist_heure AS heure,
    cl.checklist_machine_id AS machineID
FROM
    checklist cl,
    personne p,
    produit pr
WHERE cl.checklist_id IN (SELECT
            cl.checklist_id
        FROM
            checklist cl
        WHERE
           :heureStart <= cl.checklist_heure
                AND cl.checklist_heure <= :heureEnd
                AND cl.checklist_id IN (SELECT
                    cl.checklist_id
                FROM
                    checklist cl
                WHERE
                    :dateStart <= cl.checklist_date
                        AND cl.checklist_date <= :dateEnd
                        AND cl.checklist_id IN (SELECT
                            cl.checklist_id
                        FROM
                            checklist cl
                        WHERE
                            cl.checklist_produit_id = :produitId
                                AND cl.checklist_id IN (SELECT
                                    cl.checklist_id
                                FROM
                                    checklist cl
                                WHERE
                                    cl.checklist_machine_id = :machineId
                                        AND cl.checklist_id IN (SELECT
                                            cl.checklist_id
                                        FROM
                                            checklist cl
                                        WHERE
                                            cl.checklist_personne_id = :personneId)))));

If I want this query to work, I must fill all the values to get the data.
Is there a way to get all the data from a column if the values is empty  (like a SELECT * on the column) ? Do I need to make a query for every possibility ?
Answer: Perhaps something like this query? You have to query for every possibility, but not in a nested query like you did...
SELECT cl.checklist_id AS id,
  cl.checklist_indice AS indice,
  cl.checklist_produit_id AS produitId,
  cl.checklist_personne_id AS personneId,
  cl.checklist_date AS date,
  cl.checklist_heure AS heure,
  cl.checklist_machine_id AS machineID
FROM checklist cl, personne p, produit pr
WHERE (:heureStart is null OR :heureStart <= cl.checklist_heure)
      AND ((:dateStart is null AND :dateEnd is null) OR (:dateStart <= cl.checklist_date AND cl.checklist_date <= :dateEnd))
      AND (:produitId is null OR cl.checklist_produit_id = :produitId)
      AND (:machineId is null OR cl.checklist_machine_id = :machineId)
      AND (:personneId is null OR cl.checklist_personne_id = personneId);

Comment: Thank you for your quick answer !
But in my database the columns are never empty so I must fill all the input on my form to get the data, so I face the same kind of problem.. Or maybe I've misunderstood something.
Comment: I'm not checking that the database column is empty, I'm checking that your input on your form is empty. So either your input from your form for that field is empty, or you compare it to values in your database...
Comment: I've found that the error is caused by an illegal mix of collations. Thank you.
Answer: I've found the query that successfully fit my problem, here it is :
SELECT cl.checklist_id AS id,
    cl.checklist_indice AS indice,
    cl.checklist_produit_id AS produitId,
    cl.checklist_personne_id AS personneId,
    cl.checklist_date AS date,
    cl.checklist_heure AS heure,
    cl.checklist_machine_id AS machineId

FROM checklist cl

WHERE (cl.checklist_date BETWEEN :dateStart AND :dateEnd)
    AND (cl.checklist_heure BETWEEN :heureStart AND :heureEnd)
    AND cl.checklist_produit_id REGEXP :produitId
    AND cl.checklist_machine_id REGEXP :machineId
    AND cl.checklist_personne_id REGEXP :personneId;

And this is the PHP code (for every variable you must check this):
if(strlen($variable) == 0){
            $variable= "^.*$";
}

The REGEXP match all character, from a sequence size from 0 to ∞ (infinite).


Posting dynamic arrays as distinct variables using JavaScript

Question: Am trying to dynamically add the fields for subjects and the grades obtained, but am getting an error "Undefined index: subject in..." when posting those variables using java script.
Could there be something am missing with my posting mechanism. Notice that in the form data am not puting id="subject" to avoid picking the id for only one subject, and am using name="subject[]" to show an array, but I
dont seem to know how to represent this in the java script as we will see below.
form data as follows;

Academic Qualification

                              <?php
                     require_once("connection/connectPDO.php");
                     $sql="CALL sp_getSubjects()";

                        //Initiate and Call Stored Procedure Using  PDO
                                $pdo = new PDOConfig();
                                $resultsSubject = $pdo->query($sql);
                                foreach($resultsSubject as $rowSubject)
                                        {
                    ?>

<?php echo $rowSubject['SubjectName']; ?>:<input name="subject[]" type="hidden" value="<?php echo $rowSubject['SubjectID']; ?>" />

                        <select name="grades[]" id="grades" class="validate[required]">
                          <option  value="">--Select Grade--</option>
                                     <?php

                    $sql="CALL sp_grabGrades()";

                                //Initiate and Call Stored Procedure Using PDO
                                $pdo = new PDOConfig();
                                $resultset = $pdo->query($sql);
                                foreach($resultset as $row)
                                        {

                    ?>
                       <option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
                                <?php } ?>
                        </select>
                                 <?php } ?>

the form looks like this
Academic Qualification
English <--select-->
Biology <--select-->
Science <--select-->
the java script code is as follows;
            $(document).ready(function(){
                $("#submit").click(function(){
                     //if invalid do nothing
                     if(!$("#formD").validationEngine('validate')){
                     return false;
                      }
                    var vgrades = $("#grades").val();
                    var vsubject = $("#subject").val();

                    $.post("sendInitialApplication.php",
                        {
                            grades : vgrades,
                            subject : vsubject
                        /*Handles response from server*/
                        function(response){
                            alert(response);
                        });
                    alert("You are here");
                });
            });

the PHP code "sendInitialApplication.php" is as follows
            <?php
                $method = $_SERVER['REQUEST_METHOD'];

                function connect(){
                    try{
                        $dbConn = new PDO('mysql:host=localhost; dbname=student', 'root', 'root');
                        $dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                        return $dbConn;
                    }
                    catch(PDOException $e){
                        echo $e->getMessage();
                    }
                }

                /*Checks if method is HTTP POST*/
                if(strtolower($method) == 'post'){

                    $grades = addslashes($_POST['grades']);
                    $subjects = addslashes($_POST['subject']);

                    try {

                        $dbHandler = connect();
                        $dbHandler->beginTransaction();

                        //Saving Various subjects with distinct grade obtained
                        foreach($subjects as $key => $subject)
                        {

                        $setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
                        $stmt_subject = $dbHandler->prepare($setIndexSubject);
                        $stmt_subject->bindValue(':vSubjectID', $subject);
                        $stmt_subject->bindValue(':vGradeObtainedID', $grades[$key]);
                        $stmt_subject->execute();
                        $stmt_subject->closeCursor();
                        }

                        $dbHandler->commit();

                        echo "The Operation was Successful!!!!!!";

                    } catch (PDOException $e) {
                        $dbHandler->rollback();
                        die($e->getMessage());
                    }

                }else{
                    echo "Oops! Make sure Method is POST";
                }
            ?>

Comment: @holodoc could you help me here
Answer: I'm expecting that $_POST['subject'] and $_POST['grades'] should be array. Than you cannot use $subjects = addslashes($_POST['subjects']), but $subjects = $_POST['subjects']. Calling addslashes on array throws PHP warning and returns NULL.
Edit:
I suggest modify logic of your code.
Input type hidden, with subject id, will not work, as you expects. Modify your list:
// ... obtaining subjects from db ...
foreach($resultsSubject as $rowSubject) {
?>

      <select name="grade[<?= $rowSubject['SubjectID']; ?>]">
        <option  value="">--Select Grade--</option>
        <?php
        // ... obtaining grades from db ...
        foreach($resultset as $row) {
        ?>
        <option value="<?php echo $row['GradeObtainedID']; ?>"> <?php echo $row['Grade']; ?> </option>
        <?php
        }
        ?>
      </select>

<?php
}

Than serialized form should return array:
grade = array (
  subjectID1 => selectedGradeId,
  subjectID2 => selectedGradeId,
  ...
)

And data processing in sendInitialApplication.php:
// prepare db transaction
$grades = $_POST['grade'];
foreach ($grades as $subject => $grade) {
  $setIndexSubject = 'CALL sp_sendIndexSubject(:vSubjectID,:vGradeObtainedID)';
  $stmt_subject = $dbHandler->prepare($setIndexSubject);
  $stmt_subject->bindValue(':vSubjectID', $subject);
  $stmt_subject->bindValue(':vGradeObtainedID', $grade);
  $stmt_subject->execute();
  $stmt_subject->closeCursor();
}
// close db transaction

Comment: thanks but that still didnt work. subject is not being defined, how best can we show this post
Comment: Try to serialize form data on submit as shown here: http://stackoverflow.com/questions/15173965/serializing-and-submitting-a-form-with-jquery-post-and-php
Comment: Nothing still, we have a problem with the posting of subject
Comment: I've modified answer. Try to chanfe your grade selects, and data processing logic.
Comment: the subjects are entered dynamically on the db, so we can not pre_define like in the array "grade = array(subjectID1 => selectedGradeId,...) ", the subjects can grow anytime and I wish not to go back to increasing the mentioned array. the subjects are not static. A user should enter subjects and on that form they should show.
Comment: I don't see problem. Subjects are readed from database. So list of subject depends on selection logic. Each user should have different subjects list. And submit will return only listed subjects, there are no need for static list.
Comment: Please understand the logic of how I want this to run. Please read through my question and the comments again. These are dynamic fields, every user sees all the subjects as the list grows in the DB. I have another form where I enter subjects and store them in a separate table. the user from the  Form front end sees the subjects and so as the select grade input stub .


Atomic load to multiple tables in google bigquery

Question: I am trying to do a load operation in bigquery from GCS files using load_job in ruby.
The problem is, when I have multiple files in GCS affecting different tables, there's a chance some might fail due to validation/network issues, leading to inconsistent data in bigquery.
Let's say I want to load last hour data which is stored in 5 files, even if 1 of these load jobs fail, I'll be having bad data for analytics.
Is there a way I can batch all these load jobs in a single atomic request to bigquery?
Comment: you share some code how you are trying to do it. are you able to catch failures and retry in case of error ? What about a temporary table to ensure move the data properly to bigquery and after that move them to your final tables?
Comment: if your concern is about network errors submiting to BQ, it shouldn't be a case if you ensure that all your data is inside of bigquery, I would expect it to be much more stable once all your data is in temp tables inside bigquery and perform the operations from table to table
Comment: @hlagos, even if I create temporary tables, these problems will still exist when sending the copy request because they will also create different jobs in BQ, or am I missing something with that approach?
Answer: Why don't you try a BQ Sink or streaming data into BQ.
With Sinks you will be counting on the BQ underlining architecture which is quite stable and consistent to move data from text files to BQ tables.
With streaming data, you will have more control over your transactions. You can then insure that you're data is moved correctly line by line.
Comment: The reason not to go for streaming is that loading is much faster when there's a lot of data, and streaming will slow down the process.
Comment: Why don't you try to send your data to Cloud Datastore as your temp location since datastore supports ACID transactions and then after successful transaction send the data from the resulting datastore kind to the BQ table. More info can be found here: https://cloud.google.com/bigquery/docs/loading-data-cloud-datastore
Comment: We started working on a project today using dataflow that might be a help for you in the scenario you described.


Java Faces ServletContext object inside ManagedBean class

Question: I just started learning JSF.
While working with an example, I felt the need to access the ServletContext object inside MyBean class. I wanted to use an object which I had put inside the ServletContext using Listener. Can I do that? Does ServletContext has its scope inside Beans as well?
Answer: It's just available by ExternalContext#getContext(). See also its javadoc:

getContext
public abstract java.lang.Object getContext()
Return the application environment object instance for the current appication.
It is valid to call this method during application startup or shutdown. If called during application startup or shutdown, this returns the same container context instance (ServletContext or PortletContext) as the one returned when calling getContext() on the ExternalContext returned by the FacesContext during an actual request.
Servlet: This must be the current application's javax.servlet.ServletContext instance.

So, this should do:
public void someMethod() {
    ServletContext servletContext = (ServletContext) FacesContext
        .getCurrentInstance().getExternalContext().getContext();
    // ...
}

Unrelated to the concrete question, depending on the concrete functional requirement, this may not be the right solution to the concrete problem. General consensus is that your JSF code should be as much as possible free of any javax.servlet.* dependencies/imports. Your question isn't exactly clear, but if you indeed intend to access an attribute which you've put in the servlet context, then just get it from ExternalContext#getApplicationMap() instead.
E.g. in the ServletContextListener:
event.getServletContext().setAttribute("foo", foo);

and then in JSF
Foo foo = (Foo) FacesContext.getCurrentInstance().getExternalContext()
    .getApplicationMap().get("foo");

or even just by @ManagedProperty
@ManagedProperty("#{foo}")
private Foo foo; // +setter

Comment: The concrete problem was that I was instantiating a Database Connection and storing that connection object in Context-param so that all Servlets could use it.
Seeing your answer, I guess the ExternalContext class would do the job in JSF. I'll check it after going through the docs. Thank you :)
Comment: You're welcome. Well, this is honestly said kind of "eeek". This way your application would die after ~8 hours of running depending on the DB server side connection timeout setting. You should open and close DB resources in shortest possible scope. See also among others http://stackoverflow.com/questions/9428573/is-it-safe-to-use-a-static-java-sql-connection-instance-in-a-multithreaded-syste/9431863#9431863. However, for a Java EE web application, I'd have used JPA `@EntityManager` in an `@Stateless` EJB. This is injectable in both JSF managed beans and servlets by just `@EJB`.


patch small leaks in ceramic sewage line running through basement

Question: Have a ceramic (I think?) sewage line that runs from under the bathroom across the top of the basement and goes out the wall into the yard. Have very small drips in a couple of places on this line. Would like to know if there is a way to seal these leaks so I don't have to replace the whole line at this time.
Comment: Is it leaking at the joints or along the length of the pipe?
Comment: ..came here for the pictures. +1'd so that you can post some :)
Answer: Do you have enough access to the pipe to wrap something completely around it? I know we're not supposed to get carried away with brand names here, but have you searched for anything along the lines of "perma-wrap" or "water activated fiberglass pipe repair wrap?"
Or, cut a curved section of clay or PVC pipe of the right size, clean the pipe and put the cut section over it, then seal it with an industrial sealant that adheres to both materials. Even after that, I would personally wrap the pipe with something like fiberglass. But one of these approaches might create a solid seal and get you by until you can replace the pipe.


how to get list item position in android setOnTouchListener android?

Question: I am implementing listview in android.I want listview row's layout_width and height to be increased when listview item is pressed.I am using zoom_in animation to scale view which i have kept in anim folder.But i couldnot use it in selector since i dont know how to start animation if i keep it in selector.
I tried an other way that i implement animation in getView of adapter.Here i need to get the selected view's position that i set it from onTouchListener function.But now i cannot get the selected row's position in onTouch function.I want to know how to get the row's position in onTouch function? Or how to get the pressed state in getView function in adapter?Thanks in Advance.
Answer: In your touch event you can get the X,Y coordinates of the touch.
The ListView has method pointToPosition
int pos = YOUR_LISTVIEW.pointToPosition((int) e1.getX(), (int) e1.getY());

e1 is MotionEvent
Comment: Excellent solution.I had been waiting for the one like this.Works as charm.Thanks a lot.


How do I run Python code as a script?

Question: I need help running python in ubuntu
I can run python without a problem in my terminal
but when I create a .py file I can't get it to run.
Comment: So how are you trying?
Comment: thats what i try to find out
Comment: There are many ways, depending on if the file is executable or not, with shebang or not. Will see if I can quickly find a dupe with an overview.
Comment: Follow this answer: http://stackoverflow.com/a/304896 This will also make you program double-click-able.
Comment: whats shebang??
Comment: https://en.wikipedia.org/wiki/Shebang_(Unix)
Comment: got it thx dudes
Comment: @BitcoinAustria if (either) one of the answers solved your problem, would you consider accepting it, a.o. for clarity reasons? (The big "V" below the up/down arrows). It also prevents the question from re-appearing as "unanswered".
Answer: How it works (examples for python2, for python3, replace all occurrences of python by python3):

python /path/to/script.py

works if file is either executable or not
shebang (#!/usr/bin/env python) in the head of the script is good practice, but not needed

/path/to/script.py

works if script is executable
shebang is needed (#!/usr/bin/env python)

script.py

works if script is in $PATH
script needs to be executable
filename needs to have extension
shebang is needed (#!/usr/bin/env python)

script

works if script is in $PATH
script needs to be executable
filename should have no extension
shebang is needed (#!/usr/bin/env python)

A bit more information: precedence of command, shebang or extension?
The shell can get its information on how to run a script from two sources (in order of precedence):

The language information in the command: python

How do I run Python code as a script?


What are "Shrub Worms"?

Question: There's a mission goal to "wipe out 20 shrub worms in one game." It's only worth one point, so it shouldn't be hard.
I can't for the life of me figure out what a shrub worm is, and after playing a lot of games,** I've never had it tell me that I got more than 5 or so.  Clearly I need to target something specifically, but I have no clue what.
Where do they live and what do they look like?
** I sort of hate this game, but am engaged in a competition that I'd hate losing even more.
Answer: apparently it's those tree looking thing that hide under shrubs and shoot balls at you (although they look like poison shooting trees to me.. )
Comment: You nailed it.  I was sure this was wrong when I read it, because the numbers seemed off from my tests, but I was lumping all things that shoot together, and some are those dragon things.

What are "Shrub Worms"?


Docker Ubuntu PATH won't save

Question: I am using a Ubuntu image (Ubuntu 20.04). Essentially, I am trying to modify my PATH permanently so that every time I start the container I don't have to manually edit the PATH to find the new items I have installed. However, no matter what I do I am unable to make the change permanent. I have sunk some considerable time into the image, so I would very much like to find a solution so I don't have to rebuild the whole thing.
Here is the shell information
<code>#ps -p $$
  PID TTY          TIME CMD
    9 pts/1    00:00:00 sh

# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

# PATH=$PATH:/kraken
# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/kraken

#. ~/.profile
</code>
Now when I restart the container:
<code>#echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
</code>
Basically, the PATH was not saved. I have been through so many blogs and stack and I can't find anything that sticks. Any help would be really appreciated.
Comment: Can't you create your own image based on ubuntu, but with the expected path ? If I understood correctly, you changed the path inside the container and you want to persist this state. I think that it would be easier to start the container with the correct path.
Comment: @Fabien Thanks for the response. I don't believe this would work though. The kraken directory is not part of the original image. its the path where I installed the new software, so I can't create the PATH without creating the directory first
Comment: Then you need to create the directory in the image definition (in the DockerFile). You'll find a lot of resources on internet that will explain how to write a DockerFile. But the idea is that once your container is running, everything should be in the desired state. This is how you'll be able to launch several containers in parallel, all of them with the desired state.
Comment: @Fabien is it possible to edit the docker file with an already built image. It seems kind of silly that you simply can't add a PATH variable permanently.
Comment: The idea is that a container is ephemeral. You could have several containers, based on the same image, running at the same time. Imagine that you define different path values in each of them, then you start another container, which path value will be the one to use?  You can base your DockerFile on an existing image, like the one with Ubuntu and add the command to create the kraken directory (mkdir), copy what's needed inside this directory and then add it to your path with the env command. But if your question was to generate a DockerFile from a running container, I don't think so.
Answer: If you want that a container starts with a predefined path, you have to write a DockerFile to describe your expectations.
You could try with a DockerFile that looks like this :
<code>FROM ubuntu:20.04
COPY kraken /kraken #If you have some content to put in the kraken dir on your Docker instance, use mkdir -p /kraken otherwise
ENV PATH="/kraken:${PATH}"
</code>
Changing the path directly in the container at the runtime is not a solution if you want to keep the value for future containers. Docker containers are designed to be ephemeral and scalable.

Docker Ubuntu PATH won't save


How to show full date and time in Nautilus/Files 3.6+ list view?

Question: The list view of Nautilus 3.6 shows the dates files were modified in a variety of ways: the hour and minute if modified on the current day, and the month and day if modified during the current year, and the year tacked on if modified during a previous year. I would like to see the entire date and time consistently on all the files (e.g.: Sat 20 Apr 2012 01:28:34 PM EDT).
I had this set up before, but I can't figure out how to do so with version 3.6. I did find this question, but the answers no longer apply to Nautilus 3.6: How to change the date format in Nautilus list columns?
How can I do so in Nautilus 3.6+?
Comment: the date-format key in gsettings was removed by this commit: https://git.gnome.org/browse/nautilus/commit/libnautilus-private/org.gnome.nautilus.gschema.xml.in?id=73465be3671ae572ba744d36b055fda3cb210db7 which belongs to this bug report: https://bugzilla.gnome.org/show_bug.cgi?id=676898
Comment: A link to a "bug" asking that the functionality be restored: https://bugzilla.gnome.org/show_bug.cgi?id=699055
Comment: @becko Ubuntu 16.04 ships with Nautilus 3.14. It is not fixed in that version. I have not tested 3.16.
Comment: Looking at the settings on precise and raring they are identical so I am assuming it is a feature removed from nautilus there maybe a plugin or script that can re-add it though.
Comment: Happening to me on v3.14.2. A person named Carlos commented in https://goo.gl/AE7FRA that this is fixed in nautilus v3.16.
Comment: @AlikElzin-kilaka Can anyone confirm whether this was fixed or not? In the Nautilus that ships with Ubuntu 16?
Comment: Switch to Thunar.
Comment: What about now? Any fixes on this?
Answer: You can get back the full date by recompiling nautilus:
sudo apt-get build-dep nautilus
sudo apt-get install quilt
export QUILT_PATCHES=debian/patches
apt-get source nautilus
cd nautilus*
quilt new 999_full_dates.patch
quilt edit libnautilus-private/nautilus-column-utilities.c

Change line 77 from
"attribute", "date_modified",

to
"attribute", "date_modified_full",

Rebuild and install modified package:
quilt refresh
fakeroot dpkg-buildpackage
cd ..
killall nautilus
sudo dpkg -i nautilus_*.deb
nautilus &

As always, you have to perform these steps every time there is an update for nautilus in Ubuntu.
Now, a full analysis of the problem:
The actual patch which caused this change is this one.
The function nautilus_file_get_date_as_string gains an extra gboolean parameter "compact" - when true the abbreviated date is returned.
This function is never called directly - it is accessed through the wrapper function nautilus_file_get_string_attribute_q. This function takes attribute parameters like "date_modified". To accommodate the new signature of nautilus_file_get_date_as_string a new attribute is added "date_modified_full". After this change, any code in nautilus which uses the file date string will get the abbreviated date.
Finally, the file properties dialog is updated to use "date_modified_full" attribute.
So in order to have nautilus display the full date in list view, it is only necessary to change one line of code: in libnautilus-private/nautilus-column-utilities.c, line 77 from "date_modified" to "date_modified_full".
A slightly more useful patch could add a new column type which would show the full date, making this an optional feature, and only add 10 lines of code.
Comment: This is why I love open source - when the developers go crazy, I can fix it myself.
Comment: Is this currently still the only way to handle this issue?
Comment: @AlistairBuxton Have you tried submitting the second patch to the Gnome developers? It would be great if they could at least give us a choice instead of keeping the full date unavailable…
Comment: I no longer use Nautilus and I suggest you do the same.
Comment: Has this been fixed in more recent versions (so that I don't have to recompile)?
Comment: What about now? Any updates? Ubuntu is dropping Unity in favor of GNOME, sure some things have changed.
Comment: This is why I love open source - people like you can fix things when developers go crazy. Thank you!
Comment: One minor downside: now if you type home into the dash the home folder it doesn't show up. Typing the username still works though. Not sure why this is, but it's a pretty minor issue.
Comment: It doesn't show up for me either. I have an unpatched nautilus installed. I don't see how this change could cause a difference in the dash. Can you test with unpatched nautilus please?
Comment: Yeah, you are right, it doesn't show up for me now. I now wonder if it ever did in 13.04? Not a big deal, but odd.
Answer: This blog post shows a much easier solution. It is based on creating an extension which can be selected as an alternative "modified column". Tested under 16.04.

gedit ~/.local/share/nautilus-python/extensions/longdate.py

Use this code (always copy code you trust):
#!/usr/bin/env python

import os
import urllib
import datetime
from gi.repository import Nautilus, GObject

class ColumnExtension(GObject.GObject, Nautilus.ColumnProvider, Nautilus.InfoProvider):
    def __init__(self):
        pass

    def get_columns(self):
        return (Nautilus.Column(
            name="NautilusPython::Longdate",
            attribute="longdate",
            label="Longdate",
            description="Get long date"),)

    def update_file_info(self, file):
        if file.get_uri_scheme() != 'file':
            return

        filename = urllib.unquote(file.get_uri()[7:])
        statbuf = os.stat(filename)
        formatteddate = datetime.datetime.fromtimestamp(statbuf.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
        file.add_string_attribute('longdate', str(formatteddate))

chmod +x ~/.local/share/nautilus-python/extensions/longdate.py

sudo apt install python-nautilus

nautilus -q and nautilus . to restart Nautilus and see if it properly loads the extension.

Select the new "Longdate" column in the list column preferences.

The result will look like this:
Comment: First install nautilus-python: `sudo apt-get install python-nautilus`
Comment: Thanks a lot - it seems to work in Disco - Ubuntu 19.04 ! But you can not sort by Longdate. Unfortunately I can not fix that myself. Great job anyways. As @Alistair Buxton  said: This is why I love open source - when the developers go crazy, I can fix it myself. Well, with your help! THX.
Comment: This isn't working on Nautilus ("Files" 3.10.1) on Ubuntu 14.04.  When Nautilus is started from command line, it says `Nautilus-Share-Message: Called "net usershare info" but it failed: 'net usershare' returned error 255: net usershare: cannot open usershare directory /var/lib/samba/usershares. Error No such file or directory` Please ask sysadm to enable user sharing.  Then six times `** (nautilus:21161): CRITICAL **: nautilus_menu_provider_get_background_items: assertion 'NAUTILUS_IS_FILE_INFO (current_folder)' failed`.  The would-be new column doesn't show in the choices.
Comment: Thanks ! Works for me under Bionic (18.04.4 LTS), Nautilus 3.26.4 and nautilus-python 1.1-6.
Comment: [Here](https://gitlab.gnome.org/GNOME/nautilus/-/issues/949#note_612911) is another solution you should only use if you read it or trust it.
Comment: Even though you can't sort by Longdate, you can still show the useless Modfied column and sort by that.
Comment: Ubuntu 22: the package was replaced by `python3-nautilus` and `unquote` was moved under `parse` - so you need to do `urllib.parse.unquote` instead of just `urllib.unquote`, (+ `import urllib.parse`) otherwise still works :-) didn't figure out the sorting yet... Also it doesn't seem to work in the Icon View Captions. For sorting I just display "Modified --- Time" too and sort by that - which effectively sorts this column too :-)
Answer: For those using trusty & not wishing to compile I've set up a test ppa for a patched nautilus. (using Alistair Buxton's patch
The build currently also includes 2 bug fix patches, 1 from trusty-proposed, 1 from utopic.
Additionally there are 3 minor patches that have been tested by me over quite some time & pose no issues.

open with on folders
real file owner name displayed instead of "Me"
File Manager as name of launcher

The 'date-time' patch I've tested a bit, seen no issues. For those inclined to try - if any issue found contact me thru launchpad email.
The "Modified (full)" column can be added thru nautilus in listview > View > Visible Columns..  or thru nautilus > Edit > Preferences > List Columns
https://launchpad.net/~mc3man/+archive/nauty-mods
Read ppa page for info & how to easily revert if need be.
Comment: An unprejudiced request for next time you update the ppa, please consider adding yet another format for the Modifed column; same as `date +'%Y-%m-%d, %T'`
Comment: I can't seem to get this nautilus version installed. `sudo apt-get install nautilus` just concludes that `latest is already installed`. Trying `sudo apt-get --reinstall install nautilus` reinstalls, but the very same that there already is. Do you by any chance have something for e.g. `/etc/apt/preferences.d/` that makes this thing actually get installed, or how else to do it?  (on Trusty)
Comment: @ Hannu, try again, needed to be updated
Comment: `dpkg --list | grep nautilus` showed the `...+date` version. Retried, several times. Only after having rebooted with this version installed, then delved into the Terminal and there after using `nautilus --no-desktop` (unsure if it appeared there) and then `nautilus --force-desktop` I - at last - found the "Modified (full)" option in the list view. Now it seems to be present at all times. **question**: Can the content be modified? e.g. I'd hope as for use of "strftime()" ?
Comment: Hmm... might it be `LC_TIME=...` that specifies the format?
Comment: @ Hannu, no clue as to why you found the list view option so 'hard' to find, no such issues here. As far as modifying,  well download the debian.tar.xz file from ppa, you'll find the date-time.patch inside the patches folder, have at it.
Answer: Nemo is a fork of Nautilus that includes Creation date and a button for Ctrl+L.
sudo apt install nemo

To replace Nautilus for Documents links etc.:
xdg-mime default nemo.desktop inode/directory application/x-gnome-saved-search

That updates your mime settings:
$ cat ~/.config/mimeapps.list |grep inode
inode/directory=nemo.desktop
inode/directory=exo-file-manager.desktop;
$ cat /etc/gnome/defaults.list |grep inode
inode/directory=org.gnome.Nautilus.desktop

Comment: how do i make it the default file manager?
Comment: @Michael I've updated my answer.
Comment: I have nemo on one of my devices, great usability, but terrible RAM issues - always check from time to time and restart it (and nemo-desktop too if you have it), I mean like GBs... :-)


How to count percentage of certain values in column in group?

Question: I have a dataframe:
id       is_good
a1        1
a1        1
a1        0
bb        1
bb        0
bb        0
bb        0

I want to count percentage of 0 and 1 for each id. So desired result is:
id       is_good_perc
a1        0.67
bb        0.25

How to do that? What should I do after groupby("id")?
Comment: Does this answer your question? [Pandas percentage of total with groupby](https://stackoverflow.com/questions/23377108/pandas-percentage-of-total-with-groupby)
Comment: ``df.groupby('id', as_index=False)['is_good'].mean()``
Answer: General case:
df.groupby("id").is_good.value_counts(normalize=True)

# id  is_good
# a1  1          0.666667
#     0          0.333333
# bb  0          0.750000
#     1          0.250000
# Name: is_good, dtype: float64

In your case, because you have binary variables, I'd take advantage of what @sushanth put in the comments and use df.groupby('id')['is_good'].mean().


Object scope while attaching an event listener in javascript

Question: I need to do something like this:
for(int i =0; i< results.length; i++){
    $('ul').append('
'+results[i].name+'
').bind('click',function(){
        doSomething(results[i]);
    })
}

but when the click happens, the object passed to doSomething is undefined. How do I solve this?
Comment: possible duplicate of [Access outside variable in loop from Javascript closure](http://stackoverflow.com/questions/1331769/access-outside-variable-in-loop-from-javascript-closure)
Answer: results[i] is only valid variable at the time machine is inside the for loop, later on, when event handler is triggered, result[i] is undefined.
That's why you need to ensure results[i] gets saved as variable in context of a function.
for(var i=0; i< results.length; i++){
    (function(result) {
        $('
'+result.name+'
').appendTo($('ul')).bind('click',function(){
            doSomething(result);
        })
    })(results[i]);
}

Here's working example http://jsfiddle.net/T9aUq/.
Edit: Actually to make it really work, I had to change the way events are registered - at first, click handler was binded to elements matching $('ul') instead of new li element (since append() function of jQuery doesn't return appended element, but rather sticks to previous scope (which  was ul).
Comment: I think you're missing braces?
`(function(result) {
...
})(results[i]);`
Answer: save your element first!
for(var i =0; i< results.length; i++){
    var element = results[i];
    var li = $('
').html(element.name);
    $('ul').append(li);
    li.click(function(){
        doSomething(element);
    });
}

Comment: This won't work, because just as `i` changes, so does `element`. See the other answer that addresses the issue with closures.
Comment: Your code is broken. For one, there's typo `int` instead of `var`, for two, the resulting handler would always fire `doSomething` function with last element of results array as argument. Check it out here: http://jsfiddle.net/9hTBa/
Comment: To elaborate on this answer; the issue is that `i` is constantly changing.
Answer: I actually ran into this same problem recently... Silly is right, however the variables need some form of encapsulation:
for(var i =0; i< results.length; i++) doThisFirst(i);
function doThisFirst(index) {
    $('ul').append('
'+results[index].name+'
').bind('click',function(){
        doSomething(results[index]);
    })
}

If that doesn't work... Make sure you don't have a loop inside a loop with the same varname for the index:
for (var i = 0; ...) {
    for (var i = 0; ...) {
    }
}

Comment: I'm sorry, I did not realize WTK had posted the answer for this already.


Using source subdirectories within R packages with roxygen2

Question: I would like to use a directory structure within the R folder for the source code of a package. For example, within my R folder I have an algos folder with functions I want to export and document. However roxygen2 by default does not seem to go through the subfolders of the R folder.
I tried to use the @include keyword as follows for a file at `R/algos/algo1.r'
#' @include algos/algo1.r

but without success. Is there a simple way to use subfolder for the R source code?
Comment: no reason, it does not seem to say that one could not use subdirectories within the `R` folder, does it?
Comment: Is there a particularly strong reason you want to go against the [required package structure](http://cran.r-project.org/doc/manuals/R-exts.html#Package-structure)?
Answer: Writing R Extensions has this to say (in Section 1.1.5) about subdirectories under the R directory:

The R and man subdirectories may contain OS-specific subdirectories named unix or windows.

Implied in this is that they can't have other subdirectories other than those two. This is confirmed in an r-devel thread and again later in another r-devel thread.
Comment: that's a really weird limitation, how do i suppose to organize many dozens of functions/files?
Comment: @simplyPTA Support for 'targets' is definitely on the road map, although I haven't yet found time to confer with Will about how to best do this. As for 'golem', that package is obviously specifically targeting conventional packages, but you arguably don't need to it to develop Shiny apps anyway (though I've used it successfully in the past myself).
Comment: What is the reason for this limitation?
Comment: @adam I don't think a reason has ever been given. I'm just guessing, but I imagine it was an implicit requirement based on how some aspect of the build tool was (is?) written.
Comment: @simplyPTA Write ['box' modules](https://klmr.me/box/) instead of packages. 'box' supports hierarchically organised code (amongst several other things that packages don't support) and is essentially a modern module system that replaces packages. Disclaimer: I made it.
Comment: Thank you @konrad-rudolph for the suggestion and for your work, I'm already aware of it. Sadly my last year project must be a `{golem}` package so I haven't found a way to use `{box}`. For the current project, I want to use `{targets}` but again `{box}` doesn't work with it :((( Do you know whether `{targets}` could be supported?
Comment: @simplyPTA I should clarify that there's (as far as I know) nothing in 'box' which prevents its use with 'targets'. However, 'targets' makes some assumptions about how R code is structured (= as packages), so support for modules would have to be added *to 'targets'*. (The same is generally true for 'golem' but, unlike for 'targets', I think being tied to packages makes a certain amount of sense here. Rather than adding support for modules, there should probably be a separate project for Shiny + 'box'. I know that Appsilon has something along these lines.)
Comment: Thank you @konrad-rudolph for the info. Sadly I couldn't use it for past and current projects, but definitely give it a try in the future
Answer: Another straightforward alternative that I've started to use is to simply define related functions within the same .R file and name these files something that unifies the functions. In the example above one could have something like algos.R in the /R folder and within algos.R:
#' @roxygen_header1
#' @export

algo1 <- function(...){}

#' @roxygen_header2
#' @export

algo2 <- function(...){}

I think this makes navigating /R much more intuitive (at least for the developer, but probably for users too)
Comment: There is no `@roxygen` tag, you should use `@section` instead


Cannot declare class PodioItemField, because the name is already in use

Question: I'm trying to use Podios PHP client library to create a new item in a Podio app.
I use the code from their example page but at the moment I try to:
// Create a field collection with some fields.
// Be sure to use the external_ids of your specific fields
$fields = new PodioItemFieldCollection(array(
  new PodioTextItemField(array("external_id" => "my-text-field", "values" => "FooBar")),
  new PodioProgressItemField(array("external_id" => "my-number-field", "values" => 75))
));

// Create the item object with fields
// Be sure to add an app or podio-php won't know where to create the item
$item = new PodioItem(array(
  'app' => new PodioApp(123), // Attach to app with app_id=123
  'fields' => $fields
));

// Save the new item
$item->save();

I get the following error:

PHP Fatal error:  Cannot declare class PodioItemField, because the
  name is already in use in
  /var/www/html/podioproject/vendor/podio/podio-php/models/PodioItemField.php
  on line 0

I don't really understand what the error means so its hard for me to figure out what is loaded wrong and why.
There are other questions on stackoverflow where people answered to change include to include_once. I'm using composer's autoloader though, so that solution doesn't apply
composer.json:
{
    "require": {
        "podio/podio-php": "^4.3",
        "slim/slim": "^3.10"
    }
}

Comment: It must be an issue with namespaces, have you checked using the namespace directly with no use statement?
Comment: I think that this problem comes from the fact, that the file `models/PodioItemField.php` includes many classes: `class PodioItemField extends PodioObject {`, `class PodioTextItemField extends PodioItemField { '`  ... When composer needs a class, then it always loads this class file again and again. This happens for every class which is in this file. And the class `PodioItemField` has already been found before. Solution: Extract all those classes from the file `models/PodioItemField.php` into their own file, e.g. `models/PodioTextItemField.php` .... .
Comment: @RonvanderHeijden But I'm only using composer autoloader and the rest is handled in their client library - so is the error in the client library?
Comment: where is the PodioItemField class defined?, the class not in your question code
Comment: /vendor/podio/podio-php/models/PodioItemField.php. code is at https://github.com/podio/podio-php/blob/master/models/PodioItemField.php
Comment: See this answer. https://stackoverflow.com/questions/38169097/fatal-error-cannot-declare-class
Comment: @lovelace I dont understand your comment? Where do I have a use statement?
Comment: Did you install another version of Podios PHP before this one? You can use the following command to clear the cache: `php composer.phar clear-cache` or if composer is installed globally `composer clear-cache`
Comment: @FranzHolzinger No I didn't. Clearing cache didn't help.
Answer: You are not doing anything directly wrong, the fault lies at the podio-php package.
Since it's declaring multiple classes in the same file, which clashes with how composer autoloader works.
If you take a peek at ClassLoader::includeFile($file) you'll find that it doesn't use an include_once call, but a plain include:
/**
 * Scope isolated include.
 *
 * Prevents access to $this/self from included files.
 */
function includeFile($file)
{
    include $file;
}

And if you take a look at the file where the error happens (PodioItemField.php), you'll see that in there you have the definitions for 19 different classes!

Maybe it would have been a better idea to use an include_once in composer's autoloader? Frankly, I don't know why it uses include instead, but I have to say that having multiple class definitions per file is not generally considered a good or recommended practice in any case. So generally speaking it wouldn't have made a difference.
Your remaining option to use the package is to load it outside composer. Just download the podio/podio-php package and include this in one of your files:
require_once '/path/to/podio-php/PodioAPI.php';

It sucks that the project is not correctly set-up, but it doesn't appear to have been updated very recently. Maybe you could fix it yourself and submit a pull-request! :)


stabilizer of action of a group scheme on a scheme

Question: Let $G$ be a group scheme over a basis $S$, and $X$ be a scheme over $S$. Let $\rho: G \times_SX \to X$ be an action of $G$ on $S$. If $T$ is an $S$-scheme and $x \in X(T)$, then the definition of the stabilizer of $x$ is given as the subgroup scheme of $G_T$ that represents the functor $T' \mapsto \{g \in G(T') \mid g \cdot x = x\}$ on $T$-schemes $T'$.
I have problem understanding this definition. Should the $G(T')$ actually be a $G_T(T')$, since we're defining a subgroup scheme of $G_T$? And how does $g \in G(T')$ (or $G_T(T')$) act on $x \in X(T)$? We only know a priori that $G(T')$ acts on $X(T')$.
Answer: $G(T')$ and $G_T(T')$ can be naturally identified: if $p: G_T = G \times_S T \rightarrow G$ is projection onto $G$, then $h \mapsto p \circ h$ defines a bijection
$$G_T(T') = \textrm{Hom}_T(T', G \times_S T) \rightarrow \textrm{Hom}_S(T',G) = G(T')$$
$G(T') = G_T(T')$ does not act on $X(T)$, but the structure morphism $f: T' \rightarrow T$ induces a map $f_{\ast}: X(T) \rightarrow X(T')$.  To be precise, they should say that the $T'$-points of the stabilizer of $x$ consist of those $g \in G(T')$ which fix $f_{\ast}(x)$.
Comment: Thank you for your answer!


Download a Word doc via PHP creates a different file than download it directly from the URL

Question: There is a Word doc with a known URL. If I point my browser at it, it downloads to my computer. If I try to download it via PHP, it downloads, but with differences. In this case, it mixes up right foot and left foot (RF and LF) all over the place. What is wrong with my PHP code that it downloads a version of the Word Doc different than what my browser gets?
<code>$wordurl = 'https://www.copperknob.co.uk/downloadsheet.aspx?StepsheetID=142209';
$saveFileName = 'sample.doc';
file_put_contents($saveFileName, file_get_contents( $wordurl ) );
</code>
Answer: Maybe the file server has some validations, User-Agent e.g.


Weibel Exercise $1.1.4$ About $\hom(\mathbb{Z}/n, C)$

Question: I am reading Weibel's Introduction to Homological Algebra.  I have come across this exercise:
$$
\text{If $C$ is a chain complex and $H_n(\hom(\mathbb{Z}/n, C)) = 0$, then $H_n(C) = 0$.}
$$
It seems that this is false as stated.  I can take the chain complex
$$
\cdots \stackrel{0}{\to} \mathbb{Z}/5 \stackrel{0}{\to} \mathbb{Z}/5 \stackrel{0}{\to} \cdots
$$
Then the chain complex $\hom(\mathbb{Z}/6, C)$ has all homology groups $0$, since there are no nontrivial homomorphisms from $\mathbb{Z}/6$ to $\mathbb{Z}/5$.  But, all the homology groups of $C$ are $\mathbb{Z}/5$.
Answer: He doesn't write $\mathbb{Z}/n$. He writes $Z_n$, which is the kernel of the degree $n$ differential of the complex $C$, and nothing to do with the integers mod $n$.
Comment: Thanks.  I really dislike that $\mathbb{Z}_n$ is used for $\mathbb{Z}/n$ sometimes.  The exercise is now very straightforward.


java programming regarding inheritance

Question: class student {
    int id = 100;
    String name = "home";
}

class Teststudent1 {
    public static void main(String[] args) {
        student s1 = new student();
        System.out.println(s1.id);
        System.out.println(s1.name);
    }
}

In this code, the Teststudent1 Class is using variable of Class student and gives output 100 and home.
How it can be possible without inheritance?
Comment: There's no use of inheritance here.
Comment: this is because you assigned the vaue id = 100, home sort of defaults..
Comment: Learn the basics before you start asking questions, https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Answer: No inheritance involved. You are using an instance of student (s1) directly. (Note: by convention, class names should begin with an upper-case letter)
Answer: Inheritance has nothing to do with this. You simply access fields of the student class. You can access them because they are "package-private" so can be accessed from classes in the same package.
Comment: I think that you would mean "package-private" .
Comment: @davidxxx Right, package-private is the correct term.
Answer: When you don't provide an access modifier(public, protected, private) - default package level is imposed on the members/class.
Let's review the access modifier to understand it better -
Private - Can accessed only inside the class
Default package level - Can access only inside the same package. Means any class, object or method in the same package can access it
Protected - Can access inside the same package + subclasses in different package
Public - Can access in anywhere.
Now, as you haven't applied any access modifier, by default, it is default package level access and any class, object can access it.
Hence, you can access the members of student class.
Now, try a little experiment, change the access modifier of ID and NAME and run the code like
NOTE : Without extend keyword, you can't have inheritance

java programming regarding inheritance


How to perform an async task before/after opening a screen in android?

Question: Hi I am performing an operation from screen B. After the operation I am showing one alert dialog. Once the user clicks on the OK button in that dialog it will navigates to screen A. It is happening via Intent.
Screen A contains a list. The list is populated via a list activity and an array adapter.
I need to update the list by calling an async task before or after opening the screen A.
How to do it?
Comment: Look into using loaders instead.
Comment: That won't support in 2.2 version right?
Comment: It will. You have to use the support library to do so
Comment: Either you use a loader or AsyncTask you have to update the list before showing it. When you open the Screen A you probably should show a loading spinner, update the data behind the list and as soon as the new data is ready notify the list about it, then hide the loading spinner.
Comment: @dymmeh Instead of going for loader how can I update it?
Answer: The best way to do this is by instantiating your AsyncTask in your onResume() or onCreate() methods. Then, in doInBackground method of AsyncTask class you could load the data you need for listView in some Array. Finnaly, in onPostExecute() you should instantiate your adapter with data you have in array and then assign it to your listView. Something like this:
<code>ProgressDialog pd;
ArrayAdapter<String> adapter;
ArrayList<String> dataStrings;

@Override
public void onResume() {
         dataStrings = new ArrayList<String>();
         pd = new ProgressDialog(context);
         new MyAsyncTask().execute(params);
}

public class MyAsyncTask extends AsyncTask<String,  Boolean, ArrayList<String>> {

    @Override
    protected void onPreExecute( )
    {
        pd = new ProgressDialog(context);
        pd.setTitle(EsCache.instance.getLangItem("LABEL_PLEASE_WAIT"));
        pd.setMessage(EsCache.instance.getLangItem("LABEL_LOADING_DATA"));
        pd.setCancelable(true);
        pd.show();
    }

    @Override
    protected ArrayList<String> doInBackground(String... params) {
        // TODO Auto-generated method stub

               dataStrings = SomeMethodGetData(); // returns data and stores it in list
               return dataStrings;
    }

    @Override
    protected void onPostExecute(ArrayList<String> list) {
              adapter = new ArrayAdapter<String>(context,
                android.R.layout.simple_list_item_1, dataStrings);

              listView.setAdapter(adapter);
      pd.dismiss();
    }

}
</code>
This is just a simplest demonstration, but it gets the job done, it is not much different if you use some custom adapter. You have to be careful though that you don't mixup something and try to change anything that has something to do with UI from doInBackground() :)
I hope that this helps you.


MSDTC fails intermittently

Question: I have a Windows 2003 server where MSDTC is running. I have set it to No Authentication Mode, with allow inbound-outbound settings. My MSDTC works but it fails for the 1st transaction of the day. On immediate another transaction it will start working.
Error is : The transaction has already been implicitly or explicitly committed or
aborted (Exception from HRESULT: 0x8004D00E).
So I started MSDTC tracing, in trace file it shows this :
pid=2144;tid=2528;time=12/02/2011-10:49:39.140;seq=531;eventid=TRACING_STARTED;;"MSDTC is resuming the tracing of long -lived transactions"
pid=2144;tid=2528;time=12/02/2011-10:49:39.140;seq=532; eventid=TRANSACTION_BEGUN; tx_guid=4df1b0cf-26a0-43ba-8f41-965d80f92441;"transaction got begun, description : ''"
pid=2144;tid=3288;time=12/02/2011-10:49:39.140;seq=533 ; eventid=RM_ENLISTED_IN_TRANSACTION; tx_guid=4df1b0cf-26a0-43ba-8f41-965d80f92441     ;"resource manager #1002 enlisted as transaction enlistment #1. RM guid = '4e45a393-b02a-42bf-8f66-62bcb17fee8e'"
pid=2144;tid=4164;time=12/02/2011-0:49:58.390;seq=534; eventid=TRANSACTION_PROPOGATION_FAILED_CONNECTION_DOWN_FROM_REMOTE_TM ;tx_guid=4df1b0cf-26a0-43ba-8f41-965d80f92441     ;"failed to propogate transaction to child node 'DBSERVER' because the connection with the remote transaction manager went down"
pid=2144;tid=4164;time=12/02/2011-10:49:58.390;seq=535; eventid=TRANSACTION_ABORTING;tx_guid=4df1b0cf-26a0-43ba-8f41-965d80f92441;"transaction is aborting"
pid=2144;tid=4164;time=12/02/2011-10:49:58.390;seq=536; eventid=RM_ISSUED_ABORT;tx_guid=4df1b0cf-26a0-43ba-8f41-965d80f92441     ;"abort request issued to resource manager #1002 for transaction enlistment #1"
pid=2144;tid=2528;time=12/02/2011-10:49:58.422;seq=537; eventid=RM_ACKNOWLEDGED_ABORT;tx_guid=4df1b0cf-26a0-43ba-8f41-965d80f92441;"received acknowledgement of abort request from the resource manager #1002 for transaction enlistment #1"
pid=2144;tid=2528;time=12/02/2011-10:49:58.422;seq=538; eventid=TRANSACTION_ABORTED;tx_guid=4df1b0cf-26a0-43ba-8f41-965d80f92441     ;"transaction has been aborted"
pid=2144;tid=3640;time=12/02/2011-10:50:29.437;seq=539;eventid=TRACING_STOPPED;;"MSDTC is suspending the tracing of long - lived transactions due to lack of activity"
I have applied hack of Davy Brion from here, http://davybrion.com/blog/2010/03/msdtc-woes-with-nservicebus-and-nhibernate/
Also set timeout interval to 10 minutes in Transaction Options.
If the server remains idle for a while again the transaction will fail.
Thanks in advance..
Comment: Have you looked at this KB article: http://support.microsoft.com/kb/922430.  It seems **very** similar to your issue.  It looks like you have 2 servers: an app server and a DBServer?  Are the DTC settings the same on both servers?  Is there a firewall between the servers? If you do have a firewall it can sometimes help to trace the activity in the firewall.
Comment: Thank Tuzo. It was the same problem. You kb article helped me out. My problem is fixed.
Comment: Thanks Tuzo, My servers are in LAN and they do not have firewall, though one was in workgroup and another is in Domain. Now I have shifted both of them in Domain. Had never seen this article. I have changed the registry on the server, as per the article. I will post the status if it is fixed or not.  Thanks
Answer: Here is the KB article that helped: 922430
If the MS DTC transaction trace log file contains this data, follow these steps:
<code>Click Start, click Run, type regedit, and then click OK.
Locate the following registry subkey:
HKEY_LOCAL_MACHINE\Software\Microsoft\MSDTC
Right-click MSDTC, point to New, and then click DWORD Value.
Type CmMaxNumberBindRetries, and then press ENTER.
Right-click CmMaxNumberBindRetries, and then click Modify.
Click Decimal.
In the Value data box, type 60.
</code>
This value increases the length of time that the client computer waits for the bind packet response from the server computer. This value is double the number of seconds before the client computer stops the transaction if the client computer does not receive the bind packet response. For example, a value of 60 equals 30 seconds.
Note The value of 60 is only a recommended value. Additional testing on your configuration may be required.
Click OK.
Restart MS DTC.
Note For the slow response scenario, make sure that the ports that are required by Kerberos authentication (UDP 88 and TCP 88) are open when a firewall is involved in the Perimeter Network. The ports UDP 389 and TCP 389 (both for LDAP to find KDC) must also be open.

MSDTC fails intermittently


Which is the best geographical classification?

Question: Usually in classified advertising websites to catalog ads by area is used the category/subcategory system's. Like this:
Region / province / city / district
It's quite understandable for users, but I think it's not so accurate: some cities are nearest to other region than others city in the same region.
Some websites has implemented maps for drawing search areas or the radius from the user's position, but in small devices is not so practical.
There are other solutions to catalog ads by area, can you suggest some reading?
Comment: Living in a town which borders two countries, I often wished apps would work seamlessly across nations, but that differs a lot with context. If I wanted to buy something on Ebay, for instance, I might want to minimize transport costs: Free shipping can come from any country, really, but usually parcels within the same jurisdiction are the cheapest. Fetching the item yourself from the seller, however, will often be easier if it's closer to your home, i.e. the country doesn't matter at all, except maybe for customs and language barriers.
Answer: If I understand correctly, your concern around using a Google Maps "near me" type of map function is based on how the resulting map would appear on a small device. (I'm assuming it would be okay to use this kind of function to solve your problem so long as users could assign a geographic position as a starting point rather than using their own location.) If this is the case, then I would suggest limiting the map scale represented initially based on the viewport size. Small viewport = less area shown. That way users with "unsmart" phones will still get a map, while users with smart phones can easily scale up or down in the manner required by the OS.
Answer: It's probably useful to be able to override any automatic location based systems by allowing users to also enter a 'virtual' location (City / Postcode) which moves the search radius centre point.
(Some friends of mine live on the south side of a large estuary - and routinely use a different location on search to force searches to be be only on their side of the water).