killer n1525 with ubuntu 14.10

Question: fresh stock setup of ubuntu 14.10 on a gs70 with killer n1525 wifi.
lspci shows both, but wifi seems not recognized correct:
04:00.0 Ethernet controller: Qualcomm Atheros Killer E220x Gigabit Ethernet Controller (rev 13)
05:00.0 Network controller: Qualcomm Atheros Device 003e (rev 20)

anyone managed to get the killer n1525 wifi working?
thanx a lot...
Comment: What is the specific problem you are encountering? Do you get an error message? Or are there no wifi networks listed in the networking menu?
Comment: no error message. but no wifi-device around. basically as here: https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1383184?comments=all
Answer: Update #2: You shouldn't need the 4.1.0-wl-ath+ kernel fork anymore. My Wi-Fi works on a stock Linux 4.3.0 kernel. Ensure you're running kernel 4.3+ and your linux-fimware package contains the correct firmware files for your device
UPDATE: Firmware now works!
I've created a fork of the ath10k firmware repository on github and added the new firmware under ath10k/QCA6174/hw2.1/
See: https://github.com/sumdog/ath10k-firmware
The following is taken from laag's comment in the launchpad bug tracker and has detailed instructions on how to extract the firmware from the Windows driver (which I've done in the repo listed above) and compiling a new kernel in Ubuntu. please note the skip_otp=y option for the ath10k_core module is required!
I got it working as described in this thread: http://lists.infradead.org/pipermail/ath10k/2015-April/004958.html
Using xubuntu (14.10 upgraded to 15.04) Anyway distro shouldn't be much different. Basically to make it working you need to do (what i did):

1. Get the windows drivers from your notebook manufacturer, in my case MSI GS60. http://download.msi.com/nb_drivers/lan/KillerSuite_220.127.116.118_Win7_Win81-MSI.zip
2. Get the needed phyton scripts to extract windows firmware:
dissect.py https://gist.github.com/kazikcz/8e5845ad84ca251aa295
assemble.py https://gist.github.com/kazikcz/c970cbf3a863ebbc4495
3. Get kvalo's kernel tree from https://github.com/kvalo/ath

4. Unpack Killer suite and run the following commands: (run commands as root , sudo / sudo su)
python dissect.py < drivers/Production/Windows8.1-x64/k1525w81/qca61x420.bin
mkdir /lib/firmware/ath10k/QCA6174/hw2.1
python assemble.py killer-n1525-fw 0 fw-2.bin fw-1.bin 4 > /lib/firmware/ath10k/QCA6174/hw2.1/firmware-4.bin
cp drivers/Production/Windows8.1-x64/k1525w81/eeprom_qca9377_1p0_NFA435_olpc.bin /lib/firmware/ath10k/QCA6174/hw2.1/board.bin

5. Unpack kvalo's kernel and compile it with:

sudo apt-get install libncurses5-dev gcc make git exuberant-ctags

To simplify things copy your current kernel config to ath-master root folder:
cp /boot/config-`uname -r`* .config
you can configure if you want with: (not needed)
make menuconfig
then compile with: (where X is the number of cores of you processor, i used 6)
make -jX
# then take a coffee or even better a cold beer, anyway it just took about 20 minutes for me.

6. Install the new kernel:
sudo make modules_install install

7. Create config file with:
nano /etc/modprobe.d/ath10k.conf
Write to it:
options ath10k_core skip_otp=y

8. Reboot using your new kernel 4.x.x-wl-ath

9. Run ifconfig

10. Voila wlan0 should be there waiting for you, now try to connect to you AP.

If its not working try to check if you missed something, check log file (/var/log/dmesg) for more details of what failed.

Give thanks to the guys who made this possible for me: http://lists.infradead.org/mailman/listinfo/ath10k

I followed the steps and it worked fine on my MSI WS-60. You can see my comment at the bottom (#122) for more details:
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1383184
Comment: This works great on my Kali 2.0 install, thanks!
Answer: First off; I'm a total Linux noob. Please forgive me if I use wrong terminology or words but I did get the QCA6174 Killer 1525 to work on my laptop much easier than all of the above answers; or the ones I found elsewhere. All information I found is from 2014 and I guess most people will know how to easily fix it but for those users like me; here is what I did.
I followed KillerNetworking their official support information (which involved compiling an entire new kernel) which 1) did not work and 2) is an out-dated, overcomplicated method (as a new user it took me 3hrs to understand and in the end didn't do anything).
So here comes the solution that got my QCA6174 1525 to work on a fresh install of Ubuntu 15.10:

Download this zip: https://github.com/kvalo/ath10k-firmware/tree/master/
Extract the .ZIP file
Go to the extracted files and locate two .bin files here:
/ath10k-firmware-master/ath10k/QCA6174/hw2.1
Here you find two files: - board.bin and firmware-5.bin First create a new folder for these two driver files. Use this command:

sudo mkdir lib/firmware/ath10k/QCA6174/hw2.1

Now the new folder is made, copy the two driver files there:

sudo cp /ath10k-firmware-master/ath10k/QCA6174/hw2.1/{board.bin,firmware-5.bin} /lib/firmware/ath10k/QCA6174/hw2.1

Navigate to the new location cd /lib/firmware/ath10k/QCA6174/hw2.1 and confirm there the two .bin files are there.

Restart your machine and you are good to go.
Answer: Please see: http://ubuntuforums.org/showthread.php?t=2248919&highlight=n1525 I know of no method to get this device working at this time. I suggest you add to the referenced bug report.
Answer: The proper support in the ath10k driver should have just been added with the Linux kernel 4.0 (ex 3.20).
I still have not tested it but this seems pretty clear according to:

News:
2015-01-27 QCA6174 support added, will be in 3.20.

here: https://wireless.wiki.kernel.org/en/users/drivers/ath10k
Note that the QCA6174 is the chip mounted in the n1525, see: https://wikidevi.com/wiki/Qualcomm_Atheros_Killer_Wireless-AC_1525
So just upgrade to the latest Linux kernel.
Comment: Support is in the kernel, but we still need the firmware image that needs to be loaded during driver initialization (see my answer)

killer n1525 with ubuntu 14.10


Is it safe to shut off an electric water heater for long periods of time?

Question: The house is located in Florida and has a 4 year old electrical water heater.  Can I safely shut off the hot water heater for a long period of time? Or can I install a regulator and the purpose of it?
Comment: This sounds very much like an [XY Problem](https://xyproblem.info/). What is it that you're trying to accomplish by turning off the heater? What is a "long" time? What kind of regulator do you want to install - what are you trying to regulate?
Comment: Should define a long period.   Weeks or more should probably drain the tank also.
Comment: Note that if you're draining the tank, it _must_ be refilled _before_ turning on the hot water heater. Running the element (if electric) unloaded will cause it to overheat and burn out
Comment: Are you interested in knowing how dangerous that water might become if drank, or only whether the equipment will be ok?
Comment: @Wanda, could you please [edit] your question to clarify what you want to know about the regulator, and more importantly, what you're trying to accomplish by turning off the heater? Also, what would constitute  "a long period of time"? Days? Weeks? Months? Years?
Answer: All hot water heaters already have a regulator.  Otherwise the water would boil over and you'd have a boiler explosion.
You can feel free to shut off an electric water heater for an extended period of time. You can switch it off at the circuit breaker, a local disconnect if it has one, or the thermostat. If the breaker is reasonably modern I would use that, less likely to break.
Try not to switch it off every day.  It won't save that much power, and the water will spend a lot of time at medium temperatures between hot and cold. That's a breeding ground for bacteria.
Comment: Switching the water heater on and off every day is something we do regularly here in Eastern Europe, usually by a built-in or external timer. Electricity is a lot cheaper at night. On the other hand, bacteria colonies need time to develop. It is OK to heat it to over 65C only once in a week.
Comment: External timers are/were a thing here in the US as well.
Answer: If the cycles of cold and then heat will be over long intervals (months), then it shouldn't be a problem. Maybe check the tank's reservoir for bacteria buildup once in awhile, and change the entire reservoir's contents out if they appear. (They aren't a health hazard, because the water you use passes through a coil that sits in the reservoir, and the two don't mix. But grunge clogs maintenance valves, and that's never good.)
FYI: Switching off the heater shouldn't be done repeatedly in short cycles, such as for a weekend vacation home. Each cycle stresses the metal parts slightly, and may cause problems with seals after some large number of cycles (I'd guess a thousand or more. The number will vary with the model. Ask the mfr if you're concerned; they have this data from their product testing.) In that case, a better solution is to lower the temp by 30º or so when not using it, rather than a full shut-off.
Comment: "The water you use passes through a coil that sites in the reservoir, and the two don't mix"  Indirect water heaters (having a separate boiler unit) are quite rare IME.  Far more common to directly heat the single supply reservoir.
Comment: you can tell a combined boiler heat exchanger unit because the temperature/pressure relief valve water flows into the boiler  and the boiler has an open vent/drain outlet.  it's not the same thing as indirect at all. they tend to die from cracking of the (ourput) heat exchanger coil.  possibly due to thermal cycling or water hammer.
Answer: A rental house I lived in for a few years had the water heater on an automatic timer. It would turn on a couple of hours before we needed it in the morning and then shut off around 9 or so at night.
It was like that for the threeish years we lived there and never had an issue that I'm aware of.


What is a mathematically rigorous treatment of "sentences", "words" and "language"?

Question: How do mathematicians rigorously deal with words and sentences? In other words, how are words sentences constructed in a mathematical sense? Is there some (accepted) system for constructing words?
I know this is a rather broad question, but I am in the process of trying to think about "words" and "sentences" more rigorously, because often in computational mathematics we deal with sets of words or sets of sentences. These words are then transformed in some ways into the numerical domain to perform calculations on them.
An attempt could be as follows:
To start we may define a set containing all the symbols in a "language system", call it $\mathcal{S}$.
Then a word is just a finite combination of a subset of these symbols. We can either define as a relation $r: \{a_1, \ldots, a_n\} \subset \mathcal{S} \mapsto w$, or perhaps as an element of the power set of $\mathcal{S}$, say $\mathcal{W} := \mathcal{P}(\mathcal{S})$.
Then building upon this, a sentence would be some combination of words, i.e., $\mathcal{P}(\mathcal{W})$ where we define a function that puts the correct punctuations in place.
Just some thoughts. I wonder if people have tried to make this more rigorous.
Note: I have briefly studied regular expressions and formal language (long time ago) but I don't really think we necessarily have to abstract everything to the $0$s and $1$s to make sense of words.
Comment: You can see the answer to [this post](https://math.stackexchange.com/questions/1357130/constructions-of-terms-using-variable) with reference to the formal treatment into Kenneth Kunen, [The Foundations of Mathematics (2009)](https://books.google.it/books?id=_B_oQQAACAAJ&dq)
Answer: To my knowledge there is no deep study of such 'language systems' but the study of logic has made quite some progress in that regard. There are multiple ways of formalizing the concept of language systems, like just plain sequences, trees, or other but all this formulations are equivalent.
Model Theory may be what you have in mind, it studies theories and their structures, but to write down the theories axioms it is needed a language. I will give a brief definition of a language and give the example of a language for the theory of natural numbers. A language has:

$n$-placed functions. E.g. the 2-ary $+$ function, the multiplication $\times$ and the successor $S$.
$n$-placed relations. E.g. the 2-ary $<$ less than relation. Or the 1-ary $Odd$ relation.
Constants. E.g. $0, 1, 2,...$ (As you may have noticed, you only need the constant $0$. the rest can be written down using it and the successor function).

Similarly Logic has a language ($\wedge , \forall, \lnot$, etc; though this language is usally taken as a primitive). Now every sequence of these elements is a valid expression, but we only care about well formed formulas. Which are those that satisfy some requirements. E.g. a 2-ary relation may require have a term on each side of it e.g. ($1<2$). Common sense restrictions like that can be used to generate, by recursion, the set of all well formed formulas. The phrase sentence is usually just meant to mean a well formed formula with no variables unquantified. Some nice things about this construction (assuming a lot of stuff I haven't mentioned explicitely):

Unique readability theorem: There is only one way to interpret a sentence. No ambiguities in math.

Effective computation to check if an expression is a well formed formula.

There's a lot more to say but that would make me write a book so I'd just better recommend you a better book in first order logic: I personally like Enderton's A mathematical introduction to logic.
Comment: I would just like to make an honorary mention to free groups, I think they are flexible enough to satisfy as a foundation for languages (as in FOL/Model Theory) though I have never seen such construction. Even if someone spells it out, it will probably end up being equivalent to the ones that already exist though.


How much Elixir is collected during a match?

Question: I want to know how much Elixir is produced during a match  (Not counting Elixir Collectors and when Elixir bars are full) in order to test a new, costly strategy.
So, how much Elixir is produced during a match?
Answer: According to the Royale Wiki, you get 1 Elixir per 2.8 seconds.
After 2 minutes this goes up to 1 Elixir per 1.4 seconds.
Also, you'll start with 5 Elixir.
This means that during a normal match you get:
5 + (2*60)/2.8 + 60/1.4 = 90 (point something) Elixir.
If the match goes to Sudden Death, this is boosted to total of:
5 + (2*60)/2.8 + 60/1.4 + 60/1.4 = 133 (point something) Elixir, so 43 Elixir more.
Comment: Do not forget, that you start already with 5 Elixir. Although it isn't produced directly it should still be involved in calculations.
Comment: @h0ch5tr4355 _Very_ good point. I'll add that right away.
Comment: At some point after this answer they've tweaked this a bit. You'll also gain 1 extra elixir at the time the elixir doubling occours. So, you can add 1 to each number.


How to know the URL which caused PHP to go OOM

Question: I am debugging a problem I found while reading the PHP error logs:

[14-Mar-2011 09:53:31] PHP Fatal error:  Allowed memory size of 67108864 bytes
exhausted (tried to allocate 24 bytes) in XXX.php on line 77

The problem is that code it points to is very generic code, used by most pages, so I'm having an extremely hard time trying to reproduce it. I really need the URL that triggered the error.
What can I do? This is what I tried:

To find the problem from the file/line the error points to.
Examined the error log to see if it's always the same amount of bytes (it's not), the same line (it's not), the same file (it is 99% of the time).
Checked how common this error is: very common (~1 per second)
Grepped the access log for "14-Mar-2011 09:53:31", but we get TONS of hits per second and going through all of them is very unfeasible.
Answer: You should use the set_error_handler();
With that function you can create your own error handler saving the php script, line and the REQUEST_URI that generated it.
It was the first think i developed for a framework because it's very important to have a better error handler
Comment: I already thought of this but I assumed it wouldn't work with OOM errors, since it needs to allocate (little) memory. or it does work?
Answer: One caveat, if you are working in a multi-platform enviroment (linux and windows for example), there is a possibility that the error is referring to the wrong line and causing confusion if line breaking is set wrong when saving the file for the target system. Happened to us many a time and caused a lot of grief. Fixing that little detail usually made isolating the culprit a breeze. I'm not saying that this is the case, but it's worth checking.
Answer: As of php 5.2 you can see this
http://www.php.net/manual/en/function.set-error-handler.php#99193


Calling a pure virtual function from base class that doesn't define it?

Question: I have the following class:
class gkLogicBrick
{
public:
    gkLogicBrick(gkGameObject* object, gkLogicLink* link, const gkString& name);
    virtual ~gkLogicBrick();

    virtual gkLogicBrick* clone(gkLogicLink* link, gkGameObject* dest) = 0;

    //unimportant function/variables
};

and it's being subclassed like:
class gkLogicController : public gkLogicBrick
{
    gkLogicController(gkGameObject* object, gkLogicLink* link, const gkString& name);
    virtual ~gkLogicController() {}

    //unimportant function/variables
};

The method named clone() isn't being overridden and yet it is being called from another class on a gkLogicController object. I thought calling pure virtual functions wasn't allowed? Do C++ compilers automatically create a default definition for any pure virtual functions inherited?
Comment: Yes it compiles. It is a small part of a large library. I'm guessing this isn't allow then, so maybe I should look further and see if something else is going on that I'm missing...
Answer: It's OK to call a pure virtual function (through the dynamic dispatch mechanism). That is actually the purpose of pure virtual functions, when you think about it.
I assume that "being called from another class on a gkLogicController object" actually means through a pointer or reference to gkLogicController. This must then point/refer to an instance of a class derived from gkLogicController which does override clone. It is impossible to create an instance of gkLogicController itself, as it is still abstract.
Comment: This might be it. The `clone` function is called for each member in a list of `gkLogicBrick` objects, I traced further and see that `gkLogicController` objects are added to this list. Now I just need to see what calls that function, and so on.
Comment: After much tracing, I seem to have found the class of objects being used that implement clone. Thanks!
Answer: I guess you have not compiled your code. Because
struct A
{
    virtual void test()=0;
};

struct B : A
{

};

int main()
{
    B b;
}

http://ideone.com/Dbx9iH
see the error:

prog.cpp: In function 'int main()':
  prog.cpp:13:7: error: cannot declare variable 'b' to be of abstract type 'B'
  prog.cpp:6:8: note:   because the following virtual functions are pure within 'B':
  prog.cpp:3:18: note:    virtual void A::test()
Answer: If you do not define the function SOMEWHERE in an actual class (e.g. a derived class), you will get an error when trying to create the object (at compile time).
It is however fine to not have one in the baseclass if the baseclass is never directly instantiated - in fact, it's often used this way just TO make sure the baseclass isn't accidentally "used" when it shouldn't be. If the baseclass is intended to be used, then you do need to implement the function (you can still do that even if it says = 0 on the end.
And the whole point of virtual functions is to allow the baseclass (or some other component that only knows about the baseclass) to call the actual function in the derived class.


Lubuntu/Ubuntu 13 Audio clicking in power-save mode

Question: I've recently done a fresh install of Lubuntu 13 on my laptop, I immediately noticed a recurring clicking sound when it wasn't charging.
Running:
    lspci | grep -i audio

gives:
Audio device: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) High Definition Audio Controller (rev 04)

Some investigation led me to this question/answer: How do I fix laptop speakers popping when no sound is playing?
Running the script fixes the problem which seems to prove that it is related to power-save mode.  Unfortunately I need to run the script every time I reboot.
Does anybody know of a way to make this change permanent, or if there is a better way to go about resolving this?
Answer: OK, I've just come across a solution that appears to work, even after a reboot.  I found the solution here: http://ubuntuforums.org/showthread.php?t=1788483 but I'll paraphrase in case the link stops working.

Open terminal and type:
gksudo gedit /usr/lib/pm-utils/power.d/intel-audio-powersave
Find this line:
INTEL_AUDIO_POWERSAVE=${INTEL_AUDIO_POWERSAVE:-true}
and comment it out by putting a # in front of it like this:
# INTEL_AUDIO_POWERSAVE=${INTEL_AUDIO_POWERSAVE:-true}
Just below this line add a new line, like this:
INTEL_AUDIO_POWERSAVE=false
So now you will have:
# INTEL_AUDIO_POWERSAVE=${INTEL_AUDIO_POWERSAVE:-true}
INTEL_AUDIO_POWERSAVE=false

Save the file (File > Save) and exit.
Reboot your computer.
The clicking/popping sound will be gone.

Essentially this will stop the Intel driver from putting the hardware into sleep mode.  Not ideal, and hopefully a future update will fix it, but hopefully this will be of help.
Answer: You can use the file audio-power-save-off which consists your script to run every time your system starts. You have to add it on Startup Applications.

Search for Startup Applications on your dash and Run it. You can also find it in directory /usr/share/applications. Just browse it.
Once started, click Add button.
Give some name on first field, Browse for the file where you stored audio-power-save-off for the second field and again give some comment for the third field. Then Add.
Your script would be executed each time you starts your system.

Give it a try, hope it works for you..
Also I found this link  somewhat important.
Comment: Hi @saurav-kumar, thanks for the quick response.  Unfortunately Lubuntu doesn't seem to come packaged with **Startup Applications** so I tried your second suggestion.  Sadly adding the script into `/etc/rc.local` didn't seem to do anything.  I also tried copying the script to `~/.config/autostart/` but that didn't work either.  I can't find **Startup Applications** in Package Manager or the Software Center?


Should I learn haskell for understanding the functional programming part of javascript?

Question: I'm a developer with very strong oop background. And Recently I want to learn javascript coz I think it's the future. But I find myself very hard to understand the functional programming part of concepts in javascript. I searched around and I got this "Haskell" language a lot in the functional programming world. A lot of people are saying if you want to learn FP you should learn haskell.
It'll be highly appreciated if someone can provide some inputs or someone can share some experience.
Comment: Learning Haskell to understand Javascript would be like learning Chinese to understand English. You'll probably understand how to learn a language better when you're done, but you still can't write javascript.
Comment: I think it's fair, but critical, to say it'd be like learning Latin to learn Italian. You won't be able to speak Italian at the end of the day, but when you later go learn Italian you'll have some grand intuition for "why things are they way they are". I'd also recommend learning Self for the same reason.
Comment: I don't agree with your question, i think it will be more learning German and and learning English, because English and German have some thinks in common like Haskell and Javascript.
Comment: i don't know about Self?
Comment: I think functional JavaScript will be more like Scheme than Haskell and it's probably easier to learn coming from an Algol background.
Answer: I think there is no binary answer to your question. Honestly, you don't have to learn Haskell to understand functional programming. But learning Haskell will make you understand functional programming better in my opinion.
You could learn functional programming using JavaScript, but the fact that JavaScript is not purely functional and allows you to write easily imperative code, won't force you to write difficult algorithms in a functional way. So each time you have difficulty writing something in a functional way, you will probably abandon and switch to your old habit.
I will add moreover that JavaScript hides a bit its functional programming and does not naturally provide functions such as map, reduce, composition, filter and functional characteristics such as currification. By the way, you should take a look at Underscore, which is a library for JavaScript that brings a lot of functions such as map. You might also be interested in CoffeeScript which is "a little language that compiles into JavaScript".
This language is basically JavaScript with a better syntax, and it brings out the functional side of JavaScript. Even if you don't want to use it, just looking at the overview part and seeing how CoffeeScript translates to JavaScript will make you understand better JavaScript.
If you have time to learn Haskell, and force you to program non trivial algorithms with it, then you will have a really good understanding of functional programming. Haskell is pure so will have no other choice to force you to express your algorithms in a functional way. Moreover, you will learn concepts such as Functor, Monad, Curryfication, Pattern Matching that you will not learn by just using JavaScript in a functional way. One will argue that you don't need to know those concepts to be a good programmer in JavaScript, but if you know them you will see programming under a new way and it will probably change the way you program in any language.
To conclude, I will say learning Haskell, is not something you have to do to be a good JavaScript programmer, but it will help you to be more "open-minded" and to have a better programming culture. Learning Haskell asks a lot of investment, and will take you a lot of time, but it's also a lot of fun. If you want to learn it, I recommend you the book Learn You a Haskell for Great Good!.
Answer: No.
Here's a pretty basic introduction to the functional capabilities of javascript. It assumes no knowledge of functional programming.


Calculate column by condition

Question: I have table in df:
X1  X2
1   1
1   2
2   2
2   2
3   3
3   3

And i want calculate Y, where Y = Yprevious + 1 if X1=X1previous and X2=X2previous, elso 0. Y on first line = 0. Example.
X1  X2  Y
1   1   0
2   2   0
2   2   1
2   2   2
2   2   3
3   3   0

Not a duplicate... Previously, the question was simpler - addition with a value in a specific line. Now the term appears in the calculation process. I need some cumulative calculation
What I need, more example:
X1  X2  Y
1   1   0
2   2   0
2   2   1
2   2   2
2   2   3
3   3   0
3   3   1
2   2   0

What I get on the link to the duplicate
X1  X2  Y
1   1   0
2   2   0
2   2   1
2   2   2
2   2   3
3   3   0
3   3   1
2   2   4

Comment: I add example. The difference in the last line
Comment: I tried to explain how the difference. I tried your last answer (thanks for it), but this is a bit different.
Comment: Can you change sample data for explain why not dupe?
Comment: i add sample when i use df['Y'] = df.X2.shift().eq(df.X2)&df.X1.shift().eq(df.X1)*(df.Y+1).shift().fillna(0).astype(int)
Comment: Yes, but I think add example why dupe not working...
Comment: I missed. I'll try
Answer: Use GroupBy.cumcount with new columns by consecutive values:
df1 = df[['X1','X2']].ne(df[['X1','X2']].shift()).cumsum()

df['Y'] = df.groupby([df1['X1'], df1['X2']]).cumcount()
print (df)
   X1  X2  Y
0   1   1  0
1   2   2  0
2   2   2  1
3   2   2  2
4   2   2  3
5   3   3  0
6   3   3  1
7   2   2  0

Calculate column by condition


Define specific output count in EXPR command

Question: I have a scenario wherein I want to have 9 character count in expr.
I have sample code which is:
    var1=012345678 #this is 9 characters
    sum=`expr $var1 + 1`
    echo "$sum"

Here is the result:
    ./sample.sh : 12345679 #this is only 8 characters

My expected output:
    ./sample.sh : 012345679

Any help on this?
Answer: The leading zero is removed when doing the math.
You can force a 9 length output using printf "%09d" 123.
When you try to use the the syntax ((sum=${var1} + 1 )) you have another problem: When the first digit is 0, bash expects a different radix.
You can remove the first 0 with
var1=012345678
echo "${var1#0}"

This only helps with your input, not with 00012.
Removing the leading zeroes and printing the sum can be done with echo $((10#$var1))
var1=00012345678
((sum=$((10#$var1)) + 1))
printf "%09d\n" $sum

This can be solved easier with
var1=00012345678
echo "${var1} 1" |awk '{ printf("%09d\n", $1 + $2) }'

You can avoid the echo with
awk -v var1=$var1 'BEGIN { printf("%09d\n", var1 + 1) }'

The BEGIN is used for parsing without an inputfile.
The option -v is a clean way to use a shell variable inside an awk script.
Do not try things with quotes, one day it will shoot your own foot:
# Don't do this
awk 'BEGIN { printf("%09d\n", '${var1}' + 1) }' # Just do not do it

Comment: Could you please explain the part "%09d", what it means when used in awk?
Comment: `%d`=parameter is integer. `09` = minimal length 9 filled with leading zeroes if needed for length. Search for `printf format` for more information.


$\psi_1$-Orlicz norm of a product of two Gaussian random variables

Question: Is there a direct formula or a bound for the following Orlicz norm: $\|\xi \eta\|_{\psi_1}$, where $\xi, \eta \sim \mathcal{N}(0, 1)$ are standard normal random variables, $\psi_1(x) = e^x - 1$?
One way to bound this quantity would be $\|\xi \eta\|_{\psi_1} \leqslant \|\xi\|_{\psi_2} \|\eta\|_{\psi_2}$, and then compute the $\psi_2$-norm of a standard normal variable. Can this bound be improved? It gives the answer $8 / 3$.
A reminder:
$$
\|\xi\|_{\psi_1} = \inf \{t > 0 | \mathbb{E}\exp\{|\xi| / t\} \leqslant 2\}
$$
EDIT: It seems that the previous bound can indeed be improved. If one plots the approximate expectations, one can notice that the true value of the norm is below 2.
Comment: Are you sure the definition of the Orlitz-norm $\Vert\cdot\Vert_\psi$ is correct? The right-hand side does not even depend on $\psi$.
Comment: @SmallDeviation yes, it is correct, here $\psi_1(x) = e^{x} - 1$. In general, $\|\xi\|_{\psi} = \inf \{t > 0 | \mathbb{E}\psi(|\xi| / t) \leqslant 1\}$
Comment: Then you should include the definition of $\psi_1$ in your post. Otherwise it is impossible for us to know what $\psi_1$ is.
Comment: I don't know if there is a way to get anything other than a numeric solution, which gives you something like $t = 1.3725$
Comment: I am assuming you did figure out the definite integral?
Comment: @LSK21, which definite integral are you talking about? Thanks for the numeric solution!
Comment: I wrote up what I know in an answer for you.
Answer: In order to calculate the sub-exponential norm, define
$$ f(t) := \mathbb{E}[\exp(|\xi|/t)] $$
for $t > 0$. Then, we can simplify $f$ as follows by recalling the density of the Gaussian distribution:
\begin{equation*}
f(t) = \frac{1}{\sqrt{2\pi}} \int_{-\infty}^\infty \exp(\frac{|z|}{t}) \exp(-\frac{z^2}{2}) dz
\end{equation*}
Now, I admit I used an integral calculator when I was first interested in this and plugged in the right side to get
$$ f(t) = \exp(\frac{1}{2t^2}) \left( \text{erf}(\frac{1}{\sqrt{2}t}) + 1 \right) $$
where erf denotes the Gaussian error function.
(If you are interested in the steps, I can try and do the calculation again by hand, let me know in the comments)
Since $f$ is decreasing on $\mathbb{R}_{>0}$, we can now simply set the right side equal to $2$ in order to get the sub-exponential norm, which I did using Geogebra to get the approximate value I mentioned above (1.3725).
Note that the same procedure can be done for the sub-gaussian norm, which gives you $\sqrt{8/3}$ for the standard normal distribution.
Comment: Thank you for the answer! However, I think that the integral should be different. As we are calculating the norm of the product of two rvs, instead of $\xi$ we put not a standard normal rv, but a product of two standard normal random variables. Then the integral becomes more complex
Comment: Ah of course, I was thinking of just a single r.v.
Comment: You could try using the calculator I linked, but I suspect the modified Bessel function is a bit too much for it


Read XML using XMLReader in PHP without know nodes

Question: I have to read and parse an XML file using XMLReader with PHP without know the nodes.
I have this file:
<Invoices>
  <Company>
    <Name>Tuttobimbi Srl</Name>
  </Company>
  <Documents>
    <Document>
      <CustomerCode>0055</CustomerCode>
      <CustomerWebLogin></CustomerWebLogin>
      <CustomerName>Il Puffetto</CustomerName>
    </Document>
  </Documents>
</Invoices>

I would to parse it like this:
Invoices
Invoices, Company
Invoices, Company, Name
Invoices, Documents
Invoices, Documents, Document
etc...

I wrote this code:
    while ($xml->read()) {
        if ($xml->nodeType == XMLReader::ELEMENT)
            array_push($a, $xml->name);

        if ($xml->nodeType == XMLReader::END_ELEMENT)
            array_pop($a);

        if ($xml->nodeType == XMLReader::TEXT) {
            if (!in_array(implode(",", $a), $result)) {
                $result[] = implode(",", $a);
            }
        }
    }

It seems to work but doesn't print the nodes with subnodes, such as:
Invoices
Invoices, Company
Invoices, Documents
Invoices, Documents, Document

Comment: You need to iterate over each node's children as well.
Comment: @PaulCrovella My mistake. I'm used to using [SimpleXML](http://php.net/manual/en/book.simplexml.php), hence my false assumption.
Answer: Many of those nodes you'd think would be XMLReader::TEXT nodes are actually XMLReader::SIGNIFICANT_WHITESPACE.
Fortunately you can drop that $xml->nodeType == XMLReader::TEXT check altogether and build your result as you encounter elements.
Example:
while ($xml->read()) {
    if ($xml->nodeType == XMLReader::ELEMENT) {
        array_push($a, $xml->name);
        $result[] = implode(",", $a);
    }

    if ($xml->nodeType == XMLReader::END_ELEMENT) {
        array_pop($a);
    }
}

This'll give you:
Array
(
    [0] => Invoices
    [1] => Invoices,Company
    [2] => Invoices,Company,Name
    [3] => Invoices,Documents
    [4] => Invoices,Documents,Document
    [5] => Invoices,Documents,Document,CustomerCode
    [6] => Invoices,Documents,Document,CustomerWebLogin
    [7] => Invoices,Documents,Document,CustomerName
)

Comment: Thanks @paul-crovella, I used your first solution to not repeat element in the array. Thanks
Comment: now I have a problem...into "if (!empty($a) && !in_array(implode(",", $a), $result)) {" I need also to save into an other array the value of the node. When I try "$xml->value" I have no value inside...


I need to know how to replace a water damaged wood rotten stud in a wall

Question: I just bought a house built in 1930. The previous owners had a crack in the shower. I need to know how to replace the stud that holds up that wall as it is now rotten from water damage. The drywall is also rotten. The wall is not load bearing. And there's also water damage in the floor. My main concern at the moment is the stud. Also it should be noted that I stopped the leak for the time being.
Comment: Your question is a bit broad. Are you truly asking for a full project walk-through, or do you have a more specific concern? One or two studs can usually be removed from an interior wall without special care being taken with respect to structure.
Answer: Cut out the rotten drywall then use a reciprocating saw to cut out the old stud and replace with a new one. If it isn't load bearing and its only one stud this is easy. You may plan on also cutting out a portion of you bottom plate and replacing it if it also rotten.
Comment: @PaulLogan Is right, you could definitely sister a new stud alongside the existing stud, you might consider this if the other side of the wall is finished. When I had to replace a bunch of rotten exterior studs this summer, I cut the rotted half of the old studs out before sistering a new stud next to it. But if the old stud is moldy or so wet you can't dry it out, then best remove it.
Comment: Jon is right, the bottom plate is just as important as the stud.  However, instead of replacing stud you could also just sister in a new stud along side the existing questionable stud.


cfselect - how to dynamically set the selected option value w/ manual values?

Question: If I have a select setup with with hard manual values and I want to set one of the options below as the default value based on that, how would you go about it?    Like when this form is reached theres a variable that will contain 1 through 12.  So if it's "6" I'd like to make "6 months" the selected value.    I know you can put "selected = "selected"" directly in the option values but I don't see how to get an if statement in there.   I tried doing it a few was in the cfselect and couldn't figure out anything that worked.
Thanks!
<cfselect name="months_select" id="months_select" multiple="no">
    <option value="1">1 Month</option>
    <option value="2">2 Months</option>
    <option value="3">3 Months</option>
    <option value="4">4 Months</option>
    <option value="5">5 Months</option>
    <option value="6">6 Months</option>
    <option value="7">7 Months</option>
    <option value="8">8 Months</option>
    <option value="9">9 Months</option>
    <option value="10">10 Months</option>
    <option value="11">11 Months</option>
    <option value="12">12 Months</option>
</cfselect>

Answer: You can embed the CF directly into the HTML, I've done the first one as an example.
<select name="months_select" id="months_select" multiple="no">

    <option value="1" <cfif YourVariable EQ 1>selected="selected"</cfif>>1 Month</option>
    <option value="2">2 Months</option>
    <option value="3">3 Months</option>
    <option value="4">4 Months</option>
    <option value="5">5 Months</option>
    <option value="6">6 Months</option>
    <option value="7">7 Months</option>
    <option value="8">8 Months</option>
    <option value="9">9 Months</option>
    <option value="10">10 Months</option>
    <option value="11">11 Months</option>
    <option value="12">12 Months</option>
</select>

You're better off making a loop though.
<select name="months_select" id="months_select" multiple="no">
    <cfloop from="1" to="12" index="Month">
        <option value="#Month#" <cfif YourVariable EQ Month>selected="selected"</cfif>>#Month# Month<cfif Month GT 1>s</cfif></option>
    </cfloop>
</select>

Hope that helps.
Comment: Needing cfoutput should be a given. Ternary is only ACF9+ and since the OP didn't say which version he had, it was omitted.
Comment: use a loop assuming of course there is a cfoutput surrounding the cfselect. You can also use ternary if
Comment: Correct about CF9, I should have added that. :)  Considering it's a beginner question thinking code between  and  wouldn't need a cfoutput tag is reasonable (like cfmail).  Also, I don't see any reason in this code to use cfselect. a simple html select would work and not generate any extra CF javascript.
Comment: Fair enough point on the cfselect, I had just copied them from their example, but removed them now.
Answer: If you're using cfselect and generating your options with a query, you can define the default value there.
<cfselect
  name="months_select"
  id="months_select"
  multiple="no"
  query="numMonths"
  selected="#monthSelected#"
  value="monthValue"></cfselect>

Comment: True enough, but a future reader may be using `cfselect` for a bigger project.
Comment: Using a query for a simple 1-12 loop seems a bit overkill.


Optimization of algorithm while

Question: here are 2 codes that give the same result :
Code 1
<code>#include <stdio.h>
int main(int argc, char **argv)
{
    int res, nbMax = 0, i;
    unsigned long j;
    for (i = 1; i <= 1000000; i++) {
        j = i;
        int nb = 1;
        while (j != 1) {
            nb++;
            if (j % 2 == 0) {
                j = j / 2;
            } else {
                j = 3 * j + 1;
            }
        }

        if (nb > nbMax) { // <-
            nbMax = nb;
            res = i;
        }
    }
    printf("longest: %d (%d)\n", res, nbMax);
    return 0;
}
</code>
Code 2:
<code>#include <stdio.h>
int main(int argc, char **argv)
{
    int res, nbMax = 0, i;
    unsigned long j;
    for (i = 1; i <= 1000000; i++) {
        j = i;
        int nb = 1;
        while (j != 1) {
            nb++;

            if (nb > nbMax) { // <-
                nbMax = nb;
                res = i;
            }
            if (j % 2 == 0) {
                j = j / 2;
            } else {
                j = 3 * j + 1;
            }
        }

    }
    printf("longest: %d (%d)\n", res, nbMax);
    return 0;
}
</code>
the diference is the commented bloc (if). the first time is outside the 2nd while loop, and in the second inside.
the first algorithm should be faster than the second because that scope is executed more times in the 2nd algorithm.
however i get 1second time execution in the first one, and 0.9 in the second...
how can be the 2nd algoirthm faster than the 1st ??
EDIT. I work on MinGW(4.7.1) Windows 8.1 intel i7-4500
Comment: I can't reproduce this. On amd64 gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2 with `-O3`, the first piece of code runs in ~0.30s while the second runs in ~0.33s.
Comment: Same here, can't reproduce it at my end:
`code 1: Compilation time: 0.13 sec, absolute running time: 0.35 sec, cpu time: 0.22 sec, memory peak: 3 Mb, absolute service time: 0.48 sec`
-------------------------------------------------------------------------------------------------

`cod2: Compilation time: 0.13 sec, absolute running time: 0.45 sec, cpu time: 0.38 sec, memory peak: 3 Mb, absolute service time: 0.58 sec`

You can also try http://rextester.com/runcode
Comment: What optimization are you using?
Answer: I cannot reproduce it here, but it depends on the platform and compiler you are working with. Based on the Optimization Algorithms used in the compiler, some parts of your code may change.  If something does not affect your code, may be get out of the loop or even be omitted from the code during optimization phase while compiling. You can check the compiler optimization techniques in Loop Optimization for some insight.

Optimization of algorithm while


Finding $f(x)$ from integral equations

Question:
If $f$ is a continuous function such that
  $$ \int_0^x f(t) dt = xe^{2x}+\int_0^x e^{-t}f(t) dt $$
  for all $x$, find an explicit formula for $f$.

I started this problem by differentiating both sides with respect to $x$, getting
$$f(x) = e^{2x}(1+2x)+e^{-t}f(x).$$
Solving this for $f(x)$ gives $$f(x)=\frac{e^{2x}(1+2x)}{1-e^{-x}}.$$
So my main question is did I do this properly? My second question would then have to be is there an easier way to solve this?
Thanks!
Comment: IMO, this is a pretty simple way to solving it.  Straight forward easy.
Comment: Agreed - just remember to mention any necessary/sufficient conditions when dividing (i.e. is $1-e^{-x}=0$? If so can you say for which $x\in \mathbb{R}$ this $f(x)$ is valid for?)
Answer: It's correct.
Another simple way is to unify the integrals:
$$\int_0^x\ f(t)\left(1 - e^{-t}\right)\ \text{d}t = xe^{2x}$$
Then differentiate with respect to $x$ and $t$ (the second term and the first one respectively), and you will get the same result you got.

Finding $f(x)$ from integral equations


rsync @ERROR setgroup failed

Question: I set up rsync daemon on a Ubuntu server and I am trying to transfer a file from raspberry pi machine to the server:
rsync --timeout 10 --progress --password-file ~/rsync.password --append-verify some_file firstname.lastname@example.com::files
@ERROR: setgroups failed
rsync error: error starting client-server protocol (code 5) at main.c(1653) [sender=3.1.1]

I configured the rsync daemon to be run as pi user and I am getting the error above. If I run the daemon as root no errors are shown and transfer is ok.
Here is my rsyncd.conf file:
[files]
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsync.log

path = /some/path
comment = RSYNC FILES
read only = false
secrets file = /etc/rsyncd.secrets
auth users = pi
uid = pi
gid = pi
use chroot = false

The path dir has g+s permissions set on it - I want all files in it to inherit parent directory's group.
Any ideas how to resolve this error?
Answer: I found the solution. Here is the problem. Since I am running the rsync daemon with another user, not root, I needed to give rsync the following capabilities:
setcap cap_net_bind_service,cap_setgid=+ep /usr/bin/rsync

cap_net_bind_service - this is needed so the daemon can bind to the system ports(lower than 1024, the default port rsync is binding to is 873)
cap_setgid - this is what caused the setgroups failed error.

Hope this helps someone in the future.
Comment: I can't thank you enough for this answer!! I've been pulling my hair out for the past few days getting this to work and this was the only solution that solved the issue. Thanks so much for sharing! I still can't grasp why rsync, an industry standard, is so poorly documented. As if this should be common knowledge...
Comment: Glad I could help you :)

rsync @ERROR setgroup failed


Change one element of ListView

Question: I want to change one item (ImageView) in a specific row of a ListView. Now I tried it to change it through the onItemClickListener provided View to change it. It also works !
But somehow when I scroll up and down other listview rows getting also changed. I found something about the problem "view recycling" but I really didnt find a solution for it.
Someone can help ?
EDIT:
Some code here :
My Listener :
LV.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        ...
        updateEQAnimation(position,view);
        ...
        }

The function which should change it
private void updateEQAnimation(int index, View view){

   ColorStateList sColorStatePlaying;
   ColorStateList sColorStateNotPlaying;

   sColorStatePlaying = ColorStateList.valueOf(context.getResources().getColor(R.color.colorPrimary));

    if(view == null)
        return;
    AnimationDrawable animation = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.anim_current_song);
    ImageView EQ_ANIM = (ImageView) view.findViewById(R.id.imageView_eq_animation);
    EQ_ANIM.setVisibility(View.VISIBLE);
    EQ_ANIM.setImageDrawable(animation);
    EQ_ANIM.setImageTintList(sColorStatePlaying);
    animation.start();}

getView method :
 @Override
public View getView(int position, View view, ViewGroup parent) {
    View rview = view;
    holder = null;

    if (rview == null)
    {
        LayoutInflater inflater = context.getLayoutInflater();
        rview= inflater.inflate(R.layout.row_song, null, true);
        holder = new ViewHolder(rview);
        rview.setTag(holder);
    }
    else
    {
        holder = (ViewHolder) rview.getTag();
    }

    mArtLoader.loadBitmap(AL_songlist.get(position).getAlbumArtPath(), holder.imgAlbumart);
    holder.txtTitle.setText(AL_songlist.get(position).getTitle());
    holder.txtArtist.setText(AL_songlist.get(position).getArtist());

    if(Main.songService.svc_mpcontroller != null && Main.global_music_controller != null) {
        if (AL_songlist.get(position).getID() == Main.global_music_controller.get_current_id()) {
            ColorStateList sColorStatePlaying;
            ColorStateList sColorStateNotPlaying;

            sColorStatePlaying = ColorStateList.valueOf(context.getResources().getColor(R.color.colorPrimary));
            AnimationDrawable animation = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.anim_current_song);
            holder.imgEQAnimation.setVisibility(View.VISIBLE);
            holder.imgEQAnimation.setImageDrawable(animation);
            holder.imgEQAnimation.setImageTintList(sColorStatePlaying);
            animation.start();
        }
    }

    return rview;
}

Comment: You should use getItemId() for the item you want to change, then work on that id on further actions.
Comment: I edited and posted my code currently
Comment: Onur kardes. getItemId hep ayni int geri veriyo.
Answer: First I will explain view recycling then I will get to your issue. Say you can see 8 list items on the screen at one time. When you scroll the list down and item number 1 goes off screen and item number 10 comes on screen, item number 10 will reuse item number 1s view. This means that item number 10 will look exactly like item number 1 unless you update it accordingly in your adapters getView method.
Now that we understand View recycling you can see why other items will have your new drawable even though you didn't click them. You will have to store in your dataset that you use for your adapter which items have that image, whether it be an ArrayList in the Adapter or it be a custom object that the Adapter uses. Then in the getView of your adapter you could do the following:
if(hasImage)
{
    ColorStateList sColorStatePlaying;
    ColorStateList sColorStateNotPlaying;

    sColorStatePlaying = ColorStateList.valueOf(context.getResources().getColor(R.color.colorPrimary));
    AnimationDrawable animation = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.anim_current_song);
    ImageView EQ_ANIM = (ImageView) view.findViewById(R.id.imageView_eq_animation);
    EQ_ANIM.setVisibility(View.VISIBLE);
    EQ_ANIM.setImageDrawable(animation);
    EQ_ANIM.setImageTintList(sColorStatePlaying);
    animation.start();
}
else
{
    // Set the default image
}

Edit:
You should add an else statement in your getView
    if(Main.songService.svc_mpcontroller != null && Main.global_music_controller != null) {
        if (AL_songlist.get(position).getID() == Main.global_music_controller.get_current_id()) {
            ColorStateList sColorStatePlaying;
            ColorStateList sColorStateNotPlaying;

            sColorStatePlaying = ColorStateList.valueOf(context.getResources().getColor(R.color.colorPrimary));
            AnimationDrawable animation = (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.anim_current_song);
            holder.imgEQAnimation.setVisibility(View.VISIBLE);
            holder.imgEQAnimation.setImageDrawable(animation);
            holder.imgEQAnimation.setImageTintList(sColorStatePlaying);
            animation.start();
        }
    }
    else
        holder.imgEQAnimation.setVisibility(View.GONE);

Comment: hmmm... Ok I will try it. So if I understand it right I could make a list where for example I put boolean values (default = all false). And the one Ive clicked I have to make true. And then I have to check it everytime in getView if list.get(position) is true or not ? Did I understand it right ?
Comment: Yep thats how it works. What is your adapters dataset currently? If you were to call list.get(position), what would it return?
Comment: I still got the same problem. My dataset is a custom object array where one of them have an boolean value which shows that the Image has to be changed
Comment: Could you add the `getView` code from your adapter to the question and I'll have a look.
Comment: I did. Im really thankfull to you that you take your time to help me.Somehow this is still making these dublicates
Comment: I've modified my answer, let me know if that helps.
Comment: Thats really funny mate. I did it and it worked and then I watched out for a new comment by you and now I see you wrote the same solution :D Thanks for everything !
Comment: No problem, happy to help :)

Change one element of ListView


How to fetch frames with Jsoup?

Question:

    <frameset cols="180,590,*" border="0">
        <frame src="test.html" name="main" noresize="" scrolling="no" marginwidth="0" marginheight="0">
        <frame src="http://www.test.com/my.php" name="right" noresize="" scrolling="auto" marginwidth="0" marginheight="0">
            #document

                        <title>TEST</title>

        </frame>
    </frameset>

I'm parsing a webpage. But I have a problem with it.
What is the #documnet?
And how can I parse  below #document using Jsoup?
Comment: Possible duplicate of [What does #document mean?](http://stackoverflow.com/questions/21474605/what-does-document-mean)
Comment: You can read about it here:
http://www.w3schools.com/jsref/dom_obj_document.asp
Answer:
And how can I parse  below #document using Jsoup?

You can see #document as a "virtual" element. Jsoup won't see it. It is not present in the actual HTML code neither.
What you want is fetching the frames with Jsoup. See below:
Document doc = ...; // HTML page containing the frameset

Document mainFrameDocument = Jsoup.connect(doc.select("frame[name=main]").absUrl("src")).get();

Document rightFrameDocument = Jsoup.connect(doc.select("frame[name=right]").absUrl("src")).get();

How to fetch frames with Jsoup?


Caching with ServiceStack + Redis: How to not return System.Object and return DTO instead?

Question: In all of the examples I see like this, caching in ServiceStack methods must have a return type of System.Object. Is there a newer/updated documentation that allows for a normal DTO to be returned?
For example, it would be nicer if this Get method didn't return an "object" (pulled from ServiceStack documentation).
public class OrdersService : Service
{
    public object Get(CachedOrders request)
    {
        var cacheKey = "unique_key_for_this_request";
        return base.RequestContext.ToOptimizedResultUsingCache(base.Cache,cacheKey,()=>
            {
                //Delegate is executed if item doesn't exist in cache
                //Any response DTO returned here will be cached automatically
            });
    }
}

Comment: What benefit would you get from returning a DTO at this point?
Comment: It would be a bit more explicit, and consistent as the rest of the service methods return concrete types.
Comment: Fair enough - I don't really think it's worth it though, as the return type is specified by the IReturn<> interface that your CachedOrders type implements. Keeping it as an object gives greater flexibility among other things, for example if you wanted to return an HttpError.
Answer: I use this extension, but you lose the optimizations based on the context of the request. (json, compressed, etc)
public static class ICacheClientExtensions
{
    public static T ToResultUsingCache<T>(this ICacheClient cache, string cacheKey, Func<T> fn, int hours = 1) where T : class
    {
        var cacheResult = cache.Get<T>(cacheKey);
        if (cacheResult != null)
        {
            return cacheResult;
        }
        var result = fn();
        if (result == null) return null;
        cache.Set(cacheKey, result, TimeSpan.FromHours(hours));
        return result;
    }
}

public class MyService : Service
{
    public Data Get(GetData request)
    {
        var key = UrnId.Create<Data>(request.Id);

        Func<Data> fn = () => Db.GetData(request.Id);

        return Cache.ToResultUsingCache(key, fn);
    }

    [Route("/data/{id}")]
    public class GetData: IReturn<Data>
    {
        public int Id{ get; set; }
    }
}


Why is ng-repeat being commented in devtools?

Question: When I try to populate the options, nothing shows. In devtools, the ng-repeat seems to be commented out.  See here:

The option tag is not being recognised. I have tested my api's and they are working. Here is my HTML:

Welcome ....

Log Out</href>

Home</href>

       Search
   <input type="text" list="dataList">

             <datalist id="dataList">
        <option ng-repeat="type in carCtrl.types" value="{{type}}"> Type {{type}}</option>
      </datalist>

Here is my angularjs:
module.controller('CarController', function (registerCarAPI, $window, $sessionStorage, carAPI, carOwnerAPI, carTypeAPI, $scope) {
    this.listMessage = "Please register your car here:";
    this.types = carTypeAPI.query();
    this.cars = carAPI.query();

    this.ownerCars = carOwnerAPI.query({'ownerId': $sessionStorage.owner.OwnerID});

    this.registerCar = function (car) {

        car.ownerId = $sessionStorage.owner.OwnerID;
        registerCarAPI.save(null, car,
                function () {
                    $window.location = 'viewCars.html';
                },
                function (error) {
                    console.log(error);
                }

        );
    };

});

Comment: The only reason angular would do that is if carCtrl.types was empty or non existent. Are you sure it's a valid set of data? IF so, can you post what it looks like?
Comment: Can you share your rendered output? Just the datalist element, surrounding angular comments, and its contents should be sufficient.
Comment: I have added a photo at the start of the post. Is this enough?
Answer: You're using it like a select object which might be causing the issue. Try changing your datalist html to be like this:
<datalist id="dataList">
  <option ng-repeat="type in carCtrl.types" value="{{type}}">
</datalist>

Comment: Thanks for the reply. Unfortunately this isn't the issue.


Fresh installation of Lubuntu 16.04 from a DVD on a MacBook

Question: I have a MacBook "Core 2 Duo" 2.2 13" (White-SR) 2.2 GHz Core 2 Duo (T7500) with single boot - Ubuntu 17.04 on.
I want to make a fresh installation of Lubuntu 14.04.1 LTS (mac) from a DVD.
I have tried to start the laptop holding the 'c' key down until the DVD drive starts and then release it but no luck.
I also tried holding the 'option' key down and that gets me to a 'menu' with the only option to start from a hard drive named 'windows' (?) but no DVD drive option. If the hard drive is selected the system does not boot.
**pressing 'esc' during the boot process gets me to the grub menu and/or console. anything i can do from here? **
p.s. I also tried with another .iso CD that I know for sure works
and did not get any results.
so probably it's not the specific DVDisc that causes the problem.
thanks for reading!
Answer:
Connect a USB keyboard to the Mac.
Reboot the Mac and hold the Option key (or Alt key if it's a PC keyboard).

You should then be able to boot from the DVD.
Comment: i do not have a usb keyboard at my disposal at the moment... any other solution? also can you please check my edited question? the native keyboard works when in the grub terminal
Comment: I dint read you correctly, sorry. I'm out if ideas at the moment.


Drupal 7 Module Updates fail using the User Interface with a 500 server error

Question: I have a Drupal 7.15 site we are testing out, and when I provisioned everything I was able to use the module updater/installer through the web admin interface with no issues.  Now I seem to get a 500 ISE every time I try to install or update a module (either through link or direct upload).
I do not see anything helpful in the system log or in apache's error log.
I can see when I provide a URL or file, the Drupal server does grab it, puts it in /tmp/update-cache/ as it should (I have Drupal config'ed to use /tmp in File System->Temporary Directory), and it extracts the tar.gz to /tmp/update-extraction/
The files never get moved over to sites/all/modules.  Permissions are

drwxrwxr-x 27 apache webeditors 4096 Sep 12 09:43 modules

apache is a member of webeditors.
Any help is appreciated!
Answer: Propably you need to increase thr PHP Memory
The quick way:
add ini_set('memory_limit','256M'); to your settings.php
Universal way:
 edit this limit in your php.ini. by finding

php_value memory_limit 32M and changing to appropriate limit

To find php.ini location run a phpinfo();


Scratch on wall - ceramic tile

Question: by accident I scratch ceramic tile in my bathroom while cleaning. Do you have any idea how can I remove/(paint?)/fix this?
I tried a lot of home products (at start I though its just a tech pencil), but without result.
Wall specification: https://www.paradyz.com/en/catalog/elia/elia-bianco-sciana-struktura-rekt
Scratch:

EDIT: Thanks for all the answers, I'm going to try them soon. I will let you know about the results.
Comment: Maybe try a mild abrasive cleaner or conventional toothpaste.
Comment: Are you sure that's a scratch? If you drag your fingernail across it does it catch or remove the mark?
Comment: I tried scrub with a sponge, "magic sponge", pencil eraser and some other home stuff. It not changing at all. Maybe this is somehow like metal trail, but when I drag my finger across I don't feel this mark.
Comment: Toothpaste without any result.
Comment: Tile and grout cleaner/haze remover, like an acid wash?
Comment: If it is a scratch You can not "remove" it by scrubbing or other means of cleaning. A scratch is portion of the surface that has been removed thereby exposing the material under it.
Answer: Try alkyd (oil-based) paint. Yes, paint. If the tile off white and if you have a scrap somewhere, take it to a paint store and they can sell you a match. The crack will disappear or only you will know.
Answer: Metal marks can sometimes be removed with lacquer thinner or acetone. Try a cloth dampened on a corner with the solvent. I have had some good results on similar looking marred tile.
Comment: I have had much success with lacquer thinner on removing all sorts of marks on surfaces
Answer: In the past I have "borrowed" some nail polish from my wife that was a similar hue. I then, painted over it with a ceramic tile gloss (you can buy it at any home improvement store) and set it with a hair dryer (even better a heat gun, as stated above on low, if you have one). It worked and no one knew it was there unless you knew exactly where to look.
Comment: Hello, and welcome to Home Improvement. Thanks for the answer; keep 'em coming!
Answer: Try a white wax crayon like from a kid's art kit. Or a white wax putty stick; the type used for furniture scratch repair. Rub it all along the crack, rub off excess gently with a rag, then heat a bit with a blow dryer or heat gun (on low setting).

Scratch on wall - ceramic tile


Suppress record only in one group (crystal XI)

Question: My report is a list of names grouped into constituencies. There can be one name to many constituencies. Each name should show up in ALL groups where it has that constituency. (In the example below Mary has both A and B so she should be in both of those groups). The last group should be on all the remainder people who don't fall into any of the other groups. (Jack has constituency C that I am not interested in grouping on.)
Example (as I want it to be):
Constituency A

John J Smith
Mary Elmore

Constituency B

Brad Jones
Mary Elmore

None of the above Constituency

Jack T Ripley

I have a left join on constituency to name and have grouped on the constituency field. In the group options I have it set to "put all others together, with name:  None of the above Constituency"
It is showing the names in each group as I want. The problem is in the last, catch-all group. It's shows all the people who have a blank (not relevant constituency) or null constituency. I want it to only show those that are not showing up in any of the other groups. How do I suppress those only in the last group?
Example (as it is currently):
Constituency A

John J Smith
Mary Elmore

Constituency B

Brad Jones
Mary Elmore

None of the above Constituency

Jack T Ripley
Brad Jones

(Brad has constituency B and C but I don't want him to show in the last group because he already shows up in B.)
I am exporting out of a Raiser's Edge database and do not have a lot of flexibility with my queries.
Thank you for any help or advice you can provide.
Comment: can you show us your sql command?
Answer: First idea off the top of my head: Make a custom SQL statement within Crystal that returns a new field, which is just the combined collection of unique Constituencies each person belongs to. You can link this statement to the rest of your tables and treat it like just another table.
So for Mary the field would be something like Constituency A, Constituency B, John's field would be Constituency A, and Jack's field would be... empty.
Then rather than display that final group, make a subreport to display every user where the new field is blank. (You can make the subreport look exactly like it's just another group, for bonus points.


Resolution of the knapsack approach by bruteforce in python

Question: I'm actually trying to resolve the knapsack problem with bruteforce. I know it's not efficient at all, I just want to implement it in python.
The problem is it take long time. In my point of view too much time for a bruteforce. So maybe I make some mistakes in my code...
def solve_it(input_data):
# Start the counting clock
start_time = time.time()

# Parse the input
lines = input_data.split('\n')
firstLine = lines[0].split()
item_count = int(firstLine[0])
capacity = int(firstLine[1])

items = []

for i in range(1, item_count+1):
    line = lines[i]
    parts = line.split()
    items.append(Item(i-1, int(parts[0]), int(parts[1])))

# a trivial greedy algorithm for filling the knapsack
# it takes items in-order until the knapsack is full
value = 0
weight = 0
best_value = 0

my_list_combinations = list()
our_range = 2 ** (item_count)

print(our_range)

output = ""

for i in range(our_range):
    # for exemple if item_count is 7 then 2 in binary is
    # 0000010
    binary = binary_repr(i, width=item_count)

    # print the value every 0.25%
    if (i % (our_range/400) == 0):
        print("i : " + str(i) + '/' + str(our_range) + ' ' +
            str((i * 100.0) / our_range) + '%')
        elapsed_time_secs = time.time() - start_time
        print "Execution: %s secs" % \
            timedelta(seconds=round(elapsed_time_secs))

    my_list_combinations = (tuple(binary))

    sum_weight = 0
    sum_value = 0

    for item in items:
        sum_weight += int(my_list_combinations[item.index]) * \
            int(item.weight)

    if sum_weight <= capacity:
        for item in items:
            sum_value += int(my_list_combinations[item.index]) * \
                int(item.value)

        if sum_value > best_value:
            best_value = sum_value
            output = 'The decision variable is : ' + \
                str(my_list_combinations) + \
                ' with a total value of : ' + str(sum_value) + \
                ' for a weight of : ' + str(sum_weight) + '\n'
return output

Here is the file containing the 30 objects :
30 100000 # 30 objects with a maximum weight of 100000
90000 90001
89750 89751
10001 10002
89500 89501
10252 10254
89250 89251
10503 10506
89000 89001
10754 10758
88750 88751
11005 11010
88500 88501
11256 11262
88250 88251
11507 11514
88000 88001
11758 11766
87750 87751
12009 12018
87500 87501
12260 12270
87250 87251
12511 12522
87000 87001
12762 12774
86750 86751
13013 13026
86500 86501
13264 13278
86250 86251

I dont show the code relative to the reading of the file because I think it's pointless... For 19 objects I'm able to solve the problem with bruteforce in 14 seconds. But for 30 objects I have calculated that it would take me roughly 15h. So I think that there is a problem in my computing...
Any help would be appreciated :)
Astrus
Answer: Your issue, that solving the knapsack problem takes too long, is indeed frustrating, and it pops up in other places where algorithms are high-order polynomial or non-polynomial.  You're seeing what it means for an algorithm to have exponential runtime ;)  In other words, whether your python code is efficient or not, you can very easily construct a version of the knapsack problem that your computer won't be able to solve within your lifetime.
Exponential running time means that every time you add another object to your list, the brute-force solution will take twice as long.  If you can solve for 19 objects in 14 seconds, that suggests that 30 objects will take 14 secs x (2**11) = 28672 secs = about 8 hours.  To do 31 objects might take about 16 hours.  Etc.
There are dynamic programming approaches to the knapsack problem which trade off runtime for memory (see the Wikipedia page), and there are numerical optimisers which are tuned to solve constraint-based problems very quickly (again, Wikipedia), but none of this really alters the fact that finding exact solutions to the knapsack problem is just plain hard.
TL;DR: You're able to solve for 19 objects in a reasonable amount of time, but not for 30 (or 100 objects).  This is a property of the problem you're solving, and not a shortcoming with your Python code.


What does realm divide do in Shogun 2

Question: What are all the effects and how long does it last? Can the effects be influenced in anyway?
Answer: When you achieve enough fame, the shogun considers you a threat and orders all other clans to declare war. This includes allies who you may have had since the start of the game.
The mechanism by which this work is that all your relationships are set at -40 and continue to decrease as turns pass. Now, any new vassels you create will not be affected by this penalty (nor will their relationships).
Comment: So it's less "realm divided" as "realm solidly and permanently united *against you*"
Comment: Thanks for the reply, but it doesn't exactly fit with what i've seen so far. I've just had it happen to me, that's why i'm asking. On Medium, i get a -20 relation penalty with, and not all the other clans have declared war on me yet. Good to know i can get rid of the relation penalty though.
Comment: I have experienced that on Legendary difficulty, newly created vassals after the Realm Divide, still get the Realm Divide penalty. I thought first time it was an aberration, but happened to my second legendary campaign too. It seems to be unique to Legendary. I did not see this at very hard level (or I don't remember that I did).
Comment: @Bubble the penalty is based on difficulty level.  Also, its a growing penalty so it doesn't guarantee war.

What does realm divide do in Shogun 2


Thermopride OL5-85 oil furnace no longer works

Question: We bought this old house where the oil furnace worked for a while. Now it does not work even after adding enough oil and priming the furnace. We have already pushed the reset button..so I do not dare to do it again..Would you please tell me what I should do? Thank you very much!
P.S.: The furnace is a Thermopride OL5-85 one.
(Yes this is a duplicate of what I deleted under another name. I just want to have some privacy.)
Answer: Call a licensed oil burner service technician (or a company employing such technicians) and have the furnace inspected, then serviced or replaced. Typically your fuel oil supplier is also an employer of service technicians.
Likely normal servicing is all that is required; this is typically performed on an annual basis, rather than waiting until the furnace no longer works.
This really is not a prime area for DIY.


How to get data from a pl/sql function if a parameter have more than one value in function with single parameters

Question: I am developing a procedure in pl/sql that get a data set from a cursor executed in a function. For example:
Function:
f_process_data(id_process IN NUMBER, id_product IN NUMBER)

Returns :
v_result_cursor sys_refcursor;

But the problem is that in the search of the cursor I need to send at time more than one id_product. Something like this:
id_product: 1240 (sausages)
id_product: 1260 (ham)
¿How can I send (or get) more than one product in the function?
I understood that it's possible with a loop, but how?
Something like this(?):
v_sausage := 1240;
v_ham := 1260;

LOOP
   IF v_count = v_sausage OR v_count = v_ham THEN
   v_result_cursor := f_process_data(1, p_id_product);
   END IF;
   FETCH v_result_cursor
   INTO v_id, v_id_product;
   EXIT WHEN v_result_cursor%NOTFOUND;
END LOOP;

I expected that v_id and v_id_product has been recorded in a collection including the results from the id_product 1240 and 1260.
But, if the business rules changes and is not only 2 products, how about 100 or 1000 products?
Note: the cursor from the function it's not possible to modify, the id_product must be sent one by one.
CURSOR cu_get_value_products IS
SELECT value FROM supplies WHERE id = p_id and id_product = p_id_product;

Comment: @Code Novice The function calls another function that calls another function that opens the cursor, something like f_open_cursor(query) returns sys_refcursor and inside this function only: OPEN cursor FOR query; The example than I posted is similar but is not exactly as original due to protect those code, sorry for that -_-
Comment: Possible duplicate of [Passing an array of data as an input parameter to an Oracle procedure](https://stackoverflow.com/questions/2885575/passing-an-array-of-data-as-an-input-parameter-to-an-oracle-procedure)
Comment: @reymagnus How would you like to format the product parameter?  As in... what is your preference?  Do you want the parameter to be a comma separated list if product ids? `1001,1002,1058,2105` as a VARCHAR2?  Do you want to instead pass an array/collection into your `f_process_data()` as a  Function after first building up that collection with product ids?  There are many solutions to your question.
Comment: @Code Novice The cursor in the function gets only one id_product by time, and it's not possible to change.
Comment: @reymagnus Ok so what you are wanting then... is to run the Cursor for every Product_ID that comes into the f_process_data() Function.  If that is the case you will no longer be returning a ref_cursor and would need to return something else.  If you are not able to alter the Cursor that is.  So my question is now, can you change the Return type of your f_process_data() function to instead return a Collection of the data you wish to Parse?
Comment: @reymagnus If you are not able to alter the f_process_data() function or the code within it you would then need to Loop over your Function using the Product_ids.  Something like... `FOR r IN products.FIRST .. products.LAST LOOP f_process_data(products(r).product_id) END LOOP`.
Comment: @reymagnus Is your Cursor within the f_process_data() function actually defined as `CURSOR cu_get_value_products IS ... ;`?  If so how is that Cursor being Returned as a `SYS_REFCURSOR`?
Comment: @Code Novice, the function f_process_data returns sys_refcursor, because cursor cu_get_value_products is fetched into sys_refcursor. The most important here is that this function and cursor is not allowed to modify. I vote for the solution with a loop in the procedure that invokes the function but I don't know if I need to store the id_products in a for example an array but what if then its needed 100 or 1000 id_products?
Comment: @reymagnus Perhaps I'm just not privy as to how you are taking a static Explicit CURSOR defined within your function and then converting it to a SYS_REFCURSOR so that then it can be returned?  How is this conversion performed?
Comment: Because inside the function the cursor is fetched into a sys_refcursor, and the function returns sys_refcursor. I am not sure if I am clear in this point.
Comment: @reymagnus Can you post a snippet of how the Static Cursor is being FETCHed into a sys_refcursor?  Using the Pseudro code --> when I try to do `FETCH static_cursor INTO ref_cursor;` it fails.  I'm simply curious how this is done.
Answer: With somewhat limited information the below is what I've come up with.  I still have no clue what is happening with your STATIC Cursor which you mentioned in your question is defined in your f_process_data() Function.  Since I don't know the full code in this function I simply wrote my own and declared the CURSOR as SYS_REFCURSOR as that is what the function returns.
Please let me know if this works or if I'm missing some important information.  I feel like I'm lacking crucial information in order to provide a useful solution to you.
The mock-up table I created called Products contains the following columns and data.  See image.

DECLARE

  /* Store Ref Cursor returned by f_process_data() Function */
  v_result_cursor   SYS_REFCURSOR;

  /* Declare Record so we can store the data FETCHed from the Cursor */
  rec_products      products%ROWTYPE;

  /* Declare a couple Product Variables for Proof of Concept */
  v_sausage         NUMBER;
  v_ham             NUMBER;

  /* Store output */
  n_id              NUMBER;
  v_id_product      VARCHAR2(100);

  /* Declare Type of TABLE NUMBER */
  TYPE  nt_type IS TABLE OF NUMBER;

  /* Create Array/Table/Collection of type nt_type to store product ids */
  nt_product_ids    nt_type;

  /* Returns a Ref Cursor based on the product_id used as Input to this function */
  FUNCTION f_process_data(p_id_process IN NUMBER, p_id_product IN NUMBER)
  RETURN SYS_REFCURSOR
  AS
    /* Declare Ref Cursor that will be Returned */
    rc_result_cursor   SYS_REFCURSOR;

  BEGIN
    /* Open Ref Cursor based on Product ID parameter */
    OPEN rc_result_cursor FOR SELECT * FROM products WHERE item_id = p_id_product;

    RETURN rc_result_cursor;

  END f_process_data
  ;

BEGIN

  /* Set Product Variables to IDs */
  v_sausage       := 2002;
  v_ham           := 2009;

  /* Store product ids into a Number Table so we can Loop thru it */
  nt_product_ids  :=  nt_type (v_sausage,v_ham);

  FOR r IN nt_product_ids.FIRST .. nt_product_ids.LAST
  LOOP
    /* Get Ref Cursor using SINGLE Product ID */
    v_result_cursor := f_process_data(1, nt_product_ids(r));

    LOOP

    FETCH v_result_cursor INTO rec_products;

    n_id            :=  rec_products.item_id;
    v_id_product    :=  rec_products.item;

    EXIT WHEN v_result_cursor%NOTFOUND;

    dbms_output.put_line('Product_id: ' || n_id);
    dbms_output.put_line('Product: ' || v_id_product);

    END LOOP; /* Cursor Loop */

    /* Close Cursor */
    CLOSE v_result_cursor;

  END LOOP; /* Product IDs Loop */

EXCEPTION WHEN OTHERS
  THEN CLOSE v_result_cursor;

END;

Comment: You are right. The cursor is static and this is the solution that I could apply. Thanks so much.
Comment: As per your requirements I was able to create this solution without altering your Function - `FUNCTION f_process_data(p_id_process IN NUMBER, p_id_product IN NUMBER) RETURN SYS_REFCURSOR`... other than my adding `p_` as I like to reference my parameters in that manner.
Comment: I have tried to implement this and get this error: ORA-01001: invalid cursor. It crashes just before to enter second loop.
Comment: Once I have access to database, I will show my code.
Comment: @reymagnus Make sure the cursor is not being closed.  If you attempt to Fetch from a Cursor that was previously closed this is one way you will get the error 'Invalid Cursor'.
Comment: It's solved, for now. It was because to passing null values as a parameter in the function, but this error is rare.
Comment: @reymagnus Ok great!  Glad you figured it out.
Answer: In order to send more than one product to be processed at a time, create a user defined Table Type in your database called ProductList. You can then send a Product list into a stored procedure as a parameter.
Comment: But, how it works if the function and cursor only receive one parameter value at a time? I am not familiar with lists as a parameter in a pl/sql function, for now...
Comment: Don't use a function or a cursor.
Comment: The use of function or cursor is not optional because this objects can not be modified or dropped and necessarily must use them.  The global stored procedure invokes the function f_process_data and this function executes a cursor, that's It.


Excel file gets corrupted after I write into it using ExcelJS

Question: I have a function where I need to write a value in an excel file at a specific row.
<code>var Excel = require('exceljs');

 setExcelData: function (sheetName, keyword, value123, callback) {
    var workbook = new Excel.Workbook();
    workbook.xlsx.readFile('example.xlsx').then(function () {
        var worksheet = workbook.getWorksheet(sheetName);
        var y = worksheet.getColumn(1).values;
        for (var i = 1; i <= y.length; i++) {
            var q = worksheet.getRow(i).values;
            if (q[1] == keyword) {
                worksheet.getRow(i).getCell(2).value = value123;
                workbook.xlsx.writeFile('example.xlsx');
                break;
            }
        }
    });
    callback();
},
</code>
First I read the file and find the row where the keyword is present in first column. Then I try to write "value123" in the second column of the same row. But when i execute this function, the excel file gets corrupted and I cannot open it anymore.
Answer: I faced the same issue in Ubuntu if I am modifying the file in LibreOffice. So i created a doc in google drive as suggested in
https://github.com/guyonroche/exceljs/issues/35#issuecomment-283440743.  and downloaded to perform modification on excel
Below is the code worked for me.
<code>    var Excel = require('exceljs');

    async function excelOp() {
        let workbook = new Excel.Workbook();
        workbook = await workbook.xlsx.readFile('question_50508131.xlsx'); // replace question_50508131.xls with your file
        let worksheet = workbook.getWorksheet('Inventory'); // replace solution with youe sheet name
        let columnValues =  worksheet.getColumn(1).values;
        for (let row = 1; row <= columnValues.length; row += 1) {
            var rowValues = worksheet.getRow(row).values;
            if (rowValues[1] == 'Laptop') { // replace Laptop with required value
                worksheet.getRow(row).getCell(2).value = 350; // replace 350 with replacable value
                workbook.xlsx.writeFile('question_50508131.xlsx');
                break;
           }
       }
   }

  excelOp();
</code>
PreModification Excel data

PostModification Excel data


Japanese input candidate window appears at the bottom after upgrading Ubuntu from 21.10 to 22.04

Question: I upgraded from Ubuntu 21.10 to 22.04, and when typing in Japanese, the candidate dialog (for converting a word into kanji, or into something else) appears at the bottom of the screen instead of near the text input I'm currently typing on. How can I fix this?
More details:
It should appear next to the text input, just like before upgrading Ubuntu.
I had Ubuntu 21.10 Impish, now I have 22.04 Jammy. I fixed it with the answer I posted.
Comment: @guiverc Ubuntu 21 does exist. The one I had is called ubuntu 21 Impish. Now I have 22.04 jammy. Rock n roll!
Comment: Ubuntu 21.10 is *impish indri*, and it's a *year.month* format release and **not** a *year* format release.  Ubuntu releases using the *year* format are *snap* only, thus cannot use the `apt`, `dpkg` and *like deb* package format commands.  The *year* based releases with 10 years of supported life (*without need for ESM*) and are closest to the LTS releases of *year.month* format releases. Ubuntu 21.10 or *impish indri* is a non-LTS and the last non-LTS before the LTS in the development cycle that started with 20.10 and ends with 22.04 LTS and not a *year* product
Comment: Canonical/Ubuntu introduced the *year* products in 2016 and are used for server systems only, useful for IoT, appliance & devices, and also cloud use (they're faster to *spin* up).  When you upgrade to the next release; no user-packages change (a benefit of the *snap* system which *deb* packages does not allow for)....  They are **not** intended for desktop use (desktop packages are generally packaged as *deb* packages being intended for the *year.format* products) and the *year* format products are not supported by *flavors* of Ubuntu.
Comment: Yes I agree, and the Ubuntu I had is Ubuntu 21 Impish. Cheers
Answer: I was able to solve it by executing:
<code>gsettings set org.gnome.desktop.interface gtk-im-module 'ibus'
</code>
This fixed the problem permanently, including after rebooting.
Solution found here:
https://bugs.launchpad.net/ubuntu/+source/im-config/+bug/1969637


WSO2 Identity Server - distinguish users from Primary userstore and secondary userstore

Question: Is it possible to distinguish whether the user is from the primary userstore or a secondary user store? I would like to prevent the user from modifying his profile if he is from a secondary userstore.
Answer: If the user is from secondary user store, his user name will contain the user store domain he contains.
The username follows following format,
<code>userstore/username@tenantdomain
</code>
You can get user store domain from this.
In primary user store users, userstore part will not be contained in username.
Comment: Does this require "Use user store domain in local subject identifier" in Service Provider settings to be checked?
Comment: I think so, but please check and make sure.
Answer: As explained in the above answer if you have a secondary user store set up with the name "WSO2.COM" and a user with name firstname.lastname@example.com. Actual username to be used to login should be "email@example.com".  You can find more information on how to set up the secondary user store please refer to links [1],[2]. If would like to prevent user to modifying the profile. Please enable the read-only mode as explained in [2].
[1] https://medium.com/@pubududp/how-to-use-active-directory-as-a-secondary-user-store-in-tenant-mode-for-wso2-products-f49ac4829e41#.2ujax4wud
[2] http://pushpalankajaya.blogspot.com/2013/09/how-to-write-custom-user-store-manager.html
Cheers,
Pubudu.


ant cannot identify my jar files at all

Question: I have my jar files in Assignment2\lib folder and my build file is in Assignment2. The name of the jar file is Assignment1.jar The following is how I tried to compile my Assignment2 from build file through ant.
<project name="Assignment1" default="run" basedir=".">
    <property name="classes" value="classes" />
    <path id="project.class.path">
        <pathelement location="src"/>
        <pathelement path="${java.class.path}/"/>
        <pathelement path="${additional.path}"/>
    </path>
    <path id="lib.jars">
        <fileset dir="lib" includes="**/*.jar" />
    </path>
......
<target name="compile" description="compaling java files with Assignment2">
        <mkdir dir="build"/>
        <javac srcdir="src" destdir="build" debug="on" failonerror="true">
            <classpath refid="project.class.path"/>
            <classpath refid="lib.jars"/>
        </javac>
    </target>
<Project/>

I am getting compile errors. I'm using windows. Is that the problem? Is there any way to compile?
Comment: `lib.jars` path seems ok. I use the same structure in windows with no problems. From which path you execute ant? Take in account that basepath is `.`, so you should run from `Assignment2/`. Also check that in `lib/` are all requiered jars.
Answer: hey guys thanx for the answers actually i found probelm. i was trying to use a jar file created by netbeans files. Apparently netbeans jar files can be used only by netbeans. at the end i made a new jar file of Assingment1 and used it. now everything is fine. Thanx again for the answers.
Answer: Well,Everything looks good to me but, you can try the following to validate the same,

Check if the lib folder has all the necessary library jars required to compile you application
You can try assigning the relative path of the lib folder to a property and refer it in the classpath eg: Property lib value=".\Lib"
Try the following before you call the compile target to see the list of jars being included in the classpath

<pathconvert property="libjars" refid="lib.jars"/>
<echo>libjars is ${classpathProp}</echo>

ant cannot identify my jar files at all


improper integral with logarithm $x \mapsto \infty$

Question: I have a lot of doubts about improper integrals with logarithm.
In those  integrals in which there are other functions apart from the logarithm usually is ok. If there is just the logarithm it is a bit harder for me.
For example considering
$$\int_{1}^{\infty }(Log[x+1]-Log[x])dx$$
$$\forall x\in [1,\infty)\, \, \, \, \, \, \, (Log[x+1]-Log[x])=Log\left [\frac{x+1}{x}  \right ]
$$
$$Log\left [\frac{x+1}{e^{x}}  \right ]\leq Log\left [\frac{x+1}{x}  \right ]\, \, \, \, \forall x\in [1,\infty)$$
$$\int_{1}^{\infty }(Log\left [\frac{x+1}{e^{x}}  \right ])dx=\int_{1}^{\infty }(-x+Log\left [{x+1}  \right ])dx$$
$$
x \mapsto \infty \, \, \, \, \, \, \, -x+Log[x+1]\sim -x $$
$$\int_{1}^{\infty }-x \,dx$$ The integral is divergent.
So for comparison theorem for improper integrals
$$\int_{1}^{\infty }(Log[x+1]-Log[x])dx$$ should be divergent.
Is it correct?
Is the correct choice in those cases to use the exponential in the logarithm to create an inequality that when later we will evaluate the second improper integral leaves the logarithm . Do you have any techniques useful in those cases?
Answer: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

With $\ds{\Lambda > 1}$:

\begin{align}
&\color{#f00}{\int_{1}^{\Lambda}\bracks{\ln\pars{x + 1} - \ln\pars{x}}\,\dd x} =
\int_{2}^{\Lambda + 1}\ln\pars{x}\,\dd x - \int_{1}^{\Lambda}\ln\pars{x}\,\dd x
\\[5mm] = &\
\bracks{\pars{\Lambda + 1}\ln\pars{\Lambda + 1} - \pars{\Lambda + 1} - 2\ln\pars{2} + 2} -
\bracks{\Lambda\ln\pars{\Lambda} - \Lambda}
\\[5mm] & =
1 - 2\ln\pars{2} +\
\underbrace{\Lambda\ln\pars{1 + {1 \over \Lambda}}}
_{\ds{\to\ 1\ \mbox{as}\ \Lambda\ \to\ \infty}}\ +
\underbrace{\ln\pars{\Lambda + 1}}_{\ds{\to\ \color{#f00}{\infty}\ \mbox{as}\ \Lambda\ \to\ \infty}}\quad
\color{#f00}{\to \infty}\ \mbox{as}\ \color{#f00}{\Lambda \to \infty}
\end{align}
Answer: Why not simply compute the antidericative $$\int \log(y)\,dy=y \log (y)-y$$ So $$\int \left( \log(1+x)-\log(x)\right)\,dx=-x \log (x)+(x+1) \log (x+1)$$ So $$f(t)=\int_1^t \left( \log(1+x)-\log(x)\right)\,dx=(t+1) \log (t+1)-t \log (t)-2\log(2)$$ $$f(t)=(t+1)\left(\log(t)+\log(1+\frac 1t)\right)-t \log (t)-2\log(2)$$ $$f(t)=(t+1)\log(1+\frac 1t)+\log(t)-2\log(2)$$ Now using Taylor $$\log(1+\frac 1t)=\frac{1}{t}-\frac{1}{2 t^2}+O\left(\frac{1}{t^3}\right)$$ $$(t+1)\log(1+\frac 1t)=1+\frac{1}{2 t}+O\left(\frac{1}{t^2}\right)$$ $$f(t)=1-2\log(2)+\log(t)+\frac{1}{2 t}+O\left(\frac{1}{t^2}\right)$$
Answer: Your argument doesn't do the job since $\int_1^{b} -x\,dx \to -\infty$ as $b \to \infty$ and hence you have shown that $-\infty \leq \int_1^{\infty} (\log(x+1)-\log(x))\,dx$, which we could all agree on before your argument.
Perhaps use a different bounding argument. By the Mean Value Theorem, for each $x \in (1, \infty)$ there is some $c_x \in [x, x+1]$ such that $\log(x+1) - \log(x) = \log'(c_x)(x+1-x) = \frac{1}{c_x} \in \left[\frac{1}{x+1}, \frac{1}{x}\right]$ and hence, $\frac{1}{x+1} \leq \log(x+1)-\log(x) \leq \frac{1}{x}$.
Comment: $\frac 1x>\frac1{x+1}$.
Comment: @Dr.MV Totally correct! Thanks for the reminder.
Comment: You're welcome Tom.  My pleasure.  -Mark
Answer:
In THIS ANSWER, I showed using only Bernoulli's Inequality and the limit definition of the exponential function that the logarithm function satisfies the inequalities
$$\frac{x-1}{x}\le\log(x)\le x-1 \tag 1$$

Therefore, using $(1)$ we find
$$\frac{1}{x+1} \le \log\left(1+\frac1x\right)\le \frac{1}{x}$$
Since, the integral $\int_1^\infty \frac{1}{x+1}\,dx$ diverges, the integral of interest does also.


dynamic Check box android

Question: I've created check box dynamically in a table layout. I need my first check box should be enabled at the start and rest of them should not be enabled, then if i click my first check box second CB should be enabled then so on..
Table creation with checkbox.
TableLayout ll = (TableLayout) findViewById(R.id.tablelayout22);

final TableRow tr = new TableRow(this);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

tr.setId(i);
tr.setLayoutParams(lp);
lp.setMargins(10, -10, 15, 5);

CheckBox feature1=new CheckBox(this);
feature1 = new CheckBox(this);
feature1.setId(i);

final TextView fin = new TextView(this);
fin.setLayoutParams(lp);
fin.setText(FinancialYear1);

tr.addView(feature1);
tr.addView(fin);

ll.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

OncheckChangedListener:
feature1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
 public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (isChecked) {
        //......
    }
    else{

    //......
    }

Answer: if you want set first CB to true you must add follow cod:
boolean b = true;
feature1.setEnabled(b)

and with value of b do all you want to do,
and in continue if first you checked in OncheckChangedListener you must get id of CB and change the other CB with all you want to do
UPDATE /////
you have all id, so you must keep it in some list or array, and when the user hit one CB in for statement do every thing you want, i write semi code for you :
 for ( int i = 0 ; i < list.size ; i++)
 {
  if (!list.get(i).equal (id))
  {
    Checkbox ch = findViewByid(list.get(i);
    /// do what you want to other checkbox
  }
  else
     /// do what you want with checked CB
 }

sorry because i'm not near any IDE to test my code, sorry for code error, i hope this can help you
Comment: My first CB should be enabled at start, not checked.
Comment: what is your mean about enable?
Comment: When I check the first CB second should be enabled. default second third etc are disabled.

dynamic Check box android


What is the numeral system which uses the number of digits as a signifier of value called?

Question: Our standard notation of representing numbers has an implied infinite number of zero digits on the left of all numbers. 42, 042 and 00000000042 all represent the same number.
I'm thinking of the slightly different notation where the number of digits is significant. The sequence looks like this:
0,1,...,8,9,00,01,...,98,99,000,001,...,998,999,0000,...
The most famous (maybe) example of this system are the spreadsheet columns. These go:
A,B,...,Y,Z,AA,AB,...,ZY,ZZ,AAA,...
Does this style of notation have a name? I'd like to do some casual research on this idea and I need a word I can search for as a starting point.
Bonus question: Do you know of anything interesting I can read on this subject?
Answer: This order is sometimes called the shortlex order: length first, and lexicographic order for strings of the same length.


Convert Character to Factor R

Question: I have the following data:
> str(hiv_data)
'data.frame':   500 obs. of  8 variables:
 $ HIV.status     : chr  "HIV negative" "HIV negative" "HIV negative" "HIV negative" ...
 $ edu.years      : int  8 7 5 8 1 6 7 NA 4 5 ...
 $ wealth.quintile: int  5 4 5 5 2 4 2 NA 4 NA ...
 $ res.type       : chr  "Urban" "Urban" "Urban" "Urban" ...
 $ marital.status : chr  "Married" "Never married before" "Never married before" "Never married before" ...
 $ province       : chr  "WCP" "FSP" "FSP" "WCP" ...
 $ employment     : chr  "yes" "no" "no" "no" ...
 $ age            : int  27 32 26 18 44 24 18 NA 24 NA ...
>

I am performing forward selection to find a model with response HIV.status. I need to change the response to a factor with labels "Negative" and "Positive" coded as 0 and 1. I have tried doing the following:

hiv_data$HIV.status<-factor(hiv_data$HIV.status,levels=c(0,1),labels=c("HIV negative","HIV positive"))

But that results in the entire column consisting of NA values. Any help?
Comment: You are confusing levels and labels. They should be specified the other way around. However, for modelling there is no reason to have 0/1 as labels. you could just use `factor(hiv_data$HIV.status)`.
Comment: If the modelling functions works with factors as a response, there shouldn't be any issues. If it doesn't, you should convert the factor into an integer (and subtract 1).
Comment: If I use just factor(...) it converts it to the follows: ```HIV.status     : Factor w/ 2 levels "HIV negative",..: 1 NA 1 1 2 1 1 1 NA 1 ...``` For modelling is it fine if they are coded as 1 and 2?
Answer: hiv_status <- sample(c('HIV negative', 'HIV positive'), size = 10, replace = TRUE)
hiv_status
#>  [1] "HIV positive" "HIV negative" "HIV positive" "HIV negative" "HIV negative"
#>  [6] "HIV negative" "HIV negative" "HIV negative" "HIV negative" "HIV positive"

factor(hiv_status, labels = c('HIV positive', 'HIV negative'))
#>  [1] HIV negative HIV positive HIV negative HIV positive HIV positive
#>  [6] HIV positive HIV positive HIV positive HIV positive HIV negative
#> Levels: HIV positive HIV negative

hiv_status <- +(hiv_status == 'HIV positive')
hiv_status
#>  [1] 1 0 1 0 0 0 0 0 0 1

Created on 2021-05-11 by the reprex package (v2.0.0)
Comment: Thanks. This converts it to an integer though, I need it to a factor.
Comment: What about changing the last line to as.factor(hiv_status == 'HIV positive')

Convert Character to Factor R