Canvas polygon border is cropped

Question: When I set a line width higher than 1, the line is displayed cropped.
I would like to know how can I display the polygon in that canvas dimensions without being cropped, considering the defined line width.
Thanks in advance!

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var polygon = [
  {x: 178, y: 160}, {x: 124, y: 0}, {x: 265, y: 88},
  {x: 382, y: 0}, {x: 393, y: 118}, {x: 770, y: 178},
  {x: 479, y: 221}, {x: 441, y: 228}, {x: 579, y: 376},
  {x: 309, y: 314}, {x: 197, y: 428}, {x: 183, y: 304},
  {x: 0, y: 324}, {x: 132, y: 240}, {x: 36, y: 152}
];

ctx.strokeStyle = "rgba(46, 139, 86, 1.00)";
ctx.fillStyle = "rgba(156, 205, 50, 1.00)";
ctx.lineWidth = 9;

ctx.beginPath();
ctx.moveTo(polygon[0].x, polygon[0].y);
for( var i = 1; i<polygon.length; i++){
    ctx.lineTo(polygon[i].x, polygon[i].y);
}
ctx.closePath();
ctx.stroke();
ctx.fill();
<canvas id="myCanvas" width="770" height="428" style="border:1px solid #d3d3d3;">
</canvas>
Answer: So you're trying to keep it within the bounds of the canvas? If so you can acheive it using clip then doubling the current lineWidth and filling/stroking at that point, which keeps it within the boundaries of the canvas. The default clip algorithm wont allow points to fill outside of it which allows this to always work for canvas boundaries.
Example below.

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var polygon = [
  {x: 178, y: 160}, {x: 124, y: 0}, {x: 265, y: 88},
  {x: 382, y: 0}, {x: 393, y: 118}, {x: 770, y: 178},
  {x: 479, y: 221}, {x: 441, y: 228}, {x: 579, y: 376},
  {x: 309, y: 314}, {x: 197, y: 428}, {x: 183, y: 304},
  {x: 0, y: 324}, {x: 132, y: 240}, {x: 36, y: 152}
];

ctx.strokeStyle = "rgba(46, 139, 86, 1.00)";
ctx.fillStyle = "rgba(156, 205, 50, 1.00)";

const lineWidth = 9;
ctx.lineWidth = lineWidth;

ctx.beginPath();
ctx.moveTo(polygon[0].x, polygon[0].y);
for( var i = 1; i<polygon.length; i++){
  ctx.lineTo(polygon[i].x, polygon[i].y);
}
ctx.closePath();

ctx.save();
ctx.clip();
ctx.lineWidth *= 2;
ctx.fill();
ctx.stroke();
ctx.restore();
<canvas id="myCanvas" width="770" height="428" style="border:1px solid #d3d3d3;">
</canvas>
Comment: Thank you! It solved my issue ;) I was not aware of that behavior regarding the clip algorithm.

Canvas polygon border is cropped


Console command to respaw cell flora?

Question: I recent found out about the flora despawning bug when you reload a save.
Im in no mood for mods that just replaces problems with different problems.
Is there a command to reset the flora in a cell? Specifically, Solitude.
Answer: As far as I know, there's no command to reset the state of plants. I've researched this like 2 years ago(because I've met this bug as well), sadly there was no commands that respawns plants(and/or ores.)
Fortunately(at least for me, since you aren't going to use mod I think?), I've found a mod that fixes this problem. However:

Q: Will this mod fix stuff I've already harvested?
A: People keep asking this question in the comment thread, and I thought I
had explained how this work pretty well, but apparently not. I'll try
again:
The rule is: stuff you've never harvested before, is automatically
fixed. There is no need to worry about it at all. It just works.
However, stuff you've harvested before is not fixed until you install
this mod and harvest it again.
So for example, if there are 50 plants in an area, but you only ever
harvested one of them, then the 49 of them will be fixed as soon as
you install the plugin and you don't have to worry about them at all.
It is only that one, which you will have to harvest once before it is
fixed. That's why, when you visit an area after installing this mod,
if there are any flora you want to fix, you should harvest them right
away if they have respawned.

Quote from that mod's description, emphasis mine.
I hope it helps.

Console command to respaw cell flora?


Hive: Filtering rows based on a range of Time

Question:
I am new to this forum and this is my first question. i did search for solution on this forum but still unable to get the exact solution. If such a type of question is already answered then my apologies in advance.

Now coming back to my problem. I have a HIVE table "table1" having following columns:

channel_name     string
start_time       string
prog_name        string
cost             double

Below is the sample date from the above table:

BBC      2016-11-24 05:47:02     NEW: Wonder World       191.0
GTV      2016-11-24 21:35:58     NEW: Great Escape       99.0
BBC      2016-11-25 21:43:29     NEW: Wonder World       131.0
GTV      2016-11-25 23:32:56     NEW: STATE OF FEAR      145.0
GTV      2016-11-26 01:30:30     NEW: Great Escape       128.0

I have to find out cost based on filters on UI where user can filter by program name and a range of time from buckets of 0-5, 6-10, 11-15...19-24 etc. I developed below HIVE query where each row should be selected based on the program and the buckets of time filtered by the user. I have to compare on the time part of the entire timestamp value irrespective of the date.

Below is the HIVE query I tried but it is unable to compare and giving error:

SELECT sum(cost)
  FROM table1
  WHERE prog_name='NEW: Wonder World'
  AND (cast(substr(start_time, 12) AS TIMESTAMP) BETWEEN (00:00:00
                                                          AND 05:59:59)
       OR cast(substr(start_time, 12) AS TIMESTAMP) BETWEEN (06:00:00
                                                             AND 09:59:59));

FAILED: ParseException line 1:118 cannot recognize input near ':' '00'
  ':' in expression specification

What is the correct syntax to convert and compare only the time part from the timestamp value? Appreciate any suggestions/pointers for the above query.
Comment: The time intervals make no sense.
Comment: There are total 5 buckets representing 24 hours i.e. '0-6','6-10','10-14','14-19','19-24'. For finding the cost, date is not considered but only time. Thus if start_time for the program "New: Wonder World" is '2016-09-08 12:46:25' and '2016-09-07 21:48:49', both will be considered in the buckets '10-14' and '19-24'. Accordingly the where clause will be substr(start_time, 12) between '10:00:00' and '14:59:59' or substr(start_time, 12) between '19:00:00' and '23:59:59')
Comment: The `OR` is combined from two conditions that acctually create a single interval
Answer: select  sum(cost)   as sum_cost

from    table1

where   prog_name='NEW: Wonder World'
    and substr(start_time,12) between '00:00:00' and '09:59:59'
;

+-----------+
| sum_cost  |
+-----------+
| 191       |
+-----------+

Comment: Thanks man! It works :) just a simple missing single quote and extra round brackets was the problem. And also, we do not even need to cast String to Timestamp data type, HIVE internally does it. This was a great help and saved lot of my time. Other wise I was planning to use case statement to group the rows into each bucket and use a subquery.
Comment: So the below query will give me all the results for entire 24 hours without taking date into consideration, right?

select  sum(cost)   as sum_cost

from    table1

where   prog_name='NEW: Wonder World'

 and

 (substr(start_time, 12) between '00:00:00' and '05:59:59' or substr(start_time, 12) between '06:00:00' and '09:59:59' or substr(start_time, 12) between '10:00:00' and '14:59:59' or substr(start_time, 12) between '15:00:00' and '18:59:59' or substr(start_time, 12) between '19:00:00' and '23:59:59');


Iterative Meets of Posets

Question: Let $(P,\preceq)$ be a poset, where for each element $x \in P$ there finite elements $y \preceq x, y \in P$. Typically, the meet of a set of elements is supposed to be unique, however, I'm going to change that slightly. For a finite set of elements $S$, let $L(S)$ be the lower-bound set of $S$, thus $L(S) := \{x \in P | x \preceq y \forall y \in S\}$. Now, let $Meet(S,0)$ be the maximal of $L(S)$, namely, $Meet(S,0) := \{x \in L(S) | \nexists y \in L(S)\setminus x, x \preceq y \}$.
Then, for each positive integer $i$, $Meet(S,i) := Meet(Meet(S,i-1),0)$. If $Meet(S,i)$ is one element, $z$, then $Meet(S,i+k) = z$ for all positive $k$ as well. Is there a name for this kind of iterative meet? Are there important posets whose have the property that $Meet(S,i-1)$ can have multiple elements but $Meet(S,i)$ is always a single element, for $i > 0$, $|S|=2$?
Comment: No, $\mathrm{Meet}(\{a,b\},0)$ is not $\{a,b\}$, because neither $a$ nor $b$ are lower bounds for $\{a,b\}$. In order to be a lower bound, you must be less than or equal to all elements of $\{a,b\}$, and since $a$ and $b$ are incomparable, **neither** of them is a lower bound for $\{a,b\}$. So $L(\{a,b\})$ is empty, and thus $\mathrm{Meet}(\{a,b\},0)$ is empty as well. Your written definition captures what you say in the comment, but not what you say before its definition in your post, which say "the upper bounds of $L(S)$".
Comment: Meet(S,1) = Meet(Meet(S,1),1) does not define Meet(S,1).
Comment: In general, in a poset, you can't just take meets or joins or arbitrary sets of elements; for starters, meets and joins are only defined for **lattices**, not arbitrary posets; and second, they are only defined for pairs of elements (and inductively for finite subsets of elements).
Comment: @ArturoMagidin updated to make things finite/countable to better reflect what I meant
Comment: Your $\mathrm{Meet}(S,0)$ is the set of maximal elements in the set of lower bounds for $S$. For arbitrary posets, it is possible for this set to be empty even if the set of lower bounds is not; your condition of finiteness excludes that, but now it is easy to construct posets in which the set shrinks by any amount you care to specify ahead of time (ncluding starting at $n$ and going to empty in one step). However, note that this process will *not* agree with what you may think of as a "meet" (cont)
Comment: (cont) For instance, if $\mathrm{Meet}(S,0)$ has more than one element, then none of those elements are lower bounds for the set itself, so $\mathrm{Meet}(S,1)$ will, if it contains any elements, contain only elements strictly smaller than elements in $\mathrm{Meet}(S,0)$. And so at each step you are going "further away" from your original $S$, with more and more things in between the elements you have and the elements of your original set $S$.
Comment: I think (I'll try to work it out later) that if at any stage $\mathrm{Meet}(S,i)$ has more than one element, then all those elements are removed in the next iterative set; and if it has a single element, then the process just repeats the set itself. So you will either end up with the empty set or a unique element.
Comment: I don't see how you'd end up with an empty set
Comment: You end up with the empty set for instance if you have the poset $\{a,b,c,d\}$, with $a\leq c,d$, $b\leq c,d$, and $S=\{c,d\}$. After one iteration, you get $\{a,b\}$. But this set has no lower bounds, so the next step is empty.
Comment: P.S. Your definition of $\mathrm{Meet}(S,0)$ is **not** "the upper bounds of $L(S)$. The upper bounds of $L(S)$ would be $\{x\in P\mid \forall y\in L(S) (y\leq x)\}$. Your definition is that it is the set of maximal elements in $L(S)$.
Comment: In that case, $Meet(\{a,b\},0)$ is simply $\{a,b\}$. I do not wish for the upper bound, but simply the elements of $L(S)$ which are not less than another element in $L(S)$, which I believe I properly defined above
Comment: Don't call the  "largest", call them what they are called: **maximal** elements.
Comment: alright thanks, sorry I've never had formal learning in order theory.
Answer: Let $(P,\leq)$ be a poset. If $S\subseteq P$, then $x\in P$ is a lower bound for $S$ if and only if $x\leq s$ for all $s\in S$.  An element $x\in S$ is maximal in $S$ if for all $y\in S$, $x\leq y\implies x=y$; and dually, $x\in S$ is minimal in $S$ if for all $z\in S$, $z\leq x\implies z=x$. An element $t\in S$ is a minimum for $S$ if $t\leq s$ for all $s\in S$, and a *maximum for $S$ if $s\leq t$ for all $s\in S$. Finally, an element $x\in P$ is the infimum of $S$ if $x\leq s$ for all $s\in S$, and if $y\leq s$ for all $s\in S$, then $y\leq x$. Dually the supremum of $S$ is an element $x\in P$ such that $s\leq x$ for all $s\in S$, and if $s\leq y$ for all $s\in S$, then $x\leq y$.
So, your $L(S)$ is the set of lower bounds of $S$, and $\mathrm{Meet}(S,0)$ is the set of maximal elements in $L(S)$. Then you look at the lower bounds of this set, and take the maximal elements of that, etc.
We are assuming that your $P$, even if not finite, has the property that for every nonempty subset $S$, $L(S)$ is finite (since you are asking that each element have a finite set of lower bounds, and $L(S) = \cap L(\{s\})$ with the intersection running over all $s\in S$). That ensures that every element in $L(S)$ is less than or equal to a maximal element, and that $L(S)$ either has a maximum, or else has two or more maximal elements.
If $L(S)$ has two or more maximal elements, then $\mathrm{Meet}(S,0)$ is an antichain: a set in which no two elements are comparable. To see this, note that if $x$ and $y$ are distinct maximal elements of $L(S)$, then they must be incomparable: for if $x\leq y$ then $x=y$ (since $x$ is maximal), and likewise if $y\leq x$ then $y=x$ because $y$ is maximal.
Now, here's the thing: if $S$ is a set, $x,y\in S$, and $x$ and $y$ are incomparable, then neither $x$ nor $y$ are in $L(S)$: for if $z\in L(S)$, then $z\leq x$ and $z\leq y$; and since $x\nleq y$ then $x\notin L(S)$, and similary $y\nleq x\implies y\notin L(S)$.
That means that if $\mathrm{Meet}(S,k)$ has more than one element, then none of them can be in $\mathrm{Meet}(S,k+1)$: for none of them are in $L(\mathrm{Meet}(S,k))$, and hence none of them are maximal in $L(\mathrm{Meet}(S,k))$.
Now, after your first step, you have a subset of $L(S)$. If this subset has more than one element, then in your next step you will get a subset of $L(S)-\mathrm{Meet}(S,0)$. If this set has more than one element, then your next step will yield a subset of $L(S) - (\mathrm{Meet}(S,0)\cup\mathrm{Meet}(S,1))$; etc.
Thus, you start with a finite $L(S)$. And at each step you get either (i) the empty set; or (ii) a singleton; or (iii) you get more than one element, and in the next step you will get a subset of an ever-shrinking finite set. That means that you will eventually get a single element, or you will get the empty set.
Yes, the empty set is possible: if $P=\{a,b,c,d\}$, and the only relations in addition to the reflexive one are $a\leq c$, $a\leq d$, $b\leq c$, and $b\leq d$, and we let $S=\{c,d\}$ then the set of lower bounds is $\{a,b\}$, both of which are maximal in $L(S)$. So $\mathrm{Meet}(S,0)=L(S) = \{a,b\}$. But now, neither $a$ nor $b$ are in $L(\{a,b\})$ (and neither are $c$ and $d$, of course), and in fact $L(\{a,b\})$ is empty, and so $\mathrm{Meet}(S,1)=\varnothing$.
On the other hand, if you get $\mathrm{Meet}(S,k)$ a singleton, then $\mathrm{Meet}(S,k+1)=\mathrm{Meet}(S,k)$, for the element itself is a lower bound and is, by construction, the maximum of the set of lower bounds.
So the only two possible eventual outcomes are: you will reach the empty set, or you will reach a singleton.
However, a singleton is not necessarily an object you may want to call the meet of $S$. For instance, consider the following poset: $P=\{a,b,c,d,e,f,g,h,i\}$.
Now, I'll give you the least order relations (no element between the two I list, extend transitively, add the reflexivity):

$c\lt a$, $c\lt b$;
$d\lt a$, $d\lt b$;
$e\lt a$, $e\lt b$;
$f\lt c$, $f\lt d$, $f\lt e$;
$g\lt d$; $g\lt e$;
$h\lt c$; $h\lt g$
$i\lt h$; $i\lt f$.

All elements except $a$ and $b$ are less than or equal to each of $a$ and $b$. I can't draw a diagram here (I would normally use xymatrix which I believe is not MathJax supported), but you should try drawing an order diagram for this to see how it looks. I'm not sure what I would call "the meet of $\{a,b\}$", but your process yields the minimum of $P$, even though there are lots of other elements that are less than or equal to all of $a$ and $b$.
Indeed, take $S=\{a,b\}$. then $L(S) = P\setminus\{a,b\}$, and the maximal elements of $L(S)$ are $c$, $d$, and $e$. So $\mathrm{Meet}(S,0) = \{c,d,e\}$.
Now, the lower bounds of $\{c,d,e\}$ $f$, $h$, and $i$; $g$ is not, becase $g\not\lt c$. The maximal elements among them are $f$ and $h$, so $\mathrm{Meet}(S,1) = \{f,h\}$.
And now $L(\{f,h\})= \{i\}$, so the process terminates.
If you remove the relation $i\lt f$, then $L(\{f,h\})$ is empty, and you get the empty set, even though you still have that $i$ is less than or equal to $a$ and $b$ (and $c$, $d$, $e$, $g$, and $h$; everything except for $f$, in fact).
So I don't think thar your process captures what you want it to capture; you can define posets in which the process just keeps going "further down away from $S$" at every step, and ends in either the empty set or a singleton, as you wish.
Note that if $L(S)$ has a minimum, then the process will not end with the empty set, but it could not end until you get to the minimum... or it could end arbitrarily "above" the minimum (if you have a "choke point" between the minimum and the set $S$, for example).
So I suspect that this idea does not capture what you want it to capture, and so I would be surprised if it has a formal name.

Now, the meet of two elements is usually defined to be their greatest lower bound. A poset in which any two elements have a meet is called a lower semilattice. In a lower semilattice, any nonempty finite subset has a greatest lower bound; if in addition every infinite subset also has a greatest lower bound, we say that the poset is a **complete* lower semilattice. The dual concept for least upper bounds is the join, and you get upper semilattices and complete upper semilattices. If you have both least upper bounds and greatest lower bounds, and they satisfiy the absorption properties, then you get a lattice (and a complete lattice if you also get lubs and glbs for infinite subsets). There is a very rich theory of lattices, of course.
Comment: @ZacharyHunter: I'm not an ordered theorist, so I don't know if it has a name. But I would certainly not call the result a **meet**; it just doesn't have the properties that order theorists think of when you call something a meet.
Comment: I'm surprised that this doesn't have a name! I thought it was quite natural when thinking about counting unlabeled rooted subtrees, because if there were a fixed finite number of meets that found a common sub tree of several branches, you could potentially get a nice algorithm. (however I don't think that subtrees have that property, I nonetheless was just intrigued by the idea of iterative meets)

Iterative Meets of Posets


Task progress as factor of user completed steps

Question: The use case here is quite simple:

The user has a list of tasks (first image)
Each task has a set of steps (second image - opened in a "drawer" of sorts)
In order for a task to be completed, the user has to mark all of its steps as complete.
The logical progression of the steps - "step 1" has to be completed before "step 2", and so on.
Clicking "Complete" on a Step "enables" the next step, and allows the user to Complete it. Once every step is complete, the task status is set to complete as well.

The doubts/issues I'm having with the current design revolve around:

If user hits "Complete" on a step by mistake, there should be a way for them to edit it after the fact.
If the previous is true, what happens when a user has Step 1 through 4 completed, but needs to revert Step 2 to "Incomplete"(an edge case, yes, but it was brought up in a demo and I need to address it)? The only logical thing to do in this case would be to disable Steps 3 and 4 until the user completes Step 2.

What I'm looking for is:

Some critique/validation/input on the UX/Design.
Suggestions on how to solve issue #2 above.

Thanks!
Answer: Some critique/validation/input on the UX/Design.
Suggestions on how to solve issue #2 above.

In order to get a validation for your design, I would suggest to test it with you actual users. From my side, the design seems understandable.
Maybe you consider, on top of your design, having a different page for each task (If this wasn't already in your mind).
As for the issue #2, if the steps are co-dependent, and the user reverts Step 2 to "Incomplete", I would notify the user that the Steps 3 & 4 will be marked as incomplete too (because ...give some reasoning) or maybe ask them if they should be marked as incomplete (in case that you are not sure). You could have this as an option when you create the tasks so that you can avoid confusion. Take for example Jira: The subtasks are not co-dependent and you can finish the tasks in any sequence that you want.
Comment: Thanks for the feedback, it helps! I did consider having a page dedicated to each task, but accessibility and quickly marking off steps trumped it - I wanted to make sure users didn't have to navigate back and forth between pages on the app. On issue #2, I'm definitely going with a warning message + requiring users to enter a comment prior to completing a step (similar to commit messages being required by git). Cheers and thanks again!


Invalid Date in foreach

Question: I don't understand why one date is good and the rest show "Invalid Date".

const blocksDate = document.querySelectorAll(".roadmap__time");
blocksDate.forEach((block) => {
  const dateString = block.innerHTML;
  const dateBlock = new Date(dateString);
  const currentDate = new Date();
  console.log(dateBlock);
});
1 maja, 2022
16 czerwca, 2022
3 marca, 2022
3 lipca 2022
9 lipca 2021
Comment: seems like it would have something to do with locale but really I'm not familiar with such things. One possibility is that maja is a valid date in a different locale (so it works) and the rest are not recognized (because polish is not the current locale). But I'm not sure that locale is even the right word here.
Comment: @topsail—parsing of unsupported formats is implementation dependent. It should have nothing to do with locale since many hosts have no idea of their location.
Comment: The dupe is not answering the question.
Answer: The reason 1 mar(ca) works is that the Date.parse sees only the first 3 chars and guesses March
Here is a script that converts both ways

const months = ["STY", "LUT", "MAR", "KWIE", "MAJ", "CZE", "LIP", "SIE", "WRZ", "PAZ", "LIS", "GRU"]
const options = {
  year: "numeric",
  month: "long",
  day: "numeric"
};

const blocksDate = document.querySelectorAll(".roadmap__time");
blocksDate.forEach((block) => {
  const dateString = block.textContent.trim();
  const ddmmmyyyy = dateString.split(/[ \/]/);
  let dd, mmm, yyyy;
  if (ddmmmyyyy.length === 3) {
    dd = ddmmmyyyy[0];
    mmm = ddmmmyyyy[1]
    yyyy = ddmmmyyyy[2];
  } else {
    dd = 1;
    mmm = ddmmmyyyy[0];
    yyyy = ddmmmyyyy[1];
  }
  if (!isNaN(mmm)) mmm = months[+mmm-1]
  mmm = mmm.slice(0,3)

  console.log(dd, mmm, yyyy);
  const dateBlock = new Date(yyyy, months.indexOf(mmm.toUpperCase()), dd, 15, 0, 0, 0);
  console.log(dateBlock);
  const plDate = dateBlock.toLocaleDateString("pl", options)
  console.log(plDate)

});
1 Maja, 2022
16 czerwca, 2022
3 marca, 2022
3 lipca 2022
9 lipca 2021
<time class="roadmap__time"> 15/07/2022</time>
marca/2022
Lipca/2022
05/2022
06/2022
lipca, 2021
lipca 2021
Comment: <3
God bless you!
Comment: How change this converts for date as m/Y?
Comment: What do you mean? what is the input you have and expected output?
Comment: I want to convert this code when I am displaying date in format ex. 05/2022.
Comment: I have date format day/month now. I would like to change this code for this format.
My issue:
Uncaught TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
Comment: See update that handles "marca, 2022 ", "marca 2022", "marca/2022" or "05/2022" too
Comment: :/
Uncaught TypeError: Cannot read properties of undefined (reading 'slice')
Comment: Not here. Please give me the HTML you have
Comment:
15/07/2022
Comment: You keep changing the rules!!!
Comment: fixed it. Now also supports normal dates

Invalid Date in foreach


How to start Android SDK manager?

Question: I've installed Android SDK like so:
sudo apt-get install android-sdk

Now what? How do I start anything? Searching for "Android" doesn't show anything in Gnome Activities. What did installing android-sdk even do if there's nothing to run? I do see adb at the command line, but that's all.
Comment: The location of the Android SDK Manager is /tools/android.   From a terminal, change to that directory and type ./android
Comment: Unfortunately, looks like the `android-sdk` package for Ubuntu does not come with any `android` file.
Comment: I don't know what the package includes, but you can download the sdk tools directly from https://developer.android.com/studio/index.html.  From that, you can select which versions you want (for space reasons) to download.
Comment: no sdkmanager to be found anywhere
Answer: Old question, but whatever. I stumbled on the same problem and maybe someone can contribute to make it a bit better for whoever comes next.
The android-sdk manager does not give you anything to start from, if not the basic libraries and few tools to work with Android (like adb).
If you are at this point and don't know what's what, you might want to stop and read a bit more on how the Android development and ecosystem works: using Android Studio (the IDE based on IntellijIDEA) could be a good starting point.
The sdkmanager is (now) part of a different package and it doesn't seem to be shipped through the repos (I guess license issue? or they don't care to package it for debian/ubuntu). You need to download and install it separately from the official android website.
Answer: The way I did it was switching into my directory:
android-studio/bin

Then running the following bash command:
./studio.sh

How to start Android SDK manager?


Web.config transforms not being copied to Azure DevOps artifacts ZIP file

Question: Using Microsoft's documentation plus this answer I am trying to get my Web.Config transform files to be deployed as Azure DevOps artifacts so that I can apply different transforms while publishing builds into different environments.
My goal is to:

Set debug=false for all environments (or remove the attribute entirely, which is seemingly only possible by a transform file)
Change an <appsettings/> value for each deployment environment.

As per the above links, I set my Web.Release.Config file to copy to the output directory:

This is verified in the project file:
<Content Include="Web.Release.config">
  <DependentUpon>Web.config</DependentUpon>
  <SubType>Designer</SubType>
  <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>

When this change is merged to the Master branch (triggering a build and release) I see in the artifacts ZIP file that only the original web.config file from development is there.  No transform files are published to DevOps.

Reading into this further I am aware that transformations have to be prevented in the YAML file so that the <DependentUpon>Web.Config setting can be maintained for a cleaner solution explorer, so have done this also:
- task: VSBuild@1
  inputs:
    solution: '$(Build.SourcesDirectory)\My App\App Project 03.csproj'
    msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PrecompileBeforePublish=true;EnableUpdateable=false /p:TransformWebConfigEnabled=False /p:AutoParameterizationWebConfigConnectionStrings=False /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'
    platform: '$(buildPlatform)'
    configuration: '$(buildConfiguration)'

What am I missing please, or am I going about this all wrong??
Answer: Generally you need the transform config files to be included in the yaml pipeline to determine what kind of environment it's running on (development, debug etc), but there's a certain flag that needs to be set for this to happen, namely TransformWebConfigEnabled in this case it doesn't appear to be properly set which could be a reason for why they aren't being included in the zip file.
Set the flag to true in the msbuildargs and the issue should be solved
An example of the new msbuildargs that would accomplish this could be:

... Other parts...

msbuildArgs: '/p:DeployOnBuild=true /p:WebPublishMethod=Package /p:PrecompileBeforePublish=true;EnableUpdateable=false /p:TransformWebConfigEnabled=True /p:AutoParameterizationWebConfigConnectionStrings=False /p:TransformFile="Web.Release.config" /p:PackageAsSingleFile=true /p:SkipInvalidConfigurations=true /p:PackageLocation="$(build.artifactStagingDirectory)"'

... Continuation

Comment: Could be please clarify a little as `TransformWebConfigEnabled=True` contradicts with [this](https://www.herlitz.io/2020/01/10/web.config-transforms-not-working-in-azure-devops-pipeline/) and [this](https://medium.com/@dvinun/got-web-config-transformation-problem-in-your-azure-devops-953a8f29335b) tutorial to ensure that further transformations using DevOps variables are possible in the release pipelines?
Comment: Alternatively is there any resource where all these parameters/values are documented?  I thought MS Learn would have them against the MSBuild/VSBuild pages but `TransformWebConfigEnabled` is not included


Finding the limit of a sequence 4

Question: I am trying to find the limit of the sequence,
$$f_n(x)=\frac{x^n}{n}$$
for $x\in [0,1]$
I am just wondering if it is $f(x)=0$ because when $x=1$ then $\frac{x^n}{n}=\frac{1}{n}=0$ and when it is $x\leq 1$ the numerator goes to $0$ as $n$ goes to infinity.
Or is there a more mathematical approach to this result?
Comment: Prove that $\forall x \in [0,1]: \displaystyle \lim_{n \to \infty} f_n(x) = 0$
Comment: @DHMO how do I go about that?
Comment: How deep do you need? Do you need to do it epsilon-delta style?
Comment: I was showing that the sequence converges uniformly but first I wanted to find its limit, showing that the sequence converges uniformly is easy but shouldn't I find its limit first?
Comment: The limit is $0$. One way to see it: for each $x$, this sequence is a multiplication of a bounded sequence ($x^n$) and a sequence whose limit is $0$ ($1/n$)
Comment: Why do you need to show that the sequence converges uniformly?
Comment: this is just a part of the question I just wanted clarification why the limit was $f(x)=0$, I just wanted help with the limit part
Comment: @35T41 that makes sense, but I cant take the $x^n$ outside of the limit right? since it involves a n?
Comment: @fr14 He is saying that $\displaystyle \lim_{n \to \infty} \dfrac{x^n}n = \lim_{n \to \infty} x^n \cdot \lim_{n \to \infty} \dfrac1n$
Comment: okay so its a bounded sequence multipled by 0?
Answer: Let $t\in [0,1]$.
Note that $0 \leq t^n \leq 1$, and therefore $0 \leq t^n/n \leq 1/n$. Take the limit and use the sandwich's theorem.
Answer: Yes, in fact the function $x \mapsto 0$ on $[0,1]$ is the uniform limit of the sequence $(f_{n})$. To see this, note that $x \in [0,1]$ and $n \in \mathbb{N}$ imply
$$
\frac{x^{n}}{n} \leq \frac{1}{n}.
$$
Note that $1/n \to 0$; so $f_{n} \to 0$ on $[0,1]$ uniformly.
If you want an epsilon-analysis:
If $\varepsilon > 0$, then there is some $N \in \mathbb{N}$ (say $N := \lfloor \frac{1}{\varepsilon} \rfloor + 1$) ensuring $n \geq N$ implies $1/n < \varepsilon$. So $n \geq N$ implies $|\frac{x^{n}}{n}-0| = \frac{x^{n}}{n} \leq \frac{1}{n} < \varepsilon$ for all $x \in [0,1]$; this shows that $(f_{n})$ converges uniformly on $[0,1]$ to the function $x \mapsto 0$.

Finding the limit of a sequence 4


Reading seperate integers in a line

Question: I have a line of text and integers like this: Text 10 9 8
My code so far reads integers like this:
1
10
109
1098
My Code:
Dim total As String
    For x = 0 To listbox1.Items.Count - 1

        For Each ch As Char In listbox1.Items(x)

            If Char.IsDigit(ch) Then
                total = String.Concat(total & ch)
                listbox1.Items.Add(total)
            End If
        Next
    Next

I want my code to read the integers like this:
10 9 8
Thanks
Comment: Appears to be a duplicate of [this question](http://stackoverflow.com/questions/29905092/reading-more-than-one-integer-on-a-line-in-a-listbox) from the same user.
Comment: @Blackwood I know but this is using a different code
Answer: Try this.
Your Idea was good, you just added the Items.add at the wrong point.
    Dim total As String
    For x = 0 To ListBox1.Items.Count - 1

        For Each ch As Char In ListBox1.Items(x)

            If Char.IsDigit(ch) Then
                total = String.Concat(total & ch)
            End If
        Next
        ListBox1.Items.Add(total)
    Next
End Sub

Comment: then you can close the question
Comment: If this is iterating each character, then how would this work if one of your original numbers was 10. This would show 1,0,9,8 instead of 10,9,8

Reading seperate integers in a line


How am I supposed to climb the wall?

Question: I am bread and I am stuck when trying to climb the wall in the tutorial level.
I want to try one of the approaches where it is like walking. I have no troubles walking. Yet I am having a hard time doing the flip on the wall.
See me fail:

I am playing on the PC using a XBOX 360 gamepad.
Answer: You are not changing the direction of the Nudge / Swing (left analog stick). You have to switch its direction midway at the highest point in order to continue climbing.
Answer: I had a pretty difficult time with the controller, so I reverted to using mouse and keyboard. Changing the camera to be from the side a bit, and using a circular motion (like a big "C") to drag the bottom of the bread around to the top worked really well.
Another option is to swing vs flip -- have one point to anchor you ("1" for example) then you can use the mouse to pivot on that point, then use "4" (for example) to latch on above. It takes some timing, but if you get decent at it, you can move pretty fast. After just a few minutes on the wall, I started using that almost exclusively.

How am I supposed to climb the wall?


How to fix leak in ABS pipe going into cement

Question: I discovered a leak in the drain pipe from my kitchen sink (and dishwasher) as it joins with the main drain in my basement floor.
The leak is at a Y junction - the bottom of the Y is in the slab, one branch of the Y is terminated with a cap (I assume access for cleaning / plumbing problems?), and the other branch of the Y goes into the wall (and up to the kitchen).  The bottom is in the floor, the top is capped off, and the branch goes into the wall.  I don't know the exact angle or diameter.
I can see water bubbling from this 2nd branch (into the wall) when water is draining from the sink.  After some cleanup, it look as though the ABS glue has either cracked, and there is no longer a proper seal - or it's been like this for the last 10 years since the house was built.
In any other plumbing fun, I've outright replaced the parts in question (eg, for the sump pump, I cut the pipe going out of the house, replaced it with removable parts, and put in a new pump, etc.).  Doing so here is much harder because this part is in concrete.
What are the implications if I clean up the source of the leak really well (clean, sand, etc) and be liberal with some silicone glue?  What's the correct way of repairing such an issue?
Thanks!
Answer: The correct way to fix this is to cut some of the pipe out coming from the Y, and replace it with glued-in fixtures.  I don't think silicone would hold and it is certainly not up to code -- epoxy I would have no problem with myself but is also probably not code.  Sand the plastic and make sure it is really clean if you go this route!
If you are inclined to re-glue, you can cut a section out of the pipe -- one cut right at the Y's hub, and another about a foot away.  Then you need to remove the 3/4" that is in the hub, being careful not to damage the hub itself.  This is a huge pain as you can imagine, and I usually use a rotary tool with an aggressive grinding bit to simply carve it out.
Your third option is to replace the Y which might not be as hard as you imagine, depending on the access you have -- just chisel out the concrete surrounding it enough to get a coupling on the pipe.
Comment: The third option is the right one. Concrete is not impossible to cut, chisel and repair, though lots of people start out thinking that way.
Answer: Silicone should work but epoxy would work better.


Multiple Counters(Incrementing Number using JS)

Question: I want to make a multiple counters that will keep on increasing until the limit that is specified inside a dataset attribute is reached and put it inside a div, and I want to see the number increasing on time. I also want it to be a reusable function
I'm stuck in making increase and putting it inside a divs.
Html:

const amounts = document.querySelectorAll('.amount');
      const limits = [...amounts].map(amount => amount.dataset.num)
      const counts = 0;

      function counter() {
        while (counts < limits) {
          counts = counts + 1
          amounts.textContent += + counts +;
        }
      }

javascript, js, html, frontend, vanilla JS
Comment: `amounts.textContent += + counts +;` will not work as you expected
Answer: Here's an example thats fully commented.
I don't quite understand exactly what you'd like to do, but this example has all the pieces you need to create what you're describing.
setTimeout( functionName, time ) allows you to set a timer, the time is calculated in milliseconds (so 1 second is 1000).
I've stored the limits within the attributes of multiple divs and then checked these by cycling through all divs with the class .limit, before comparing their data-limit attribute to that of the counter variable.
Update
Have now used setInerval so that you can start, stop and reset. Everything is commented.

// Create array of limits
limits = [2, 5, 6, 9]

// Create counter
counter = 0

// Create divs for each limit
limits.forEach(function(key, value) {

  // Add class .limit for easy identification
  // Store limit in data-limit attribute
  document.getElementById('limitList').innerHTML += "
" + key + "
";

});

// Counter function
function increaseCounter() {

  // Increase counter
  counter += 1;

  // Display counter
  document.getElementById("displayCount").innerHTML = counter;

  // Get remaining limits
  remainingLimits = document.querySelectorAll(".limit:not(.limit-met)");

  // Check each limit div, skip if limit met class present
  remainingLimits.forEach(function(el) {

    // If limit equals count
    if (el.getAttribute("data-limit") == counter) {

      // Append text
      el.append(" \u2713");

      // Mark as met via class
      el.classList.add("limit-met");

    }

  });

  // Check if there are remaining limits
  if (remainingLimits.length === 0) {

    // Stop the timer if there aren't any
    clearInterval(myCounter);

  }

}

// Start counter by default
var myCounter = setInterval(function() {
  increaseCounter()
}, 1000);

// Reset button
document.getElementById("reset").onclick = function() {

  // Reset counter
  counter = 0;

  // Reset display counter
  document.getElementById("displayCount").innerHTML = counter;

  // Get met limits
  metLimits = document.querySelectorAll(".limit-met");

  // Remove met-limit class
  metLimits.forEach(function(el) {
    el.classList.remove("limit-met");
    el.innerHTML = "";
  });

  // Restart timer
  clearInterval(myCounter); // Pause if already running to prevent double coutning
  myCounter = setInterval(function() {
    increaseCounter()
  }, 1000);

}

// Start button
document.getElementById("start").onclick = function() {

  // Restart timer
  clearInterval(myCounter); // Pause if already running to prevent double coutning
  myCounter = setInterval(function() {
    increaseCounter()
  }, 1000);

}

// Stop button
document.getElementById("stop").onclick = function() {

  // Stop timer
  clearInterval(myCounter);

}
.limit {
  color: red;
}

.wrapper {
  margin: 12px;
  padding: 12px;
  border: 1px solid black;
  border-radius: 4px;
}

.limit {
  margin-left: 12px;
  border-radius: 4px;
  border: 1px solid red;
}

.limit-met {
  color: green;
  border-color: green;
}

button {
  background: red;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  margin: 12px 0px 0px 12px;
}

#start {
  background: green;
}

  <button id='reset'>Reset</button>
  <button id='stop'>Stop</button>
  <button id='start'>Start</button>

    Counter:

0

    Limits:

Comment: what about in vanilla JS?
Comment: The only use of jquery was auto generating the divs rather than any of the comparison/counter logic, but have updated to show only vanilla JS.
Comment: so this will work now, without the script tag of jquery?
Comment: Try the code snippet! Click on `Run code snippet` and you can see it run :)
Comment: the counter is working, but i want multiple counters. i made my question more clear above **please check my html code** . thanks
Comment: Have updated to a much more complex scenario that can be paused, restarted, etc. You dont need multiple counters unless their time interval is different. You should have a single `setInterval` that updates anything that is needed. This has all the pieces you need to create your desired use-case.


Java networking | Streams are working only 1 time

Question: Im working on a little chat program and now i have a huge problem and i can not solve it.
I dont know where the mistake could be, for me the code is right. So i really really need help. I have 2 threads in my server, 1 thread for accepting clients and the other for the streams. And the thread for the streams is not working right. It sends only 1 time a message back to the client and multiple clients are also not working. And there is another strange problem. I can only send 1 message back, if i put the JOptionPane-message called "Sockets empty" in the else statement, without it doesnt work.
Here is the stream thread code:
<code>private static Runnable streamThread = new Runnable()
{
    public void run()
    {
        while(true)
        {
            if(!(socketList.isEmpty()))
            {
                for(int i = 0; i < socketList.size(); i++)
                {
                    try
                    {
                        String key = socketList.get(i);

                        if(socketHashMap.containsKey(key))
                        {
                            Socket connection = socketHashMap.get(key);

                            ObjectInputStream ois = new ObjectInputStream(connection.getInputStream());

                            String response = (String) ois.readObject();

                            ObjectOutputStream oos = new ObjectOutputStream(connection.getOutputStream());

                            oos.writeObject(key + ": " + response);
                            oos.flush();
                        }
                        if(connection.isClosed())
                        {
                            JOptionPane.showMessageDialog(null, "Client closed connection", "Info", JOptionPane.INFORMATION_MESSAGE);
                        }
                    }
                    catch (IOException | ClassNotFoundException e) {
                        JOptionPane.showMessageDialog(null, "ERROR: " + e.getMessage(), "ALARM", JOptionPane.ERROR_MESSAGE);
                        try {
                            connection.close();
                            connection.shutdownInput();
                            connection.shutdownOutput();

                            listClientsModel.remove(i);
                        } catch (IOException e1) {
                        }

                    }
                }
            }
            else
            {
                JOptionPane.showMessageDialog(null, "SOCKETS LEER", "Info", JOptionPane.INFORMATION_MESSAGE);
            }
        }
    }
};
</code>
And if you want to see the complete servercode :
http://pastebin.com/sxGGRnJv
Answer: The documentation for getOutputStream says:

Closing the returned OutputStream will close the associated socket.

And that is the problem. You create an ObjectOutputStream, but don't keep a reference to that object around. As this object gets garbage collected, it will call close() which will close the socket's output stream.
Same problem with the InputStream.
You could, for example, create a class that contains your socket and input and output stream and store that in your map instead of just the socket. That way you can re-use the streams.
Comment: I dont know if i really understand the part with the reference, what do you mean with the object around? Does it mean that i can´t create a second stream from the same socket? So i have to create a reference to the stream and re-use them. I created a new class called connectionClass and created a new instance whenever a client joints. The instance gets the socket and all streams + username. But its not working right, i get everytime a NullPointerException when i try to do something with the connectionClass, that is a sign that nothing is in there.
Comment: Here is the new Connection.class where i store the streams+socket+username : http://pastebin.com/b2Sj3Ytm. Here i create a instance of Connection: http://pastebin.com/udiaVHnT and here i try to do something with it: http://pastebin.com/PAni6KWk
Comment: Do you put the new Connection objects into the list? Also, there is no more output.flush() in your code.
Otherwise it looks okay from what I can see.


is there a solar passive water condenser (from humid air) design anywhere?

Question: i've looked around and i found only two related designs:

active electric water condenser.
solar passive water still (that distill dirty water)

not quite what i was looking for...
Answer: Finely, i've found this product. the closest i came to... although i would like to find a diy design that generates water for adults trees.


How to search multiple file names in Nautilus?

Question: How to search for multiple file names at once in Ubuntu via the GUI? I tried Nautilus but without success.
Comment: I don't know if you will find a easy way to do this in Nautilus, but in terminal you can use this example: `find . -type f \( -name "*.class" -o -name "*.sh" \)`
Answer: Try gnome-search-tool
It's available in the software centre, or via sudo apt-get install gnome-search-tool.
When you run it, rather than enter things to the 'Name contains' box, click on 'Select more options', then the drop down and choose 'Name matches regular expression', then click add.  In the new box that appears, you can use any regular expression to search file names.  If you want file1 or file2, then type file1|file2.
This is someone else's image, but it illustrates the method:

There are a number of options for searching, and regular expressions (regex) are very powerful, googling may find you further examples to try.
The program does not index your files, so if you search a large area, it may take a while.
Integrating with Nautilus:
A Nautilus-script will allow you to launch gnome-search-tool within the current directory.  Simple create a file called Search Here in ~/.gnome2/nautilus-scripts, and put:
#!/bin/sh
exec gnome-search-tool --path=$NAUTILUS_SCRIPT_CURRENT_URI

as the entire file contents.  Then, set the file as executable (under Properties, Permissions).  Now, close all instances of Nautilus, and reopen one.  When you right-click in a directory, there should be a submenu called 'Scripts', under which 'Search Here' appears.  This will open gnome-search-tool in the current directory.
Comment: That was the problem, no regular expressions applicable.
Comment: Sorry, I'm confused.  Do you mean that my answer doesn't solve your problem because there is no applicable regular expression, or that Nautilus doesn't accept regular expressions?

Nautilus does not understand regular expressions, so if you want a GUI search which does, then I have given an example.  If you want to integrate it with Nautilus a bit more, then a script could to so: I'll edit my answer.
Comment: Can we search for multiple file names in `gnome-search-tool`? I have a file that contains names of all files that have to be moved some where else, now there are no regular expression to indicated them. If i will put *.htm it will obviously index all htm files, i want to put all the file names which are different[i.e. cabug.htm grahew.htm killbil.htm so on, nothing regular about them], to search all of them at once or feed the file containing all file names to an command line search utility to index them in one place or `mv` them to specified folder.
Comment: `If you want file1 or file2, then type file1|file2` this method is not working in my system.
Comment: Interesting, it works perfectly for me.  You are definitely typing that into the new box that appears, not the one at the top of the program?
Comment: I got it Frankie but it's just not working in my end:( ![A snapshot](http://i1082.photobucket.com/albums/j375/drofart/Screenshotfrom2013-05-30165255.png)
Comment: ![See this too](http://i1082.photobucket.com/albums/j375/drofart/Screenshotfrom2013-05-30171100.png)
Comment: May it be a bug on my side ?
Comment: You need to select 'Name matches regular expression' from the dropdown _before_ you click the 'add' button next to it.  Then it will create a box which understands regular expressions.  In you second screenshot you are typing in a box labelled 'Contains the text'.


void cannot be converted to boolean if statement error

Question: private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {
        try
        {
            DVD dvd = new DVD(txtTitle.getText(),
                    Integer.parseInt(txtYear.getText()),
                    true);

            if(collection.addDVD(dvd))
                JOptionPane.showMessageDialog(this, "dvd added successfully");

Basically i need to save my dvd collection when it closes down but the if statement gives me the error of void cannot be converted to boolean.
This is the addDvd method
public void addDVD(DVD inDVD)
    {
        dvds.add(inDVD);
        inDVD.setID(nextID);
        nextID++;
    }

the void addDvd method can't be changed because it was given from my teacher...
Comment: When do you want to show a message? Is it required?
Comment: If method is `void` then it can't return a value.
Comment: This is why
To create a dvd we have to click on an add button when we add a child frame pops up and then it has the details that it needs to filled...and then needs to be saved when we click on save button

However we need to make sure that the year is numeric otherwise it will be an error, and if the same dvd already exists then we can't add it since it already exists?
Answer: Why are you trying to test the return result of addDVD()?  You can just do:
collection.addDVD(dvd);
JOptionPane.showMessageDialog(this, "dvd added successfully");

Comment: This is why
To create a dvd we have to click on an add button when we add a child frame pops up and then it has the details that it needs to filled...and then needs to be saved when we click on save button

However we need to make sure that the year is numeric otherwise it will be an error, and if the same dvd already exists then we can't add it since it already exists?
Comment: Well then you need to add those checks to `addDVD()` and have it return a `boolean`.
Answer: Try this:
try {
// do all the work as above
// remove if statement
collection.addDVD(dvd);
JOptionPane.showMessageDialog(this, "dvd added successfully");
}
catch {
// catch the error here
JOptionPane.showMessageDialog(this, "dvd not added successfully");
}

Comment: This is why
To create a dvd we have to click on an add button when we add a child frame pops up and then it has the details that it needs to filled...and then needs to be saved when we click on save button

However we need to make sure that the year is numeric otherwise it will be an error, and if the same dvd already exists then we can't add it since it already exists?
Comment: You can create a function that checks if the dvd already exist. E.g. you can use hashmap   when you add new dvd. Another function for checking if the dvd already added and make this function returns boolean


CSS bottom 0 aligns to outside of div

Question: When I try to fix a div to the bottom of a wrapper div with position: absolute, bottom: 0, the div is aligned to the outside bottom of the div, ending up below and outside it. This means that if the wrapper extends to the bottom of the page that my div's child is not even visible. Any ideas what can cause this?
Comment: Can you had a fiddle of your project or your code ?
Comment: set `position:relative` to the parent div , this may fixed your issue
Comment: Questions seeking debugging help ("why isn't this code working?") **must include** the desired behavior, a specific problem or error and **the shortest code necessary to reproduce it** in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve).
Answer: If i understand your proper than please try this one.
.wrapper {
   position: relative;
}

.wrapper div {
   position: absolute;
}

Thanks.
Comment: The parent div has position relative already, that's why I was confused as to how this behavior can happen
Answer: You have to give position: relative to the parent div and to the wrapper you
should give position: absolute.
Comment: The parent div has position relative already, that's why I was confused as to how this behavior can happen
Answer: Just give parentposition: relative; where you want to adjust that child div

.parent{
    width: 600px;
    height: 400px;
    background: grey;
    position: relative;
}

.child{
    width: 200px;
    height: 200px;
    background: blue;
    position: absolute;
    right: 0;
    left: 0;
    bottom: 0;
    margin: auto;
    color:white
}

   Div At Bottom

Comment: The parent div has position relative already, that's why I was confused as to how this behavior can happen

CSS bottom 0 aligns to outside of div


(jQuery) Selecting document.body instead of Parent Element

Question: This part of code is an answer from this question.
$(document.body).on('change', 'select[name^="income_type_"]', function() {
    alert($(this).val());
});

I Have two questions the first one is.
Is there a performance issue selecting 'document.body' instead of selecting the Parent element of select?
Something like this.
Second question is.
It will be function like '$.live()' when putting Parent element instead of document.body?
$("#IdOfParentHere").on('change', 'select[name^="income_type_"]', function() {
    alert($(this).val());
});

Thanks!
Answer:
Is there a performance issue selecting 'document.body' instead of selecting the Parent element of select?

No. There is no significant difference in performance. Of course it would be a little faster if you put it closer on the DOM, but we are talking about an incalculably small difference.

Second question is. It will be function like '$.live()' when putting Parent element instead of document.body?

$.live does exactly the same thing as $("body").on("click", "selector",
Answer: There could be a performance impact(not much significant though) when attaching event handlers to body instead parent element.
Take a case where you are trying to delegate a click event, what you really want to is to handle dynamically created li elements which are in a static ul element. In event delegation when an event happens inside the attached element that events target will be evaluated against the delegation selector to see whether to trigger the handler. In this case if the event is attached to the ul only events inside the ul has to be tested, but if the hanlder is attached to body all the click in the page will have to be tested.
The live() method attaches the handler to the document object, so yes it will be similar to that.

This method provides a means to attach delegated event handlers to the
  document element of a page, which simplifies the use of event handlers
  when content is dynamically added to a page.
Comment: Your answer is much detailed but somehow, almost a straight sentence. Thanks!


I am watching a java tutorial on youtube and can't seem to find I difference between my HandlerClass and itemStateChaged

Question: I watched the tutorial and in it it says the item listener runs the handler class when an action happens but if that is the case why do we need the itemStateChaged. This is not the complete code by the way.
<code>    pf = new Font("Serif",Font.PLAIN,14);
    bf = new Font("Serif",Font.BOLD,14);
    itf = new Font("Serif",Font.ITALIC,14);
    bif = new Font("Serif",Font.ITALIC + Font.BOLD,14);
    tf.setFont(pf);

    //wait for event to happen, pass in font object to constructor
    pb.addItemListener(new HandlerClass(pf));
    bb.addItemListener(new HandlerClass(bf));
    ib.addItemListener(new HandlerClass(itf));
    bib.addItemListener(new HandlerClass(bif));

}

private class HandlerClass implements ItemListener{
    private Font font;

    public HandlerClass(Font f) {
        font  = f;
    }

    public void itemStateChanged(ItemEvent event) {
        tf.setFont(font);
    }
</code>
Answer: ItemListner is Java Interface with one itemStateChanged(ItemEvent e) method (see https://docs.oracle.com/javase/7/docs/api/java/awt/event/ItemListener.html)
Therefore, every HandlerClass which implements ItemListener has to provide      itemStateChanged(ItemEvent e) implementation.
Using addItemListener(new HandlerClass()) you register your listener for an item.
itemStateChanged() is called when an item has been selected or deselected by the user. The code written in this method performs the operations that need to occur when an item is selected (or deselected).


Connecting to a locally running SignalR .netcore server via android emulator

Question: I have a .netcore SignalR server running locally through ISS express. (https://localhost:44372/secureChat")
I have an Android Emulator running through Android Studio.
For referencing localhost things via the emulator you use the ip 10.0.2.2.
I'm using the microsoft signalR android package: com.microsoft.signalr:signalr
I using the hubConnectionBuilder to connect to: https://10.0.2.2:44372/secureChat
When I attempt to connect I get the following error: java.lang.RuntimeException: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
I've found solutions online but none of them relate to SignalR or socket connections.
Alternatively I also have a website that connects to the local signalR server and when I launch the website locally and then host that inside a WebView in android app, it works fine (webview connected at https://10.0.2.2:3000) , but I'm trying to experiment with connecting directly from Android without the webview.
Does anybody have any idea what I need to do to resolve this issue?
Comment: https://blogs.iis.net/robert_mcmurray/how-to-trust-the-iis-express-self-signed-certificate
Answer: The problem is that your android emulator doesn't trust the self signed certificate of iis express, export the certificate to a file, upload to the emulator and follow this link to add the certificate https://support.google.com/nexus/answer/2844832?hl=en


VBA, Dynamically pickup a date

Question: I have a file I want to pickup from the previous wednesday June 10th. I will be running my code today (Sunday June 14th). However this will reoccur every week.
Is there a way I can make my code dynamic enough to pickup the previous wednesday date?
Here is my code Set wbTarget = Workbooks.Open("C:\extract\Business_Report_20200527.xlsx")
Can I alter that path to dynamically pickup a date?
Thank you.
Comment: You need to pickup the last Wednesday date independent of the calling date, or only if it happens on Sunday? And your example does not keep a name as I would expect. I would think it like 'Business_Report_20200610.xlsx'. Is it something I am missing...?
Comment: Sunday is irrelevant. So each week it would go like 0527, 0604, 0611 and so on.
Answer: Try this:
Dim today As Date
Dim IntervalType As String
Dim FilePath As String
today = Date()
IntervalType = "d"

While Weekday(today) <> vbWednesday
    today = DateAdd(IntervalType, -1, today)
Wend

FilePath = "C:\extract\Business_Report_" + Format(today, "yyyymmdd") + ".xlsx"
Set wbTarget = Workbooks.Open(FilePath)

Comment: 'today', 'IntervalType` and `FilePath` are not objects. I would suggest you to eliminate `Set` in front of them, when allocate values. Otherwise, VBA will return an error... Otherwise, the code looks nice. I will vote it up.
Comment: with sebastians code I get error object required. Now I remove `Set` on FilePath and wbTarget , but now getting an object required on today. How do I go about this?
Comment: I enumerated the variables where Set is inappropriat... Do the same for 'today', too.
Answer: Another way to do it:
Sub Test()
    MsgBox "Last Wednesday:  " & PreviousWednesday & vbCr & _
           "Wednesday prior to 9th June:  " & PreviousWednesday(DateValue("9 June 2020")) & vbCr & _
           "Last Wednesday formatted: " & Format(PreviousWednesday, "yyyymmdd")

    'Your code:
    'Set wbTarget = Workbooks.Open("C:\extract\Business_Report_" & Format(PreviousWednesday, "yyyymmdd") & ".xlsx")
End Sub

Public Function PreviousWednesday(Optional CurrentDate As Date) As Date
    If CurrentDate = 0 Then CurrentDate = Date
    PreviousWednesday = (CurrentDate - Weekday(CurrentDate, vbMonday) + 1) - 5
End Function

VBA, Dynamically pickup a date


Baby Rudin 3.54, Concerning the Definition of Rearrangement of a Series

Question: This theorem has already been asked about, however my specific question, to my knowledge has not.
I hope it will be acceptable if I refer the reader of this question to either here or here for Rudin's proof, since it has already been written up.
Rudin says that for "sequences $(m_n)$, $(k_n)$" the following is "clearly a rearrangement of $\Sigma a_n$.''
$$
P_1 + \cdots + P_{m_1} - Q_1 - \cdots - Q_{k_1} + P_{m_1 + 1}  + \cdots + P_{m_2} - Q_{k_1+1} - \cdots - Q_{k_2} + \cdots
$$
Can anyone tell me, is he saying that $\Sigma a_{n'}$ is a rearrangement of $\Sigma a_n$ where $(a_{n'})$ is defined
$$
a_{1'} := \sum_{i=1}^{m_1} P_i \hspace{1mm}-\hspace{1mm} \sum_{j=1}^{k_1} Q_j,
\quad\ldots\quad
a_{n'} := \sum_{i=m_{n'}+1}^{m_{{n'}+1}} P_i \hspace{1mm}-\hspace{1mm} \sum_{i=k_{n'}+1}^{k_{{n'}+1}} Q_j,
\quad\ldots
$$
for any sequences of integers $(m_n)$ and $(k_n)$? Or is he saying that $\Sigma a_{n'}$ is a rearrangement of $\Sigma a_n$ where $(a_{n'})$ is defined
$$
a_1 := P_1, \quad\ldots\quad a_{n'}
=
\begin{cases}
P_{\ell+1} &\text{ if }\hspace{2mm} \ell\ni a_{n'-1} = P_\ell \wedge \ell\neq m_n\hspace{1mm}\forall n\in\{1,2,\ldots\}
\\
Q_{\ell+1} &\text{ if }\hspace{2mm} \ell\ni a_{n'-1} = Q_\ell \wedge \ell\neq k_n\hspace{1mm}\forall n\in\{1,2,\ldots\}
\\
Q_{k_\ell} &\text{ if }\hspace{2mm} \exists\ell\ni a_{n'-1} = P_{m_\ell}
\\
P_{m_\ell + 1} &\text{ if }\hspace{2mm} \exists\ell\ni a_{n'-1} = Q_{m_\ell}
\end{cases}
$$
Moreover, this only makes sense if $(m_n)$ and $(k_n)$ are strictly increasing sequences of positive integers (although Rudin does not make this specification), is that correct?
Thanks to anyone who is willing to help.
Edit: My suspicion is that the latter of these two is correct, but I would be grateful for a second or third opinion.
Comment: I don't think this proof was one of Rudin's better efforts.  In my view, it obscures the essential idea under a welter of notation.
Comment: Doesn't the construction of $(m_n)$ and $(k_n)$ make them strictly increasing?
Comment: @saulspatz  Rudin wants to prove it all in one shot. Better to prove one thing (really) clearly, say rearrangements can converge to any number, and then state his general theorem without proof...
Comment: I suppose so, yeah, that's a good point. Although, Rudin says that this is "clearly a rearrangement" before constructing $(m_n)$ and $(k_n)$. I think you're right though.
Answer: Rudin is building a rearrangement of the $a_n$ terms via the recursion theorem:

Theorem 1: Let $X$ be a set with $x_0 \in X$ and $\psi: X \to X$ be any function. Then there exist one and only one function $\rho: \Bbb N \to X$ satisfyings
$\tag 1 \rho(0) = x_0$
$\tag 2 \forall n \in \Bbb N, \; \rho(n+1) = \psi(\rho(n))$
See, for example, the wikipedia article recursive definition.

You won't find recursion in the index. Apparently, for Rudin, building sequences via recursion is so routine it doesn't deserve mention. If you want to learn it, read his proofs!
You will notice that in the body of the proof you won't find any attempt to 'map things out' - the recursion machine implicitly takes care of things at 'run time'.
I suggest the serious student rework the proof for three cases:
Case 1: For all $n$, $\alpha_n = \alpha \in \Bbb R$ and $\beta_n = \beta \in \Bbb R$ and $\alpha = \beta$.
Case 2: For all $n$, $\alpha_n = \alpha \in \Bbb R$ and $\beta_n = \beta \in \Bbb R$ and $\alpha \lt \beta$.
Case 3: For all $n$, $\alpha_n = -n$ and $\beta_n = +n$.
Try working on Case 1 by first thinking it through and working out your ideas on some scrap paper.
Notice that in Rudin's proof he wants $\beta_1 \gt 1$. No doubt he needs that to build (seed) his machine. It is a red herring, but if you understand that you will be in business.
Finally, to really understand the theorem you can use Rudin's proof to get the main ideas and then build your own recursion machine(s).
Comment: I like that a lot. I'm going to try and take your idea and run with it, thank you so much. I hope to put together a proof of the kind you're describing within the next few days. By the way you're 100% right about Rudin not saying what he is doing. To be honest, I always figured that he was outlining a proof by induction of the existence of a sequence when, in actuality, he was defining a sequence recursively.
Comment: @ThomasWinckelman The definition of a rearrangement makes it appear that you have to set out and define $k_n$ so that ${a_n}' = a_{k_n}$, but really you just want to build ${a_n}'$, with the corresponding $k_n$ being implicitly built at the same time; you can throw $k_n$ away.
Comment: @ThomasWinckelman Yes, I've mixed up induction with recursive definition at times.
Comment: @ThomasWinckelman Also, listen to to Rudin in Example 3.53 and finish it up. Even though here you can explicitly/upfront describe $k_n$ to get $1 + 1/3 - 1/2 + 1/5 + \dots$, you can also define it with recursion as in Theorem 3.54.
Answer: Looks to me like it's close to the latter option. (As saulspatz commented, $(m_n)$ and $(k_n)$ are constructed to be strictly increasing, so that's not an issue.) The point here is that each of the terms $P_i$ is by definition one of the terms $a_n$, and each of the terms $-Q_j$ is by definition one of the terms of $a_n$, and they each correspond to a distinct term, so a sum of all the $P_i$s and $-Q_j$s is a rearrangement of $\sum a_n$.
The precise definition of the sequence $a'_n$ would be as follows, adopting the convention $m_0=k_0=0$:
$$
a'_n = \begin{cases}P_{n-k_j} &\text{if } m_j+k_j < n \leq m_{j+1}+k_j \\ -Q_{n-m_j} &\text{if } m_j+k_{j-1}<n\leq m_j+k_j \end{cases}
$$
Comment: Thank you I appreciate it!
Answer: for what it's worth, I finally put together a pretty thorough reworking of Rudin's proof.
I'd be happy to receive feedback, but mostly I just thought I'd share in case anyone cares.
Here's a link to the PDF, because I don't know how to make my LaTeX macros compatible with this website (sorry).


modification of extracting age variations using regex

Question:     import re
    s = '99year old 93yo 100 yo 97y.o. and his wife is 93 y.o. 20 y.o  90old 23 year old 29 years old but not 25-year-old and 91year old cousin is 99 now and 90-year-old or 102 year old'
    reg = r'(?:9\d|1\d{2})(?:\s|-)?years?(?:\s|-)?old'
    r1 = re.findall(reg,s)
    r1
    ['99year old', '91year old', '90-year-old', '102 year old']

The following code works well and is taken from extracting age variations using regex
My goal is to extract the elements listed in r1 plus any digit above 90 ending with y.o. or yo. My desired output is
 ['99year old', '93yo', '100 yo', '97y.o., '93 y.o.',  '91year old', '90-year-old', '102 year old']

I have tried to alter reg as follows but this doesn't quiet work
reg = r'(?:9\d|1\d{2})(?:\s|-)?years?(?:\s|-)?old(?:9\d|1\d{2})y.o.|(?:9\d|1\d{2})yo'

How do I alter reg to get my desired output?
Answer: I'm guessing that maybe some expression similar to,
\b(?:9\d|1\d{2})\s*-?y(?:ears?)?\.?\s*-?o(?:ld)?\.?\b

might be OK to look into.
Test
import re

regex = r'\b(?:9\d|1\d{2})\s*-?y(?:ears?)?\.?\s*-?o(?:ld)?\.?\b'
string = '''
99year old 93yo 100 yo 97y.o. and his wife is 93 y.o. 20 y.o  90old 23 year old 29 years old but not 25-year-old and 91year old cousin is 99 now and 90-year-old or 102 year old
'''

print(re.findall(regex, string))

Output

['99year old', '93yo', '100 yo', '97y.o', '93 y.o', '91year old',
  '90-year-old', '102 year old']

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Unable to mock Thrift classes in Grails for testing (GroovyCastException)

Question: For unit testing, I need to mock several Apache Thrift related Java classes (THttpClient, TBinaryProtocol, and a generated Client) being used in a Grails service, but have run into several exceptions when using the usual mocking techniques. I created getters in the service (instead of using new operators within the method being tested) which I am mocking. One issue addressed is that the Thrift classes do not have default constructors, so I created a subclass to meet requirements for mocking:
class TestableTHttpClient extends THttpClient {
     public TestableTHttpClient() {
         super("http://example.com");
     }
     public TestableTHttpClient(String url) {
         super(url);
     }
}

I have tried mocking using mockFor() but get a GroovyCastException: Error casting map to MyServiceTests$TestableTHttpClient, Reason: null:
def mockTHttpClient = mockFor(TestableTHttpClient, true)
mockTHttpClient.demand.open { }
mockTHttpClient.demand.close { }
def mockTHttpClientInstance = mockTHttpClient.createMock() // fails

I have tried map coercion with the same GroovyCastException: Error casting map to MyServiceTests$TestableTHttpClient
def mockTHttpClientInstance = [
    open: { },
    close: { }
] as TestableTHttpClient]

I have tried using closures with the same exception as above.
def helperMethod = { assert 1 == 1 }
def helper = [open:helperMethod, close:helperMethod]
def mockTHttpClientInstance = helper as TestableTHttpClient // fails

I made changes on the metaclass, which passed two of the classes, but the last class (Client) I need to return a specific mocked value. Instead, the real method was getting called: TTransportException: No more data available.
def mockTHttpClientInstance = new TestableTHttpClient()
mockTHttpClientInstance.metaClass.invokeMethod = { String name, args -> }
def mockTBinaryProtocolInstance = new TestableTBinaryProtocol()
mockTBinaryProtocolInstance.metaClass.invokeMethod = { String name, args -> }
def mockClientInstance = new TestableClient()
// mockClientInstance.metaClass.invokeMethod = { String name, args -> }
mockClientInstance.metaClass.methodINeedToMockResults = { String name -> true }

def mockMyService = [
    getTHttpClient: { String -> mockTHttpClientInstance },
    getTBinaryProtocol: { TTransport -> mockTBinaryProtocolInstance },
    getClient: { TProtocol -> mockClientInstance }
] as MyService

Any suggestions? I have already read over http://grails.org/doc/latest/guide/testing.html and the Grails books I know of contain very little on testing other than domains and controllers.
Answer: Try to use different mocking frameworks. I recommend Mockito.


Using JQuery to get table values

Question: I have a html table with 4 tablecells:
1: Checkbox
2. label
3. textbox
4. label
Once I click on the checkbox, a jquery function fires, but im trying to get the values next to the checkbox. I have tried below, but nothing works. I know I am close. Any help would be very much appreciated.
$(this).next()
$(this).nextSibling
$(this).nextSibling.childNodes[0]

      <input id="MainContent_check_FLIGHT DECK1" type="checkbox" checked="checked"/>

     Pilot
     <input "type="text" value="86.2" maxlength="10" id="MainContent_input_FLIGHT DECK_weight1" />

     255.0

Comment: could you post your html code, might be easier to follow.
Comment: Values next to the checkbox?
Comment: my answer will work - i kind of guessed your html and got it right
Comment: Are you trying to get the value of the text input when the checkbox is checked?
Answer: $(this).parents('tr').find('label').text()

http://jsfiddle.net/7jnTF/2/
Comment: Why not +1, no one is upvoting today `:)`
Answer: $(this).next('td').html();

or
$(this).next('td').text();

This should work - ( i think ) that you have something like

     <input type=checkbox .... />
     YOU WANT THIS LABEL
     <input type=textbox ..... />
     ANOTHER LABEL

Comment: Why not +1, no one is upvoting today `:)`
Answer: Working demo http://jsfiddle.net/suSkb/
Your case specific demo http://jsfiddle.net/7nyn8/
Please note: classes can have spaces but not id and id should be unique.
Hope it fits your cause :)
Code
$('.hulk').click(function(e) {
    alert($(this).parents('tr').html());
     alert('Lable HTML = > ' + $(this).parents('tr').find('lable').text())
});

further
$('.hulk').click(function() {
    alert($(this).parents('tr').html());
    alert('Pilot here:=> ' + $(this).parent().next().html());
    alert('Lable HTML = > ' + $(this).parents('tr').find('span').text())
});

Comment: I just guessed , that when he said label he meant plain text , I think you and some other answer thought he knew what he said when he said label

Using JQuery to get table values


Effective ways to "Jazz up" and polish the UI of iOS 5 App

Question: I've finished up my first iOS 5 app (and only third iOS app overall) and I'm wondering if anyone out there has any recommendations for adding that touch of class, polish, professionalism, etc. to a plain-vanilla iOS app. I've taken a look at an iOS 5 appearance tutorial but I don't find it extremely helpful. What do you do to add polish to your UI? For example, do you add a logo view in your UINavigationBar? Do you create custom UIKit control backgrounds/images? Do you remove rounded edges from controls? I would especially appreciate any input related to how you use the new Appearance options in iOS 5 to accomplish your UIX goals.
Comment: As a user, I find it nice that the UI on iOS is normalized to some extent. Adding a logo looks nice, but making a completely custom UI for your app may make it look less appealing (at least to me).
Comment: I agree, but as I user too I also find certain apps to look and feel more "polished" than others, and as somebody who is by no means a design expert I can't always pinpoint why I (or others) like these design choices.
Answer: For inspiration, look at the apps featured by Apple in the App store.  Maybe hire an artist or designer familiar with iOS devices and their users (if you are not one yourself).  There seem to be lots of creative ways to potentially "delight" the user, customize things for your specific app's purpose or customer base, but still stay within the spirit of the HIG.
Comment: I can't afford a designer, so I'm looking for some more concrete suggestions... For example, I know there are things I can do in CSS to give a form input control a more "professional" feel, but those things do not always apply on the iPhone/iPad.


Is the world balanced around the number of players?

Question: When I play Don't Starve Together, I always feel like the generated world was made for a single player game.
I usually play with two friends but we usually end up starving pretty soon (20ish days) since we all try to supply on the same sources. Don't get me wrong, we all work together so triple work (farms, beehives, spiders) should equal triple food. It doesn't seem to add up properly since we end up lacking seeds or other basic supplies soon.
I can't imagine if we were to be six players.
 Simply because resources around us get collected more frequently and we start missing  resources very soon.
We are pretty experienced players with all our solo worlds advanced so we know how to survive properly.
The only way I see around this would be to all go separate ways completely far enough to get our little personal world but then again, what is the point of playing in the same world if you play like this.
So, are the world generated with the number of players in mind or does it simply generate a similar world without thinking of how many players will play in it?
Comment: I doubt it, Don't Starve Together is early access for a reason. I'd wait for it to become more mature since the original game was heavily based on being single player.
Comment: I disagree with the off-topic flag for being unreleased. Technically, this game is available publicly through legitimate means. "Early Access" is just another (admittedly good) excuse for "the game isn't finished, but we'll release it anyways".
Comment: @Thebluefish That's what I thought. It's unfortunate since it's at the very core of the multiplayer gameplay but I guess I'll just have to wait and see. I just hope someone can come up with a definitive answer they got somewhere.
Answer: Currently it's the same generation as single player. This is bound to change but as of now, I just set things slightly higher that DON'T reproduce.
There's a huge thread on multiplayer servers here - http://forums.kleientertainment.com/topic/45915-what-makes-a-good-dst-world/
That should help :)


How many ways to lineup 14 candies in a row?

Question: Cindy has 6 identical pink candies and 8 identical green candies. Find the number of ways that Cindy can line up her candies in a row, so that there are exactly four places where a pink candy is next to a green candy. One example is $PPGGGPPPGGGGGP.$
Comment: Let $P$ represent a group of one or more adjacent pink candles and $G$ a group of one or more adjacent green candles. Then we must have $PGPGP$ or $GPGPG$. It is not hard to count each of these separately.
Answer: With inclusion/exclusion we find for positive integers:

There are $\binom71=7$ sums $g_1+g_2=8$.
There are $\binom72=21$ sums $g_1+g_2+g_3=8$.
There are $\binom51=5$ sums $p_1+p_2=6$.
There are $\binom52=10$ sums $p_1+p_2+p_3=6$.

So there are $21\times5=105$ orders of the form $[g_1][p_1][g_2][p_2][g_3]$.
And there are $7\times 10=70$ orders of the form $[p_1][g_1][p_2][g_2][p_3]$.
That gives a total of $$105+70=175$$possibilities.
Comment: Thanks for the answer
Answer: To have four neighboring $P$ and $G$, there are two orderings: $P_1,G_1,P_2,G_2,P_3$ or $G_1,P_1,G_2,P_2,G_3$.
The first orderings are:
$$\begin{align} &4P,7G,P,G,P;\cdots 4P,G,P,7G,P \Rightarrow 7 \\
&3P,7G,2P,G,P;\cdots 3P,G,2P,7G,P \Rightarrow 7 \\
&3P,7G,P,G,2P;\cdots 3P,G,P,7G,2P \Rightarrow 7 \\
&\cdots \\
&P,7G,P,G,4P;\cdots P,G,P,7G,4P \Rightarrow 7. \end{align}$$
Counting rule: note $n(P_1)+n(P_2)=2,3,4,5$, so:
$$\left(\binom11+\binom21+\binom31+\binom41\right)\cdot 7=(1+2+3+4)\cdot 7=70.$$
The second orderings are:
$$\begin{align} &6G,5P,G,P,G; \cdots ; 6G,P,G,5P,G \Rightarrow 5 \\
&5G,5P,2G,P,G;\cdots ;5G,P,2G,5P,G \Rightarrow 5 \\
&5G,5P,G,P,2G;\cdots ; 5G,P,G,5P,2G \Rightarrow 5 \\
&\cdots \\
&G,5P,G,P,6G;\cdots ; G,P,G,5P,6G \Rightarrow 5.\end{align}$$
Counting rule: note $n(G_1)+n(G_2)=2,3,4,5,6,7$, so:
$$\left(\binom11+\binom21+\binom31+\binom41+\binom51+\binom61\right)\cdot 5=(1+2+3+4+5+6)\cdot 5=105.$$
In conclusion, $70+105=175$.


Change Dll loaded with MEF

Question: I'm using MEF and the System.ComponentModel.Composition.dll to load some dll.
I'm doing something like :
AggregateCatalog catalog = new AggregateCatalog(new AssemblyCatalog(Assembly.GetExecutingAssembly()), new DirectoryCatalog(directory));
_container = new CompositionContainer(catalog);
_container.ComposeParts(this);

to import my dll.
After some times, I would like to update my dll but if I try to delete it, I have an access denied, because it's alrealdy used by the program.
How can I release the dll, replace with a new dll and load the dll again ? (without closing the program)
Thanks in advance for your help
Answer: You need to enable shadow copying in the AppDomain, this forces the application to behave similarly to a web app where the executable content is not running from the source location, but a temporary location.
The only problem you have is either

Use an obselete method AppDomain.CurrentDomain.SetShadowCopyFiles() which forces it on the the current domain.  Not advisable as this has been deprecated in favour of:
Use AppDomainSetup.ShadowCopyFiles = "true"; when creating a new AppDomain.  You then need to defer execution of the your assembly in the other AppDomain.  Maybe this form post can help?

I'm not sure you can enable Shadow Copying through application configuration...
Comment: I've tryed many way, but unable to make it working. I had to make my application restard to have the opportunity to update dll :(
Answer: If you try to insert on catalog one Object Assembly like this:
Assembly assembly = Assembly.Load(System.IO.File.ReadAllBytes(Path.Combine(directoryPath, ItemPlugin)));
aggregateCatalog.Catalogs.Add(new AssemblyCatalog(assembly));

You can Delete\Change the file later...

Change Dll loaded with MEF


Search for data.frame indices according to multiple column criteria - how to speed up for large data sets?

Question: I have a large data.frame (50M rows) and need to find indices which match a multiple column criteria.
I made a toy example to illustrate the problem.
I read here that it's faster to search though data.tables than data.frames so I converted data.frame into a data.table object
cases<-c(1,3,5)
women<-c("Julia", "Judith", "Juno", "Jane", "Joanna")
data.df<-data.frame("id" = 1:5, "age" = c(20, 30, 40, 50, 60), "name" = c("Joanna","Joe", "Julia", "Juno", "John"))

library(data.table)
data.dt<-as.data.table(data.df)
setkey(data.dt, "id")

I want the results vector to contain age values of records which pass the multiple column criteria, in this case 20, 40, NA. I search using the for loop (which is probably a silly approach, any tips would be greatly appreciated here)
results<-vector()
for (i in 1:length(cases)){
which_id<-cases[i]
ind<-data.dt[id==which_id & name %in% women, which=TRUE]
if(length(ind)==0){results[i]<-NA}
else{results[i]<-data.dt$age[ind]}
}

This would do on a smaller data set but with 500K records in cases and 50M in data.df it is going to take an excess of 12 hours to run. There must be a simpler way, can anyone give a hint?
Comment: please see this vignette

https://cran.r-project.org/web/packages/data.table/vignettes/datatable-keys-fast-subset.html
Comment: Do you want ```data.dt[J(cases)][name %in% women]```
Comment: After reading the vignette I see that I was using data.tables same way as if I was using data.frame
Answer: If I understand correctly, the OP wants to filter his dataset by id first and then to return age if the name is found in women (and NA otherwise).
Below are different data.table approaches which return the expected result
20 40 NA

for the example case. However, performance may vary for the production dataset.
1. Filtering by id, matching on women
setkey(data.dt, id)
data.dt[cases][name %in% women, Age := age][, Age]

Here, integer matching is used as name has been turned into factor by OP's call to data.frame(). (If name is of type character %chin% could have been used).
To make sure NA is returned in case of no matches, an update in place is used which puts NA by default.
Note that Cole's approach data.dt[J(cases)][name %in% women] would only return a  filtered dataset with 2 rows but not the expected result.
2. Filtering by id, joining with women
This is similar to above but uses a join instead of a match:
setkey(data.dt, id)
data.dt[cases][.(women), on = .(name = V1), Age := age][, Age]

3. Joining with women, then joining with cases
This approach selects the rows where name matches women first (by joining), then it right joins with cases so that each case will have its corresponding entry in the result vector:
setkey(data.dt, id)
data.dt[.(women), on = .(name = V1), nomatch = 0L][cases, age]

Discussion
The OP has pointed out that speed is a concern with a production dataset of 500k elements in cases and 50M rows in data.df. Which of above methods is the fastest for the production dataset may also depend on the number of entries in women.
Without proper benchmarking I am reluctant to recommend one of the methods.
Comment: Hi, thank you for a comprehensive answer. I tried the first approach and it works (how fast it is!) but will check with the other two methods and see which one is the fastest.
Answer: I assume that you expect ind to be either of length 1 or 0 (meaning that the IDs are all different).
Then, you can use {dplyr} to do that very fast:
library(dplyr)
results2 <- data.df %>%
  slice(match(cases, id)) %>%
  mutate(res = ifelse(name %in% women, age, NA)) %>%
  pull(res)

Comment: Thanks for pointing this out! You are right that it'd be better to leave results as a list. Your solution should work for what I am trying to do, ie. determining the pairs of people who become married in each year but in reality there will be these curious cases with more than 2 people matching the criteria and hence ind greater than 1.
Answer: Maybe you can try the following code
(v<-data.df[cases,])$age[match(v$name,women)>0]

or
(v<-data.dt[cases,])$age[match(v$name,women)>0]


how to handle microservice database relations?

Question: I am working on a sample microservice project.
I have teacher-service, student-service, studies-service, and sports-service.
I used database per service pattern
a teacher has many students
a student has many studies data and sports data
the teacher may change for students

how to handle the relationship?

and the teacher wants to see his students studies and sports data

what is the best way to handle this situation in microservices

I tried by storing students id in teacher-service
<code>|---------------------|------------------|
|      teacher_id     |     student_id   |
|---------------------|------------------|
|          12         |         34       |
|---------------------|------------------|
</code>
but in studies-service and sports-service I am only storing student_id.
to get teacher's students studies and sports data. I take all student id of the teacher from teacher-service and pass it to studies-service, and sports-service.
I pass the student id by Rest GET method and its getting longer
=====> update.
how about storing teacher_id and student_id in all databases (duplicate data with consistancy) or using a in 3rd database (a sharded database)
Comment: The approach you are using is valid, try to use Feign Client (https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html) to reduce boiler-plate code and try to make your external service highly available. Also create multiple instance and balance it.
Comment: Microservice A calls microservice B for student details, and may ask microservice C for another details as well, and so on.
Comment: but @YogeshPrajapati, GET method has a character limit if we pass all student _id API may reject, and if use pagination we need to call this all time. how to handle this
Comment: Ohhh, sorry i misunderstood your question. You should not pass all ids at once to another service via GET
Comment: but in Rest Get is used for quering, how to replace in with other methods
Comment: If the GET call parameter-numbers are growing and if that is an issue, try with POST call. Violating REST rule is okay if the situation is forcing you.
Answer: I think the problem is that you haven't fully explored the domain and are rushing to figure out how to create database relationships. For now, don't focus on where the database keys are stored, because this is no longer a 3rd-normal-form database design.
Think in terms of bounded contexts. The context of a teacher may be very small--the teacher doesn't 'own' anything other than skills. A subject has many classes/sections which each own a teacher and students. A sport will have coaches and students.
Thinking about it like that will help you figure out what services need to contain references to resources outside their own context.
Comment: I believe that is the right answer.
It is unclear for example what the 'studies' represent? It can be a set of studies the school offers or it can be student`s studies data, both would be stored differently.


Where can I find a knife blade with no handle?

Question: I would like to make a nice wooden handle for a knife, but I do not have the means of cutting out a blade shape from scratch.
Where are some places I could look, or some search terms for a knife blade without a handle?  I am not asking for people to shop for me - that is against the rules - I am, however, looking for some search terms or formal names for this type of item.
It doesn't make a difference if the blade is sharp or not because I am going to resharpen it once I make and mount a handle.
Comment: This would have made more sense to ask in the chat room. It looks like a shopping question that you're trying to rephrase as something else.
Comment: I agree, shopping question, but since it's here, look at Lee Valley (I'm just a customer) http://www.leevalley.com/en/wood/page.aspx?p=31078&cat=1,130,43332,43393
Answer: Try searching for "knife blade blanks" which seems to turn up quite a few full tang blandes without scales.
Comment: That's exactly what I was looking for.  I don't know how it is off topic!
Answer: Some people have been known to grind a knife blade using a file as a starting place. The file is a hard steel item that if ground without over heating could lead to a nice knife blade.
Answer: Go to a used tool store/salvation army/junk store, and buy a knife you like the blade of. Remove the handle and have fun regrinding the blade.
Cheap and easy!


How to connect mobile broadband using terminal?

Question: I configured new-mobile-broadband connection. I know that I can connect by clicking as following:

But I want to connect manually to that mobile broadband by using terminal.
How to do with terminal command?
Answer: You can connect using the command :
nmcli con up id '<BROADBAND CONNECTION NAME HERE>'

Ex:
nmcli con up id 'BSNL/CellOne New GPRS/3G'

For better output, use the following command :
sleep 10 && nmcli nm wwan on && nmcli con up id 'BSNL/CellOne New GPRS/3G'

Comment: Could you please explain the command? That would be immensely helpful. Thanks.
Comment: Could you explain please ? I have tested with `nmcli tool, version 1.14.6` and I have `Error: argument 'nm' not understood. Try passing --help instead.` I dont know how to get the ID.


Calling server side function onclick of TD

Question: I have a asp ImageButton which has its corresponding Onclick event like OnClick="imgSubscriberInformation_Click", this imagebutton is inside a td, so I want to call imgSubscriberInformation_Click(object sender, ImageClickEventArgs e) on click of td, how can I do this? the td doesnot support serverside click event.
Also, I need the imageURL of imagebutton to be passed on every click.
aspx code:

aspx.cs code:
protected void imgSubscriberInformation_Click(object sender,ImageClickEventArgs e)
{
  hidCtrl.Value = "false";
  if (hidSubscribeInfo.Value == "")
  {
      if (imgSubscriberInformation.ImageUrl == "Images/downarrow.png")
      {
        LoadUserControl();
        PopulateData();
        imgSubscriberInformation.ImageUrl = "Images/uparrow.png";
      }
  }
  else if (hidSubscribeInfo.Value != "")
  {
    imgSubscriberInformation.ImageUrl = "Images/uparrow.png";
    LoadUserControl();
    PopulateData();
    hidSubscribeInfo.Value = "";
  }
}

Comment: can you paste code, so I can help you
Comment: look at runat="server"  but show code us your code for further enlightenment
Comment:
Comment: apsx code is in the above comment.
Comment: you can use asp.net table instead of html table
Comment: can please paste code of html
Comment: @NareshPansuriya I have pasted in the comments above.
Answer: You could do this entirely with jQuery/javascript. Grab all the TD's (or specify them by class) and assign to them an onclick event to trigger the click of the image button within.
//all TD's
$("#mytable td").on( "click", function() {
         $(this).find('img').trigger( "click" );
      });

//or
// by class
$(".tdWithImgButton").on( "click", function() {
         $(this).find('img').trigger( "click" );
      });

Comment: Also just changed .next to .find
Comment: You have really improved code. Although OP has not tagged question with jQuery but still a good solution
Comment: @EdPitt i tried the above code using class, but its not triggering the images click function. although $(this).find('img').length is 1.
Comment: Its calling the OnClientClick function, but i need to call OnClick function.
Answer: Guys i found a solution,
i moved the onClient click function to TD
and inside the javascript function i did this "__doPostBack("imgSubscriberInformation", "");"
this will call the click event of the imageButton.
Thanks for your time.


Install jsreport in the application server

Question: Can jsreport be hosted on the same server where the application is being executed?
jsreport website has this schema to describe how it should work:

I've installed jsreport in the app server, and added the following code to the app:

Code:
var jsreport   = require( 'jsreport' );
jsreport.bootstrapper().start();

And the following two messages are the ones I have doubts about:
2015-11-25T05:39:17.346Z - info: Creating default express app.
2015-11-25T05:39:17.495Z - info: jsreport server successfully started on http port: 61070

First, is it running another express app?(I already have an express app), Second, my app is running under port 3000, Why does it started on other port?
Also, if someone could give an explanation of the correct way to install it and run it, and also an example of how to make an endpoint for a report to be called from the client side of my app, I'll thank you...
Answer: From the documentation:

Attach to existing express app
If the jsreport contains express extension it will automatically start
  a default express.js based server running on ports specified in
  config. This behavior can be overridden with passing express
  application instance to the options. In this case jsreport express
  extension will just add required routes and middle-wares to the passed
  instance.

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello from the main application');
});

var reportingApp = express();
app.use('/reporting', reportingApp);

var server = app.listen(3000);

var jsreport = require('jsreport')({
  express: { app :reportingApp, server: server },
  appPath: "/reporting"
});

jsreport.init().catch(function (e) {
  console.error(e);
});

See the docs for other answers.


Why is $\int_{[x,y]}| f |\leq |x-y| \int_{R}| f| $?

Question: Hi in the proof of f integrable, $g(x)= \int_{[0,x]} f dt$ is uniformly continuous, i saw a proof that uses the following argument. Let $\epsilon > 0$ be given, take $δ := \epsilon^-1 · (\int |f|dt) >0$ since f is integrable. Let $x<y $such that $|x − y| < δ$, Then,$|g(x) − g(y)| ≤ \int_{[x,y]} |f(t)|dt ≤ |x − y|\int_{R}
|f(t)|dt < \epsilon. $
My question is, how do we get that $\int_{[x,y]} |f(t)|dt ≤ |x − y|\int_{R}
|f(t)|dt$? I have tried to bound it and only able to conclude that $\int_{[x,y]} |f(t)|dt\leq |x − y| sup(|f|)$ ?
Thanks in advance
Comment: The proposed inequality is false. That would imply that $g$ is Lipschitz on $\Bbb{R}$, which then implies that $f$ is bounded. Of course, there are integrable functions which are unbounded on any open sets. This necessitates the control over such exceptional 'peaks'.
Comment: I see, so if f is bounded and integrable, then we can do this?
Comment: @Socchi: No, even then it is false.  Take $f = 2 \cdot 1_{[0,1/2]}$.
Answer: You can't, the proposed proof is wrong.  A simple counterexample is $f(x) = |x|^{-1/2}$ for $-1 \le x \le 1$, $f(x)=0$ otherwise.  Note $g(x) = 2 \sqrt{|x|}$ for $-1 \le x \le 1$ which is not Lipschitz.
Comment: But your f(x) is not integrable?
Comment: I was worried about the region, thanks. I wonder whether a part of the proof is missing?
Comment: Oh, at infinity, you're right.  Fixed.  What's relevant is what happens near 0.
Comment: Thanks, I guess that claim is wrong? Maybe some part of the proof is missing to get to that conclusion?
Comment: I think it's just wrong.  I can't think of any useful class of functions $f$ for which it is true.


Android Studio aidl is missing

Question: <code>compileSdkVersion  21
buildToolsVersion "22.0.1"

defaultConfig {
   applicationId "org.xyz.abc"
   minSdkVersion 16
   targetSdkVersion 21
}
</code>

classpath 'com.android.tools.build:gradle:2.2.3'

Error getting -

Error:Execution failed for task ':app:compileDebugAidl'.
  java.lang.IllegalStateException: aidl is missing
Answer: Change build tool version to "21"
buildToolVersion and compileSdkVersion should be same

Android Studio aidl is missing