Algebraic fraction equality with 3 unknowns

Question: I'm facing the following problem:
$$\frac{a}{(6x-1)} - \frac{1}{(3x+1)} = \frac{b}{(6x-1)(3x+1)}$$
$$\frac{a}{6x-1}-\frac{1}{3x+1}=\frac{3ax+a-6x+1}{\left(6x-1\right)\left(3x+1\right)}$$
where a and b are constants. Find the values of a and b.
I'm solid on the algebraic manipulation but can't get my head around how to get to a system with 2 unknowns. Pointing me in the right direction would be much appreciated.
Answer: HINT
If it's an identity in $x$, there must be an $a,b$ such that it is true for all $x$. So just try values of 2 values of $x$, solve for $a,b$ and plug back to check if it is indeed an identity
You should get $a = 2 , b = 3$
EDIT
In your solution, once you take the common denominator on the left side, you get a fraction, whose numerator must be a constant. That means the coffecient of $x$ in the numerator must be $0$, and the constant would be $b$ - that's how you proceed
Answer: The left hand sides are equal, and the denominator on the right is the same, hence the numerator on the right must be the same. That is
$$b=3ax+a-6x+1$$
$$b=(3a-6)x+(a+1)$$
Hence we must have $3a-6=0$, I will leave the rest to you.


JavaScript works in debug mode but not working normal mode

Question: <code>$(document).ready(function() {
    urlHolder.checkUser = '${checkUser}';
    $('#checkUserForm').submit(function() {
        checkUser();
    });
});

var urlHolder = new Object();
function checkUser() {
        $.post(urlHolder.checkUser, {
            email : $('#email').val(),
            password : $('#password').val(),
        }, function(response) {
            if (response != null) {
                alert('Success! User has been added.');
            } else {
                alert('Failure! An error has occurred!');
            }
        });
    };
</code>
I'm using this code for checking user exist or not. When I used firefox debugger (breakpoint on alert() line ), it worked and server came back a response, but if I didn't put any breakpoint, alert doesn't work, but server came back a response. Note: not only alert() but also window.location.href = "http://stackoverflow.com"; didn't work.
Comment: I am seeing third question within 10 min that is containing incorrect `java` tag in it.
Comment: @afzalex Yea, seriously, people need to start tagging better
Comment: [Java is to Javascript, as Ham is to Hamster](http://www.smashingmagazine.com/wp-content/uploads/images/xhtml2-html5/comic-960px.jpg). Let's see the markup for `checkUserForm`. I'll bet it has an `action` attribute that is submitting the form as you aren't calling `preventDefault` anywhere.
Comment: Actually, my application works on Java so I added java tag, I want to indicate, it's java on back-end but you are right, it is meaningless so I erased tag.
Answer: Change the following lines to prevent the form from being submitted:
<code>$('#checkUserForm').submit(function(event) {
  event.preventDefault();
  checkUser();
});
</code>


Poor rendering of non-standard fonts in Chrome on Windows

Question: I'm sure this has been discussed before, but I can't find any canonical question / answer.
Currently, IE9 and Firefox 4+ both use different font rendering that produces (for some) more blurry fonts but overall better kerning and more consistent results. Also, it renders non-standard fonts on Windows much better. I've have not done a thorough investigation, but I think it has to do with the fact that both IE9 and Firefox use now a different graphics layer which in apparently renders fonts differently. Also, the reason some of the standard fonts such as Arial, Tahoma etc. look in Firefox the same as 10 years ago is that it actually has a list of exceptions for them (look for gfx.font_rendering.cleartype_params.force_gdi_classic_for_families).
So far so good. The problem is Chrome. It still uses the old font rendering that makes the non-standard fonts practically unusable. Just for illustration, the font I had in mind was: http://www.google.com/webfonts/specimen/Play. Just open the sample in Firefox/IE9 and Chrome and you should see the difference. Is there anything I can do? Or should I look for a more optimized font.
Update: I see it's a common problem: the headings on http://www.smashingmagazine.com look very jaggy in Chrome.
Update: Sample image:
Comment: This is still a HUGE problem Chrome has
Comment: Same question here, with BIG answers and fixes: http://stackoverflow.com/q/11487427/1114320
Comment: I have written a big article about this, including fixes: [How to fix the ugly font rendering in Google Chrome](http://www.dev-metal.com/fix-ugly-font-rendering-google-chrome/).
Answer: I have read that Chrome (originally Chromium) has anti-aliasing issues that's why it's jaggy.
Using font-faces also makes a difference than using local fonts in your system. So, all we can do is just wait until they fix this issue or help the Chromium Project if you can.
Answer: Known issue. You can try gdipp or MacType.
Answer: Copying my anwswer from Making CSS3 @font-face font rendering play nice with ClearType on Windows

A similar question here: Font-face embedded fonts look fuzzy in Windows 7 browsers got an answer that solved the same issue for me.
The fontsquirrel font generator http://www.fontsquirrel.com/fontface/generator optimizes fonts and adds them with hinting/rendering info that helps the windows font rendering engine render them better. It also generates smaller files, which will download faster.


Boot-repair can't complete a repair under Ubuntu Gnome 14.04

Question: Yesterday I installed Ubuntu Gnome 14.04 on my computer. The installation program wouldn't recognize my Windows 8.1 installation, but it could see the NTFS-partitions.
I figured that I could make the necessary partitions for Ubuntu manually, and then later make both systems boot-able with boot-repair.
Now my computer boots into Ubuntu Gnome, and I followed this guide https://help.ubuntu.com/community/Boot-Repair to install boot-repair with the following commands
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo sed 's/trusty/saucy/g' -i /etc/apt/sources.list.d/yannubuntu-boot-repair-trusty.list
sudo apt-get update
sudo apt-get install -y boot-repair && (boot-repair &)

(Notice the trusty/saucy-line, this is because boot-repair ain't on launchpad for 14.04 yet)
It all went well until boot-repair asks me to insert the following command in a terminal
sudo apt-get install -y --force-yes grub-pc linux

After this the terminal says
E: Unable to locate package linux

Can anybody tell my why I get this error, and how I should proceed?
Answer: It's not
sudo apt-get install -y --force-yes grub-pc linux

It's
sudo apt-get install -y --force-yes grub-pc

There is no such package named linux.
Comment: Okay, this seems to be the solution. The strange thing is that the boot-repair script specifically ask for that command. It must be a bug in boot-repair.

Thanks for the quick answer!
Comment: who told you to run that command?
Comment: The boot-repair application itself. When I went through the different steps, it told my two times to run a command in the terminal, by showing a little window where I could copy the text from. The second time it showed my the exact command I posted here. sudo apt-get install -y --force-yes grub-pc linux
Answer: Yes... boot-repair does specifically request that one enter
sudo apt-get install -y --force-yes grub-pc linux

I agree that it does not work unless you remove the linux from the end of the line, so I assume that it's a typo. Hopefully, it still fixes the problem correctly.


Heroes of Newerth lagging periodically

Question: Everything was fine on Ubuntu 12.04. Today when I moved to Ubuntu 14.04 and installed HoN everything was fine, game loaded game started normally, in the game everything working fine just I have lags periodically(every 1-2 min). This lag is not long about couple of seconds.But when I have lags in team fights that make me lose a game! However I made contact with S2games(support for HoN) and they are not sure what make this lags.
So please help me.
I have laptop ASUS K50IN (all performances in game are on low) and I'm using Ubuntu 14.04 Unity.
Comment: What graphics do you have? You probably need a driver.
Comment: Nvidia geforce g102M and im using Nvidia driver 331.38
Comment: Are you sure you are using that driver? Sometimes upgrading removes them or you might need to use a different one now.
Comment: i tried all of them and all working fine just not for HoN...
Comment: Have you tried a different desktop environment other than unity? Just trying to rule possibilities out.
Comment: yes i did ... and its not working . i tried ubuntu ,mint,debian all environments and its the same... Only on slackware 14.1 is working fine.
Comment: I meant *[desktop environments](http://en.wikipedia.org/wiki/Desktop_environment)*, not Linux distributions.
Comment: like i said i did and i just mention that is not working in similar distros and theirs environments .
Comment: "all environments" includes which ones? Did you try LXDE and XFCE?
Comment: on ubuntu unity,kde,xfce,lxde on mint everything what u can download from official site same with debian... i really dont know what is not clean in my answer .
Answer: This is a problem that I have also been experiencing in DOTA 2. To solve it you need to upgrade your kernel manually. I upgraded to 3.14.4 personally.
Here is a guide on upgrading the kernel manually:
How to update kernel to the latest mainline version without any Distro-upgrade?
I hope it will work for you !

Heroes of Newerth lagging periodically


How to wrap each element in python list?

Question: For example i have array like this:
['1', '2', '3', '4']

And i need to wrap it like this:
{'profile': '1', 'profile': '2', 'profile': '3', 'profile': '4'}

Tried something like this but with no luck:
result = ['1', '2', '3', '4']
result = {'profile': v for v in result}

Comment: You can't have duplicate keys in dictionary
Comment: @Kirix to do *what*? What are you trying to achieve here? How will you *use* this structure once you've figured out how to build it?
Comment: @frostnational yeah, i this understood, but may be somehow possible to to this with other types?
Answer: The construct
{'profile': '1', 'profile': '2', 'profile': '3', 'profile': '4'}

is Python-equivalent to
{'profile': '4'}

since, as noted, dictionaries cannot contain duplicate keys.  Hence dictionaries are arguably not what your are looking for.
What you can do is to use list comprehension, as in
 >>> [('profile', x) for x in a]
 [('profile', '1'), ('profile', '2'), ('profile', '3'), ('profile', '4')]

Answer: Dictionaries are not the structure you are looking for as they don't accept duplicate keys.
When you do  result = {'profile': v for v in result} you are overwriting result['profile'] each iteration.
Answer: You can't make a dictionary with duplicate keys. But you can make a list of tuples. Using list comprehensions. See https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions
    [('profile', i) for i in ['1','2','3','4']]

Result
    [('profile', '1'), ('profile', '2'), ('profile', '3'), ('profile', '4')]

Answer: You can use map() to apply a function to each element of a list. However, as frostnational commented, you cannot have duplicate keys in a dictionary. If you want to have a dictionary for each element, you can do something like this (afterwards, you can pull each dictionary from the list):
>>> def wrap(x): return {"profile": x}
>>> map(wrap, range(1,10))
[{'profile': 1}, {'profile': 2}, {'profile': 3}, {'profile': 4}, {'profile': 5},
{'profile': 6}, {'profile': 7}, {'profile': 8}, {'profile': 9}]


Determining Local Time in another Timezone

Question: How can I determine the current date and time of various countries using a PERL script that executes on a server in the US? For example, getDTnow() should determine the current date and time on the server and use that to return the date and time of various countries.
P.S: It would be great if this can be done using only the built-in functions, without any external modules.

Conclusion: Date maths is [use swear word here] complicated and easy to get wrong. Other perl gurus on IRC, groups and other parts of the net confirmed what Ether had been advicing me - use DateTime. DVK's solution is also pretty neat for those of you who don't mind messing with the perl environment. (Note: Though on windows, the caveats section of the Time::Piece docs says one should be careful while 'Setting $ENV{TZ} in Threads on Win32').
Comment: Regarding "without any external modules" -- you need to read ["But I can't use CPAN!"](http://www.shadowcat.co.uk/blog/matt-s-trout/but-i-cant-use-cpan/)
Comment: time calculations are *not* simple, as there are lots of edge cases. If there is a module that has already taken care of the debugging and implementation of all the edge cases for you, you should use it, rather than attempting to reinvent the wheel.  You can always pop the hood to learn how it is doing it -- the code is readily available for inspection.
Comment: part of learning Perl is learning CPAN.
Comment: @Ether: Thanks for the link. It was an interesting read. I don't want to use any modules because I am learning perl. If a built-in function can do the simple task, why import a perl module that does a whole lot of other stuff that my script will never use? (Let's not forget TIMTOWTDI :).
Answer: DateTime is a wonderful library that can use standard timezones to do everything you desire and more:
use DateTime;

# returns local time in Italy
my $dt = DateTime->now(time_zone => 'Europe/Rome');

# prints time in desired format
print "The current date and time in Italy is: ", $dt->strftime('%Y-%m-%d %T');

Comment: Yes, I am looking for something like this but I'd like to avoid using any modules. Is there anyway to do something similar with gmtime()?
Comment: @Sam: read the link I provided above. Avoiding using any modules is a fool's errand.
Comment: I am not averse to using a module. But I want to know if this can be done using any of the built-in functions.
Answer: You can control which timezone localtime returns in via TZ environmental variable:
local $ENV{TZ} = ":/usr/share/lib/zoneinfo/Asia/Tokyo";
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = localtime();
print "$sec,$min,$hour,$mday,$mon,$year,$wday,$yday\n"'
# Prints 40,58,4,12,0,111,3,11

local $ENV{TZ} = ":/usr/share/lib/zoneinfo/Europe/London";
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = localtime();
print "$sec,$min,$hour,$mday,$mon,$year,$wday,$yday\n"'
# Prints 41,58,19,11,0,111,2,10

Unfortunately, the path above is different on different Unixes (/usr/share/lib/zoneinfo on Solaris, /usr/share/zoneinfo on Linux). Since there appear to be no other variations, a slightly portable version would check which of the 2 directories exists and use that - but this obviously only works on Solaris and Linux and may be other unixes. No idea about Windows/MacOS/whatnot.
Valid locations for TZ can be found here: http://www.timezoneconverter.com/cgi-bin/tzref.tzc (but not all of them would necessarily be available on your system - check the above directory).
Please see http://en.wikipedia.org/wiki/Tz_database for more info on TZ database.
Comment: Don't forget to adjust for daylight savings time!
Comment: @Sam: No, there isn't DST in UTC but there is DST in the local time. You'd also have to manually account for when DST is in effect and keep in mind that when DST takes effect (if at all!) depends on the location. Date wrangling is a horrific mess of special cases and foolish local conventions, the only things that rolling your own will do is produce bugs and teach you to never do it again.
Comment: Wouldn't gmtime() be more appropriate than localtime() - one wouldn't have to meddle with the environment variables ... I am stuck on how to 'pass' it a timezone to get the date / time of that zone.
Comment: @Sam - I may have misunderstood you, but I thought "current date and time of various countries" you requested was the local time (which localtime returns).
Comment: @Sam - "How to pass the timezone" part was the `ENV{TZ}` assignment.
Comment: @DVK: Yes, I want the local time. I was seeking a clarification from you - can we avoid having to set the timezone through ENV{TZ} by using gmtime()? For example, can we do something like this. @now = gmtime(); @china = @now + $chinaOffset; @germany = @now + $germanyOffset ... and so on? Is there some other way to pass the timezone offset to gmtime directly?
Comment: @Sam - you can probably parse the timzeone database by hand. But that's **exactly** what `localtime` does!!! So, yes, you can re-implement localtime by hand, but why bother?
Comment: @Ether - doesn't localtime internal logic adjust for that?
Comment: Perldocs on gmtime() says there is no DST in GMT. From what I have read so far, apparentlly GMT / UTC takes 'care' of that. If anybody could shed some more light on that ...
Comment: Thanks mu. I think I am beginning to get what you and others mean.
Answer: You could always store the variation from your timezone in a hash where the key is the timezone and the value is the adjustment from the current time.  then when you pass the current time it should return the local time for that zone.
Comment: The logic is clear to me too. But how do we implement this in perl?
Comment: @Sam - it's alreayd implemented in Unix. See my answer on how to tap into that.


$(3*5)*(5*9)$ modulo arithmetic $12$

Question: Modulo $12$ multiplication table and I got $3$, but I don't know if it's true or not.
I don't know whether it's correct place.
Please reopen it.
Comment: It is true that $(3 \cdot 5)(5 \cdot 9) \equiv 3 \pmod{12}$.  Did you pose your question to check your answer, or do you have a more general question?
Comment: Welcome to MSE! Firstly, you are asking a Maths related question at Maths' stackexchange. So, you are definitely in the right place. Secondly, although there will be many people who  will be able to explain it you from scratch, it helps to lay out the steps, so we can help you locate the error step and help specifically.
Answer: $(3\cdot5)(5\cdot9)=675$. Now, since we are taking modulo $12$, we will take $675-12k$, where $k$ is some positive integer, until we get a "least positive residue" (i.e. the smallest positive number where if we subtract $12$ one more time, then we would get a negative number).  So, plug in different values of $k$ and see what you get...
Comment: But we are asked about $(3 \cdot 5)(5 \cdot 9)$
Comment: oops, I fixed it :)
Answer: The straightforward solution: calculate $3\cdot 5\cdot 5\cdot 9=675$, divide $675$ by $12$ (e.g. long division), and you get the quotient $56$ and remainder $3$. So $3\cdot 5\cdot 5\cdot 9\equiv 3\pmod{12}$.
However, you may be expected to know that you are allowed to reduce (modulo any whole number) at each multiplication step. For example: $3\cdot 5=15\equiv 3\pmod{12}$. Also, $5\cdot 9=45\equiv 9\pmod{12}$. Therefore:
$$(3\cdot 5)\cdot(5\cdot 9)\equiv 3\cdot 9=27\equiv 3\pmod{12}$$
This technique is useful to avoid the numbers growing too much as you are calculating the remainders - in each step the result is reduced to something smaller than the modulus (in this case - smaller than $12$). You may be given a problem with a bigger expression and no calculator allowed - in which case you would be compelled to use this idea to shortcut the calculations.

$(3*5)*(5*9)$ modulo arithmetic $12$


Question for wine and playonlinux

Question: Today I downloaded the iso of microsoft office 2019 on the pc linux ubuntu 20.04 LTS and I did sudo apt install wine64 and I downloaded wine and then after I downloaded the playonthelinux application always from the terminal.
Ho fatto all the procedure but nothing I can not install office 2019 iso on linux ubuntu asks me for an error in code 0-1018 impossible to install office ?? why how do i properly uninstall the program on ubuntu ?.
Thanks and await answers.
Answer: According to WineHQ site, you can't really install MS Office 2019 using wine. The status is "Garbage".
https://appdb.winehq.org/objectManager.php?sClass=version&iId=37735
Answer: You can actually install it and it runs, but with some glitches.
First off, use Wine 5.11 to install it. It will not install with any other version, including newer ones (at least from my experience). Then follow the exact instructions from this page: https://appdb.winehq.org/objectManager.php?sClass=version&iId=37735
Once installed and confirmed to run, you can then install newer wine versions and it will still run, with some glitches.
Glitches/bugs include:

Not being able to log into Microsoft accounts (not a problem if it's just for offline use).
Visual glitches/slowness, such as UI sections turning black momentarily until they are fully created and then appear.
Some read-only document files that load fine in a Windows-installed version of office won't load into the wine-installed version. You can load them into Softmaker Office/FreeOffice, WPS or LibreOffice and then re-save them as a writable file, and they will load just fine.
Some UI elements that should be anti-aliased aren't.
It does not exit cleanly, leaving a bunch of zombie exe processes running. You have to end/kill them manually after you're done using Office.
Answer: I tried to follow both the setup of @MikeF (Wine) and the version discussed here for PlayOnLinux (which of course uses Wine as well). I also 'merged' these two versions by using a PlayOnLinux with Wine 5.11 specified. But to no avail.
At first everything goes fine, although there is some weird symbol before and after text.

The main issue is that the installer turns black the moment that the installation starts. Then it gets stuck at 59% (they might or might not be related issues).
I've tried to play around with various graphics options and libraries, but that didn't help. In all cases I was left with the following log (although small issues existed because me trying with intel and nvidia graphics and with and without msxml6/riched20).
Comment: I've tried 4.01, 4.0-RC1 installation got stuck at 57%. 5.11 stuck at 59%. 5.15 throws error 30088-45 at 59% or 65%, 6.01 installation throws an error at 100% If i install components dx9, dx10, dx11, urlmon, msxml6, riched20 in a 5.15 wine it goes up to 97% (error 30015-11)

Question for wine and playonlinux


How many elements are in $V((x^3-1,p))\subset\mathrm{Spec}(\mathbb{Z}[x])$?

Question: I am trying to solve the following problem:

Consider $\mathrm{Spec}(\mathbb{Z}[x])$. List the first four primes $p$ such that
  $$|V((x^3-1))\cap V((p))|=3.$$

However, I doubt there exist such prime numbers. It is well-known that the prime ideal in $\mathbb{Z}[x]$ is one of the followings

$(0)$.
$(f(x))$, where $f(x)$ is an irreducible polynomial.
$(p)$, where $p$ is a prime number.
$(p, f(x))$, where $p$ is a prime number and $f(x)$ is an irreducible polynomial in $\mathbb{Z}_p[x]$.

So $V((x^3-1))\cap V((p))=V((x^3-1,p))$ should only have two elements: the
 prime ideals
$$(x-1,p)\quad \quad (x^2+x+1,p)$$
Where is the third prime ideal? I am really confused.
Comment: If $p\equiv1\pmod 3$ then, by cyclicity of $\Bbb{F}_p^*$, there are three pairwise non-congruent solutions of $a^3\equiv1\pmod p$. In those cases $(x-a,p)$ is a prime ideal containing $x^3-1$ giving three distinct prime ideals in $V((x^3-1,p))$. Also $(x^3-1)\equiv (x-1)^3\pmod 3$, so in that case $x^2+x+1\equiv (x-1)^2$.
Comment: @JyrkiLahtonen Thanks a lot!
Answer: The third element is $(p)$.
On the other hand, $V\bigl((x^3-1,p)\bigr)$ has $3$ elements if $x^2+x+1$ is irreducible in $\mathbf Z/p\mathbf Z$, i.e. if and only if its discriminant $-3$ is not a square mod. $p$.
Now, if $p=2$, $x^2+x+1$ is irreducible, so $2$ is the  first prime in the list.
Suppose $p$ is odd. By the law of quadratic reciprocity, we have
$$\biggl(\frac{-3}p\biggr)=\biggl(\frac{-1}p\biggr)\biggl(\frac{3}p\biggr)=\bigl(-1\bigr)^{\tfrac{p-1}2}\cdot\biggl(\frac p{3}\biggr)\bigl(-1\bigr)^{\tfrac{p-1}2}=\biggl(\frac p{3}\biggr),$$
which shows $x^2+x+1$ is irreducible mod. $p$ if and only if $p$ is not a square mod. $3$, i.e. if $$p\equiv 2\mod 3.$$
Comment: But why $x^3-1\in (2)$?
Answer: Only prime ideal of type 4 in your list can contain the ideal $(x^3-1,p)$.
So in order to to find three such prime ideals you must find three distinct irreducible factors of $x^3-1$ modulo $p$. In that case the said factors are necessarily linear, so $|V((p,x^3-1))|=3$ is equivalent to $x^3-1$ having three pairwise non-congruent zeros modulo $p$.
Claim. This happens if and only if $p\equiv1\pmod3$.
If $a\in \Bbb{F}_p^*$ is a solution of $a^3=1$, then either $a=1$ (one solutions), or $a$ has order three. By Lagrange's theorem in the latter case we must have $3\mid p-1$. On the other hand, if $3\mid p-1$ then, by cyclicity of $\Bbb{F}_p^*$ there exists and element $a$ of order three. In that case $1,a,a^2$ are all solutions of $x^3\equiv1$. As $a\neq1$ they are pairwise distinct.

For example when $p=7$ we see that $1,2,4$ are all solutions of $x^3\equiv1\pmod7$. These yield the three prime ideals $(x-1,7)$, $(x-2,7)$ and $(x-4,7)$ all containing the polynomial $x^3-1$.


Rsync behavior in a cron script

Question: I have an nfs device that creates checkpoint (backups) everyday. I want to use Rsync to copy these checkpoints to another device (Drobo connected via iSCSI). So I've run the script on a single nfs share and it works nicely. Here are a couple concerns I have that will take too long to experiment with multiple times.

There are multiple shares to back up, and I would like to loop through them and run the script over each one. How will this work with Rsync? Will the Rsync job start and then loop again and run a second and third and fourth Rsync job simultaneously, or will Rsync wait for the job to finish before ending and restarting the loop? Maybe I just need to put some check in the loop to not restart until Rsync is done.
Referring to that last sentence; what does Rsync return that I could use to report if there was an error or continue the loop if all went well?
The checkpoints created by the NFS device are named based on the date. Rsync is unpacking the .ckpt* file into a statically named directory. Since the source is a different directory but the files inside are the same, and the target is named the same, will Rsync still only copy the differences?

this is the rsync job:
    rsync -az $NEWCHKPT/* /drobo/bak.${share}/${share}_daily
I know this is post is asking alot. Any advice is greatly appreciated.
Answer:
Depends on how you write the loop; unless you background the rsync commands with the & symbol, the rsync commands will run in sequence.
rsync will return a useful exit status. These are listed in rsync's manual page. man rsync | less '+/^EXIT VALUE'. You have to decide whether you want to abort the whole script when one fails, or attempt to run the others, then provide an error summary at the end for the ones that failed.
rsync has various ways to decide whether to copy a file or not. The default is to check the size and last modification time of the source and destination files. If both match, it skips copying that file. That's usually good enough.
Comment: Thanks, that is some helpful information. I know Rsync has some helpful return values. I guess what I should have asked is; How can I get a hold of those values in my script? Like what variable do I need to check after the rsync job?
Comment: @dan08 If you only care whether it succeeded or not, you use `if rsync ...; then echo "rsync succeeded"; else echo "rsync failed"; fi`. If you want to distinguish between the different types of failures, you want to copy the `?` parameter right after the rsync command. `rsync ...; status=$?; if (( status == 11 )); then echo "bla bla"; elif (( status == 12 )); then echo "other bla"; fi`
Comment: Yes, the latter is exactly what I want. Thanks.
Comment: If geirha's answer solved your problem, don't for get to "accept" the answer. +25 points to geirha, +2 to you.

Rsync behavior in a cron script


How to know the login and password details, my name and computers name after i'm done installing ubuntu?

Question: During the setup I'm asked to type in my name and the computers name.
After the OS is installed, how can I know those?
Comment: Your question is unclear a bit. However, you can go to recovery mode and command shell and from there run following commands: "hostname" - output computer's name, "lastlog" - output all users on computer, the last one probably is the user you created when os was installing.
Answer: Username

Your username is usually your first name when you enter your first name and surname into the designated box during the installation process. The username is always in small caps, but at the graphical login screen your full name is shown in the default installation and you just need to remember your password. Alternatively you could also boot live media, mount the file system and look in the directory home of your installation to see which accounts exist. Digging deeper you can find all user and system accounts in /etc/passwd.
User password
You have to remember the password before you continue, or you would normally not be able to login. But you can reset your password.
Computername

You don't need to remember your computer name or hostname, as this is shown to you at graphical and terminal login. Unless you don't customize this, the device name of your computer or motherboard is picked and probably stripped of some numbers to look nicer and your username is added. So your computer could be named Thinkpad-$Yourname, ProBook-$Yourname, Zenbook-$Yourname if that's what you have. The hostname is defined in /etc/hostname.


Do hoes mine trees faster than swords do?

Question: Lets say you have a sword and a hoe, can't use your hands and are intending to mine a tree. There is a ton of trees and you can only use one weapon to mine all of them. Which of these would mine the most in the smallest amount of time, a diamond hoe or a diamond sword?
Comment: Why can't you use your hands?
Answer: They both mine at the same speed. It would still be better to use the hoe, because it is used way less than the sword, so you can afford it losing durability or breaking.
Comment: There is also an achievement for breaking a diamond hoe if you manage to break it, but since it has lots of durability you probably won't be able to.
Answer: In 1.16 snapshots, Hoes mine trees much faster than swords and still have a chance to drop saplings, apples, and sticks.


iconv equvalent of mb_string functions

Question: I have the next sequence of code:
// characters U-00000080 - U-000007FF, mask 110XXXXX
$char= pack('C*', $ord_v, ord($string{$c + 1}));
$c += 1;
$utf16= mb_convert_encoding($char, 'UTF-16', 'UTF-8');
$ret .= sprintf('\u%04s', bin2hex($utf16));

The code is part of json encode function from json.org.
  What is the equivalent iconv conversion to achive the same thing?
  I tried iconv('UTF-8', 'UTF-16', $char); but iconv inserts a LE flag byte (I guess), and I don't know how to deal with it.
Regards,
Alex
Answer: iconv('UTF-8', 'UTF-16', '$char') converts the string "$char". To convert the content of the variable $char omit the apostrophes. iconv('UTF-8', 'UTF-16', $char)
Comment: sorry for the miss-typed question. in the original code I omitted the quotes.

iconv equvalent of mb_string functions


How do I get gamepad input in Java? (Windows 10)

Question: I'm creating a pretty basic game in my free time, and before I really get into it I want to learn how to include controller support. I've tried plenty of tutorials and different libraries, but they all in some way seem to require JInput (and LWJGL, they seem to related in some way?). This wouldn't be an issue, and generally speaking I've figured out how to work with JInput. However, I can't find a single version of JInput that is compatible with windows 10. Even if I were to find one, I have no way of knowing that the test code I wrote would even work with the newer versions of the library, so I have no way of testing or even knowing if they work with windows 10.
I would prefer to use JInput as it seems standard, but if you know of any way to add controller support in Java, then I will jump at the chance to try it out.
Here's my code and error - maybe I'm just doing something wrong.
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Controller;
import org.lwjgl.input.Controllers;

    public class GamePadTut {

        static Controller cont;

        public static void main(String[] args) {
            try {
                Controllers.create();
            } catch (LWJGLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            Controllers.poll();

            for(int i =0; i < Controllers.getControllerCount(); i++) {
                cont = Controllers.getController(i);
                System.out.println(cont.getName());
            }
        }
    }

and the errors
WARNING: Found unknown Windows version: Windows 10
Attempting to use default windows plug-in.
Loading: net.java.games.input.DirectAndRawInputEnvironmentPlugin
java.lang.UnsatisfiedLinkError: no jinput-dx8_64 in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at net.java.games.input.DirectInputEnvironmentPlugin$1.run(DirectInputEnvironmentPlugin.java:75)
    at java.security.AccessController.doPrivileged(Native Method)
    at net.java.games.input.DirectInputEnvironmentPlugin.loadLibrary(DirectInputEnvironmentPlugin.java:67)
    at net.java.games.input.DirectInputEnvironmentPlugin.<clinit>(DirectInputEnvironmentPlugin.java:109)
    at net.java.games.input.DirectAndRawInputEnvironmentPlugin.<init>(DirectAndRawInputEnvironmentPlugin.java:45)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at net.java.games.input.DefaultControllerEnvironment.getControllers(DefaultControllerEnvironment.java:157)
    at org.lwjgl.input.Controllers.create(Controllers.java:71)
    at GamePadTut.main(GamePadTut.java:11)
java.lang.UnsatisfiedLinkError: no jinput-raw_64 in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at net.java.games.input.RawInputEnvironmentPlugin$1.run(RawInputEnvironmentPlugin.java:75)
    at java.security.AccessController.doPrivileged(Native Method)
    at net.java.games.input.RawInputEnvironmentPlugin.loadLibrary(RawInputEnvironmentPlugin.java:67)
    at net.java.games.input.RawInputEnvironmentPlugin.<clinit>(RawInputEnvironmentPlugin.java:109)
    at net.java.games.input.DirectAndRawInputEnvironmentPlugin.<init>(DirectAndRawInputEnvironmentPlugin.java:46)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at net.java.games.input.DefaultControllerEnvironment.getControllers(DefaultControllerEnvironment.java:157)
    at org.lwjgl.input.Controllers.create(Controllers.java:71)
    at GamePadTut.main(GamePadTut.java:11)

Answer: I believe you are missing the .dll in your native library path. the jinput-dx8_64 is a .dll file if I'm not mistaken.
http://wiki.lwjgl.org/wiki/Setting_Up_LWJGL_with_Eclipse.html
^ that should help you get that set up, if you're using eclipse. If you're using another IDE I don't really know haha.


Random generate image from json and display in div container

Question: I want to fetch these 12 images (or more) from a JSON file randomly and display them inside 6 divs on each refresh. I am able to get this solution through the below method. But I need solution to get same output by reading from a JSON file.
Thanks for your valuable comments.
JS:
$('.ir_image_holder .ir_img_src').each(function() {
  var num = Math.floor(Math.random() * 20 + 1),
    img = $(this);
  img.attr('src', '/img/instant_rewards/prize' + num + '.jpg');
  img.attr('data-block', num);
});

HTML:

JSON:
{
 "imageList": [
  {
    "image_1": "/img/prize1.jpg",
    "image_2": "/img/prize2.jpg",
    "image_3": "/img/prize3.jpg",
    "image_4": "/img/prize4.jpg",
    "image_5": "/img/default.jpg",
    "image_6": "/img/default.jpg",
    "image_7": "/img/default.jpg",
    "image_8": "/img/default.jpg",
    "image_9": "/img/default.jpg",
    "image_10": "/img/default.jpg",
    "image_11": "/img/default.jpg",
   }
 ]
}

Answer: You'd have to parse your JSON into an array. There are a few ways to do this, the easiest way would probably be using ES2105 Object.values(). Like so:
var array = Object.values(json);

Read more about Object.values() on the MDN:

The Object.values() method returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop (the difference being that a for-in loop enumerates properties in the prototype chain as well).

And here's your working demo:

var json = {
 "imageList": [
  {
    "image_1": "/animals/1",
    "image_2": "/animals/2",
    "image_3": "/animals/3",
    "image_4": "/animals/4",
    "image_5": "/animals/5",
    "image_6": "/cats/1",
    "image_7": "/cats/2",
    "image_8": "/cats/3",
    "image_9": "/cats/4",
    "image_10": "/cats/5",
    "image_11": "/cats/6",
   }
 ]
};

var arr = Object.values(json.imageList[0]);

$('.ir_image_holder .ir_img_src').each(function() {
  var num = Math.floor(Math.random() * 11 + 1),
    img = $(this);
  img.attr('src', 'http://lorempixel.com/100/100' + arr[num] + '');
  img.attr('data-block', num);
});

Comment: Thanks Chris.. So, i can use $.get('/data/imagelist.json') method to get Json array outside the file which this method rite?


Dynamic source data for powerpoint chart

Question:
The data on the chart on the powerpoint slide is dependent on the data encased by the blue lines. The data is on a worksheet that pops out when i click edit data after right clicking on the chart.
I am trying to write a vba code to set the source of the data to include all of the data but to no avail as of now. My code is as follows:
Melon.Chart.SetSourceData _
Source:=Melon.Chart.ChartData.Workbook.Sheets(1).Range("B3:C" & (28 + Weekno))

Melon is the name of the chart on the powerpoint slide. Weekno actually stands for the week number of the 2017 which is a variable depending on the current week. The above code keeps returning a Run-time error '13': Type mismatch error and does not set the source data to the intended range.
Anyone has any idea? All help will be appreciated! Thank you!
Comment: How is `Weekno` defined? Is it a numeric type like `Integer` or `Long`? What value does it have when you run the code? Could you post the rest of the code?
Comment: Try this instead: Melon.Chart.SetSourceData _
Source:=Melon.Chart.ChartData.Workbook.Sheets(1).Range("B3:C" & Cstr(28 + Weekno)))
Comment: @RyanWildry `Weekno` is an `Integer`. I have attached my codes for your reference. Thank you.
Comment: @SteveRindsberg Thank you Steve. I have implemented your recommendation and I attached a screenshot of the result.
Comment: 'With Melon.Chart.ChartData
    .Activate
   .Workbook.Sheets(1).ListObjects("Table1").Resize Range("$A$1:$C$29")

End With'
Answer: With Melon.Chart.ChartData
    .Activate
   .Workbook.Sheets(1).ListObjects("Table1").Resize Range("$A$1:$C$29")

End With

This Works!!!! Im so happy


Integration of quotient of hypergeometric functions

Question: If one has an expression of the form,
$$\int \frac{\, _2F_1(a,b;c;z)}{_2F_1(d,e;f;z)}dz,$$
where the arguments are all complex numbers, is it possible to integrate this to get another hypergeometric function, or some other analytic expression?
If one expands the hypergeometric functions into their series representation, it seems straightforward that this expression can be integrated, however possibly the resulting series is no longer convergent. When I tried to evaluate this integral with Mathematica, it won't give me an output, so does this mean that the new series is non-convergent? Or is there some other way I can analyse the series?
In particular, the integral is,
$$\int \frac{\, _2F_1((3 + \alpha),  (3 - \sqrt{\beta} + \alpha); 3 +
 \alpha; z)}{_2F_1( (1 + \alpha),  (1 - \sqrt{\beta} + \alpha ); 1 +
 \alpha; z)}dz,$$
where $\alpha$ and $\beta$ are constants.
Thanks!
Answer: The ratio of two analytic functions is analytic on any domain where the denominator is not $0$. Also the integral of a power series has the same radius of congergence as the original power series (as can be easily verified by the ratio test).
So yes, this integral exists on any simply-connected domain that does not include a zero of the denominator, and the integral will also be analytic over that domain. However, it is not likely to be another hypergeometric function.
Answer: The integration of the quotient of hypergeometric functions can be calculated or verified with the help of a CAS such as Mathematica.
The Gaussian hypergeometric function is defined by:
$\displaystyle \, _2F_1(a,b;c;z)=\sum _{k=0}^{\infty } \frac{z^k (a)_k (b)_k}{k! (c)_k},$
where the Pochhammer symbol is defined by
$\displaystyle x_{(n)}=x(x+1)(x+2)\cdots (x+n-1)=\prod _{k=1}^{n}(x+k-1)=\prod _{k=0}^{n-1}(x+k)$
${\displaystyle x_{(n)}={\frac {\Gamma (x+n)}{\Gamma (x)}}}$
The quotient of the two hypergeometric functions in this question is (verified with Mathematica):
$\displaystyle \frac{\, _2F_1\left(\alpha +3,\alpha -\sqrt{\beta }+3;\alpha +3;z\right)}{\, _2F_1\left(\alpha +1,\alpha -\sqrt{\beta }+1;\alpha +1;z\right)}=\frac{1}{(1-z)^2}$
Hence the integral is given by
$ \displaystyle \int \frac{\, _2F_1\left(\alpha +3,\alpha -\sqrt{\beta }+3;\alpha +3;z\right)}{\, _2F_1\left(\alpha +1,\alpha -\sqrt{\beta }+1;\alpha +1;z\right)} \, dz=\int \frac{1}{(1-z)^2} \, dz=\frac{1}{1-z}+C$
For arbitrary numbers $p$ and $q,$ the integral of the quotient of hypergeometric functions is:
$\displaystyle \int \frac{\, _2F_1\left(p+\alpha ,p+\alpha -\sqrt{\beta };p+\alpha ;z\right)}{\, _2F_1\left(q+\alpha ,q+\alpha -\sqrt{\beta };q+\alpha ;z\right)} \, dz=\int (1-z)^{q-p} \, dz=\frac{(1-z)^{-p+q+1}}{p-q-1}+C$


How can i use my RAM memory fully?

Question: Hello there i have 4 gigabyte of ram installed in my system but only 1.5 gigabyte is used and other ram sapace is in the form of swap space. But i want to use those also. Is it possible?
<code>             total        used        free      shared  buff/cache  available
Mem:           3847        1547         104         231        2194        1810
Swap:          2047         156        1891
</code>
I am new to UBANTU so i have this doubt.Please help
Comment: You do not have RAM as swap. all your RAM, - some reserved by BIOS and kernel, is available for your use. As of your snapshot, you are only using 1.547 Gigs.
Comment: How can i use it fully can you explain please...
Comment: It will be used automatically and as required. If, for some reason you want to forcibly use it all, then see [here](https://askubuntu.com/questions/1188024/how-to-test-oom-killer-from-command-line).
Answer: Your memory is being fully utilized.
If you look at:
<code>             total        used        free      shared  buff/cache  available
Mem:           3847        1547         104         231        2194        1810
</code>
note the columns shared and buff/cache... this is currently unused memory that is used for file and disk buffers/cache.
This line:
<code>Swap:          2047         156        1891
</code>
indicates that swap is also being used. Swap is used by the system to store recently unused active memory pages. Swap is not RAM space.
Answer: Note that there is a difference between RAM and swap. Swap Space is Linux is nothing but a Virtual Memory composed of  Hard Disk space used as Main Memory. In case, if RAM is not sufficient to handle the processes, this swap memory will be used.
Modern computers, nowadays, may not need Swap space at all, as we got to get at least 4GB RAM which is enough to handle most of the tasks. But Earlier days (15 years ago), the RAM would be usually a maximum of 1GB, so Swap space play a role in computing.
Memory will be used depending on the type of application. If you use text editor such as gedit, it will use less RAM. But instead of it you use chrome, it will use a lot of memory.
Comment: re: "Swap Space is Linux is nothing but a Virtual Memory composed of Hard Disk space used as Main Memory."... not **exactly** correct... it's **not** used as "Main Memory"... it's used to store **recently unused active memory pages**.
Comment: I have tried to explain him in very simple terms without going into technicals
Comment: Well, you might as well explain accurately.
Comment: postnote: **all** computers need swap, irrespective of how much RAM is installed.

How can i use my RAM memory fully?


Acces list element in flutter? Geocoding

Question: I am trying to get the latittude from the list :

[      Latitude: 28.6139391,
Longitude: 77.2090212,
Timestamp: 2022-06-12 11:34:06.992Z ]

which is generated by this code below:
  Future fetchAlbum() async{
List locations= await locationFromAddress("New Delhi, India");
print(`locations`);
 }

i want to get lattitiude so i am trying :
print(locations[0])

but it getting me same output but without square brackets :

Latitude: 28.6139391,
Longitude: 77.2090212,
Timestamp: 2022-06-12 11:34:06.992Z
Answer: Looking at documentation: https://pub.dev/documentation/geocoding/latest/geocoding/locationFromAddress.html
It seems like the method returns List<Location> which you can access it easily.
Please change your code to:
Future fetchAlbum() async {
  final locations = await locationFromAddress("New Delhi, India");
  print(`locations`);
  if (locations.isNotEmpty) {
     final location = locations.first; // or locations[0]
     print(location.latitude)
     print(location.longitude)
  }
}


ToString() method not supported

Question: I am trying to create a selectlist in c#. My code :
       var ceremonies = db.Ceremonies;
        var Ceremonies =
            from c in ceremonies
            select new SelectListItem
            {
                Text = c.Name + "_" + c.Date,
                Value = c.Id.ToString()
            };

But here i am getting exception something like ToString() method not supported. Whats the problem ?
Answer: Your query is being transformed into SQL - but the call to ToString can't be handled properly. Generally the simplest way of fixing this is to effectively split the query into the part that needs to be done in the database, then switch to LINQ to Objects via AsEnumerable:
var ceremonies = db.Ceremonies
                   .Select(c => new { c.Name, c.Date, c.Id }
                   .AsEnumerable()
                   .Select(c => new SelectListItem {
                               Text = c.Name + "_" + c.Date,
                               Value = c.Id.ToString()
                           });

As an aside, declaring two local variables which vary only by case gives pretty nasty readability.

ToString() method not supported


CakePHP 2.x: How to manually set validationErrors without a model?

Question: After reading cakePHP: how set error validation to input field manually in controller, I was wondering how to show a validationError from a controller if we use a form without a model?
So for example, we have a view checkSomething.ctp, with a Form that we can submit.
echo $this->Form->create(false); // If we put "SomeModel" here, it would work.
echo $this->Form->input("myField");

And say we are on /Home/CheckSomething/.
class HomeController extends AppController{
    public function CheckSomething(){

        // So manually validate a field
        if(strlen($this->request->data["myField"]) < 5){

            // myField is not valid, so we need to show an error near that field
            $this->SomeModel->invalidateField("myField", "You must enter at least 5 characters");

            // How to do this?

        }
    }
}

We cannot use a model here... How to set a validationError for a field without a model? How to manually invalidate a field that comes from such a form?
Answer: The easiest way would be to send the error to the view directly:
$errors = [];
if (strlen($this->request->data["myField"]) < 5) {
    $errors['myField'] = 'You must enter at least 5 characters';
}
$this->set('errors', $errors);

And in your view:
echo $this->Form->create(false);
echo $this->Form->input('myField', [
    'error' => isset($errors['myField']) ? $errors['myField'] : false
]);

Comment: That is exactly the way to solve this problem. Thanks!


Cannot launch activity which extends MapActivity

Question: An activity (ShowPos) cannot be launched when it extends MapActivity. If I change to extends Activity, it launches.
It did work earlier, before I copy/pasted the java codes of the project to a new project in a new workspace when suddenly Eclipse inexplicably could no longer find any Android API, and none could be re-imported. Similar things have happened a few times before, it seems ordinary with Eclipse. But copy/paste has always worked before, for a while at least. And now it warns of no such error.
I do have an API-key, which has worked before.
maps.jar is now under Google API 2.2 under the project in the project explorer.
The editor notes no errors in any file in the project.
When launched, LogCat starts with:

 - D dalvikm Calling exit(1)
 - W dalvikm Unable to resolve superclass of Lintrax/three/ShowPos; (35)
 - W dalvikm Link of class 'Lintrax/three/ShowPos;' failed
 - D AndroidRuntime Shutting down VM
 - W dalvikm threadid=1: thread exiting with uncaught exception
   (groupnr)
 - E AndroidRuntime FATAL EXCEPTION: main

My project name is now "intrax.three". Why does it add an "L" to that?
The Manifest does contain:

    uses-library android:name="com.google.android.maps"
    uses-permission android:name="android.permission.INTERNET"

(Couldn't paste the Manifest file here)
Thanks for any help about how I can help Eclipse find stuff!
Comment: You should at least post your code or logcat if you need some help.
Comment: I've gotten a new MD5 key with the keytool, and a new API-key from Google. But it was the same as last time. Shouldn't it be a unique one for each project?
Answer: Go to Project -> Preferences -> Android -> Project Build Target and make sure that you created a project that uses the Google APIs
Comment: Thank you for reminding me, but yes, for sure I have already done that! I've done this several times now. It usually helps for a while. Last time Eclipse stopped finding any API after I tried to switch from 2.2 to 2.3.3 (with Google API). Now I've copied everything to a new Google API 2.2 project, with which it worked last time. But now it doesn't even launch, despite no errors indicated.
Answer: If you have already defined the Internet permission and uses-library
<uses-library android:name="com.google.android.maps" /> in your manifest.

Also make sure that the project target is set to google APi.
Third and imp thing is your package level need to be corrected and build the project again without any map.jar library provided explicitly. Only use google APi inbuilt maps.jar and creat new activity that extends the MapActivity (Also do declare in manifest).
Comment:  should be inside
Comment: Continued: That's my mistake.  should be outside  in the Manifest. I confused the two and didn't see my error no matter how hard I stared. It all works now! Thanks all!
Comment: I must emphasize that it is the *PLACEMENT* of the tags in the manifest which is the big problem for beginners like me. I've seen similar problems with similar answers without anyone understanding anything. So next time, emphasize WHERE the tag is in the manifest.
Answer: I've followed the MapView tutorial and it works just fine without any errors.
The error in question is a link error where the Dalvik VM is not able to find your class. This means all the suggestions given here (uses-library, internet permission, setting Google APIs as the Build Target) don't even come into the picture yet. Link error means that Android OS is not able to find your class. So, I suggest you try creating a clean project where you create the new Class from Eclipse and then paste the code snippet instead of pasting files.
BTW, the L is used to identify an Object. Reference: Java Identifiers.
Happy Coding!
Comment: Actually, I have already pasted code instead of files into clean new projects. But the problem was that I misplaced the  tag in the Manifest. See below. Thank you!


TypeError: coercing to Unicode: need string or buffer

Question: This code returns the following error message:

with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f:
TypeError: coercing to Unicode: need string or buffer, file found
# Opens each file to read/modify
infile=open('110331_HS1A_1_rtTA.result','r')
outfile=open('2.txt','w')

import re

with open (infile, mode='r', buffering=-1) as in_f, open (outfile, mode='w', buffering=-1) as out_f:
    f = (i for i in in_f if i.rstrip())
    for line in f:
        _, k = line.split('\t',1)
        x = re.findall(r'^1..100\t([+-])chr(\d+):(\d+)\.\.(\d+).+$',k)
        if not x:
            continue
        out_f.write(' '.join(x[0]) + '\n')

Please someone help me.
Answer: You're trying to open each file twice! First you do:
infile=open('110331_HS1A_1_rtTA.result','r')

and then you pass infile (which is a file object) to the open function again:
with open (infile, mode='r', buffering=-1)

open is of course expecting its first argument to be a file name, not an opened file!
Open the file once only and you should be fine.
Comment: Can you please look at my post and see what I'm doing wrong? https://stackoverflow.com/questions/62286907/typeerror-coercing-to-unicode-need-string-or-buffer-nonetype-found-seems-to
Answer: For the less specific case (not just the code in the question - since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.
For example:
os.path.exists(arg)
os.stat(arg)

Will raise this exception when arg is None.
Comment: Thanks for this.  That python error code is really misleading.
Answer: You're trying to pass file objects as filenames. Try using
infile = '110331_HS1A_1_rtTA.result'
outfile = '2.txt'

at the top of your code.
(Not only does the doubled usage of open() cause that problem with trying to open the file again, it also means that infile and outfile are never closed during the course of execution, though they'll probably get closed once the program ends.)
Answer: Here is the best way I found for Python 2:
def inplace_change(file,old,new):
        fin = open(file, "rt")
        data = fin.read()
        data = data.replace(old, new)
        fin.close()

        fin = open(file, "wt")
        fin.write(data)
        fin.close()

An example:
inplace_change('/var/www/html/info.txt','youtub','youtube')


Setting Value to ngtypeahead in Model Driven Form(Reactive)

Question: I am using Angular Reactive form and having typeahead field via ng-bootstrap typeahead. I am having a list of states created using interface as below -
export interface IContactStates {
   Id: number;
   Name: string;
}

List of states is populated via service and typeahead is initialized in component.ts as -
search = (text$: Observable<string>) =>
  text$
    .debounceTime(200)
    .distinctUntilChanged()
    .map(term => term === '' ? []
      : this.statesList.filter(v =>
v.Name.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))

formatter = (x: {Name: string}) => x.Name;

and ngbTypahead is defined as below in html template -
<ng-template #rt let-r="result" let-t="term">
        {{ r.Name}}
      </ng-template>

            State
            <input class="form-control form-control-sm" formControlName="State"
            type="text" [ngbTypeahead]="search"
            [resultTemplate]="rt"
            [resultFormatter]="formatter"
            [inputFormatter]="formatter"
            [editable]="false"
            placeholder="State (start typing the name and then select from list)"
            (selectItem)="selectItem($event)">

                {{displayMessage.State}}

This works fine when I am creating new form but when I am trying to edit any already submitted form, State control value is setting undefined. I tried to get any hint on setting the typeahead value from ng-bootstrap help documents but no luck.
Answer: Ok. I make it to work. Just reinitialize the form control element again.
Update 1
After getting value from server for selected item, search and assign the object to my formcontrol.
const state = this.statesList.find(function(item){
        return item.Id === trader.State;

Then, patch the Typeahead control with this variable.
Comment: Would you please be so kind and update your answer how exactly you accomplished that?


Manually Release Googlemap Markers From MarkerCluster

Question: I have too much markers on google maps about 15000.
so, I have Used MarkerClusterer For that.
Please do not down Vote.
Here is my Clustered Markers : http://jsfiddle.net/u758rqpa/45/
Here in my array first two markers have same latitude and longitude but they have different rotation angel.
when i click on these two markers cluster, that map is zoomed fully but not display those two markers.
And when click on other two markers cluster it display different.
I am not getting ,How can i display markers on MarkersCluster click.
so, is there any way to release markers from Markerclusters when i click on that ?
marker = new google.maps.Marker({
              position: new google.maps.LatLng(markerA[i][2], markerA[i][2]),
              map: map,
              icon: {
                  path: 'm 32.460621,0.112468 -32.372233,-0.022 0,-0.088 L 0,0.090468 l 22.91468,22.9147 c 0.02205,-0.022 0.04437,-0.044 0.06629,-0.066 6.300656,-6.3007 9.451842,-14.5699 9.47965,-22.8263 z',

                  fillColor: color[i],
                  fillOpacity: 1,
                  strokeColor: '',
                  strokeWeight: 0,
                  rotation: 250 + markerA[i][3],
                  anchor: new google.maps.Point(0, 0)
              }
          });
     clustermarkers.push(marker);
}
markerClusterer = new MarkerClusterer(map, clustermarkers);

Here is Another demo which is not clustering : http://jsfiddle.net/u758rqpa/47/
Answer: Yes, there is an option in MarkerClusterer to do what you want:
markerClusterer.setMaxZoom(MAX_ZOOM);
Where MAX_ZOOM is the maximum zoom of your map minus one (in your fiddle, that would be 16).
This means that when the map is zoomed all the way in, the marker clusterer is no longer being used and the map displays all markers that are in the clusterer at the zoom level.
This method is listed in the documentation for MarkerClusterer
Your fiddle with the markerClusterer.setMaxZoom() method: http://jsfiddle.net/u758rqpa/49/
Comment: can you please tell me how can i change MarkerCluster icon ?
Comment: @Nikunj - ask a new question.
Comment: Adam _ Here is My New Question. http://stackoverflow.com/questions/26294722/same-latitude-longitude-markers-display-at-different-places-in-google-maps


What is the ship icon near Ysgramor's Tomb?

Question: On my way to Ysgramor's Tomb, I saw a ship outline to the northwest and went to investigate.  I went out into the ice flows and the ship outline on the compass began to highlight as I got closer.  Then, it went poof and disappeared.  I never was notified that I arrived some place, and it does not show up on my map.  Does anyone know what this ship is and how do I reach it?
Comment: I know exactly what you are talking about.  I tried swimming down to it, but died a few times trying to investigate... by drowning
Comment: On PC (I don't know other consoles, must be tested) there's a bug that if you down to water your head (on first person camera) to the half, and you can see the water line at half of screen, you are able to view all objects under water without the "fog" of a disturb water.
Answer: It is an under water ship, which can be investigated, if you want to investigate fully i recommend either a water breathing potion or spell.
Comment: @IrishJMA Is it worth investigating? Depends on how much you like [iceberg lettuce](http://i.imgur.com/ZFSLm.jpg).
Comment: so it won't trigger that I've been there unless I swim down to it?  is it worth investigating?
Comment: Yes you have to go to it to get the icon to become white (dunno how else to put it), as for 'is it worth it?' i'm not sure as i cannot remember what is there nor do i remember the name to look it up in the wiki. Go there then look the name in the wiki to find this out...
Answer: Sounds like Pilgrim's Trench
Answer: There isn't any loot down there and other than for the purposes of adding a discovered location to your map, no, there isn't much point in going down there. If you do though, have a few water breathing potions well stocked and some health potions if you begin to drown.
Comment: If you want an answer, please [ask your own question](http://gaming.stackexchange.com/questions/ask). Adding a post is reserved for actual answers only.
Answer: I haven't been to the ship yet since I only heard about where it was now but I do plan on searching it. You could try a water breathing enchantment or something. I'm not sure where but I found a helmet once with the enchantment and I just put it into a ring. Should help if you don't want any healing potions or water breathing ones.


Does Spark incur the same amount of overhead as Hadoop for vnodes?

Question: I just read https://stackoverflow.com/a/19974621/260805. Does Spark (specifically Datastax's Cassandra Spark connector) incur the same amount of overhead as Hadoop when reading from a Cassandra cluster? I know Spark uses threads more heavily than Hadoop does.
Comment: Running a smaller unscientific benchmark to test this. If noone else responds, I will at least share my findings.
Answer: I'll give three separate answers. I apologize for the rather unstructured answer, but it's been building up over time:
A previous answer:
Here's one potential answer: Why not enable virtual node in an Hadoop node?. I quote:

Does this also apply to Spark?

No, if you're using the official DataStax spark-cassandra-connector. It can process multiple token ranges in a single Spark task. There is still some minor performance hit, but not as huge as with Hadoop.

A production benchmark
We ran a Spark job against a vnode-enabled Cassandra (Datastax Enterprise) datacenter with 3 nodes. The job took 9.7 hours. Running the same job on for slightly less data, using 5 non-vnode nodes, a couple of weeks back took 8.8 hours.
A controlled benchmark
To further test the overhead we ran a controlled benchmark on a Datastax Enterprise node in a single-node cluster. For both vnode enabled/disabled the node was 1) reset, 2) X number of rows were written and then 3) SELECT COUNT(*) FROM emp in Shark was executed a couple of times to get a cold vs. hot cache times. X tested were 10^{0-8}.
Assuming that Shark is not dealing with vnodes in any way, the average (quite stable) overhead for vnodes were ~28 seconds for cold Shark query executions and 17 seconds for hot executions. The latency difference did generally not vary with data size.
All the numbers for the benchmark can be found here. All scripts used to run the benchmark (see output.txt for usage) can be found here.
My only guess why there was a difference between "Cold diff" and "Hot diff" (see spreadsheet) is that it took Shark some time to create metadata, but this is simply speculation.
Conclusion
Our conclusion is that the overhead of vnodes is a constant time between 13 and 30 seconds, independent of data size.
Answer: Performance with vnodes and without in the connector should be basically the same. With hadoop each vnode split generated it's own task which created a large amount of overhead.
With Spark, tasks contain the token ranges from multiple vnodes and are merged into a single task and the overall task overhead is lower. There is a slight locality issue where it becomes difficult to get balanced numbers of tasks for all the nodes in the C* cluster with smaller data sizes. This issue is being worked on in SPARKC-43.
Comment: Thanks RussS! Since you are a Datastax dude you might find the benchmark mentioned in http://stackoverflow.com/a/29942469/260805 interesting.
Comment: Shark actually will be treating vnodes differently than normal Spark operations since it uses the Hadoop input formats under the hood. It's performance will be much close to the old Hadoop vnodes performance except the per task overhead will be much less.  Thanks for publishing your results.


How to add images to listview in android?

Question: I want to load images to listview.
Look likes this.

I do not know how to add this images to listview.
When click this list item its load another activity.
Can i add this mages to list and set to adapter?
Comment: This is very simple and basic, I don't think using lib :)
Comment: use custom list view/try lazy list view https://github.com/thest1/LazyList
Answer: In http://www.mkyong.com/android/android-listview-example/
Instead of String Array You have to use Integer array & Put your drawable images in it.
Like this:
int images[] = {R.drawable.product1, R.drawable.product2, R.drawable.product3, R.drawable.product4, R.drawable.product5, R.drawable.product6, R.drawable.product7};

&
fetch your images in your ImageView like this:
imgview.setImageResource(arr[position]);

you are done.
Comment: I tried your answer. what about this error?02-27 16:29:12.993: E/AndroidRuntime(1702): java.lang.NullPointerException
02-27 16:29:12.993: E/AndroidRuntime(1702):  at android.widget.AbsListView.obtainView(AbsListView.java:2467)
02-27 16:29:12.993: E/AndroidRuntime(1702):  at android.widget.ListView.measureHeightOfChildren(ListView.java:1250)
02-27 16:29:12.993: E/AndroidRuntime(1702):  at android.widget.ListView.onMeasure(ListView.java:1162)
Comment: Its says 02-27 16:39:22.963: E/AndroidRuntime(2385):  at android.widget.AbsListView.obtainView(AbsListView.java:2467)
02-27 16:39:22.963: E/AndroidRuntime(2385):  at android.widget.ListView.measureHeightOfChildren(ListView.java:1250)
this.measureHeightOfChildren
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/48566/discussion-between-sagar-shah-and-anuruddhika)
Comment: simple and clean !
Answer: you need to create custom xml(only with image) for your list view and you need to set custom adapter to your list view.

    check this link this will help you.

        http://www.mkyong.com/android/android-listview-example/

    or try this

    Activity file:

    public class MainActivity extends Activity
    {

         ImageView selectedImage;
         private Integer[] mImageIds = {
                    R.drawable.ic_launcher,
                    R.drawable.android3d,
                    R.drawable.ic_launcher,

            };
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

                 ListView gallery = (ListView) findViewById(R.id.gallery1);

            gallery.setAdapter(new GalleryImageAdapter(this,R.layout.img));

             // clicklistener for Gallery
            gallery.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    Toast.makeText(MainActivity.this, "Your selected position = " + position, Toast.LENGTH_SHORT).show();

                }
            });
        }
       class GalleryImageAdapter extends BaseAdapter
    {
        private Context mContext;

        int layout ;

        public GalleryImageAdapter(Context context, int layout)
        {
            mContext = context;
            this.layout = layout;
        }

        public int getCount() {
            return mImageIds.length;
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        // Override this method according to your need
        public View getView(int index, View view, ViewGroup viewGroup)
        {
            // TODO Auto-generated method stub

            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

                View rowView = inflater.inflate(layout, viewGroup, false);

                ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
                imageView.setImageResource(mImageIds[index]);

                return rowView;

        }
    }
    }

    activity_mail xml:

        <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ListView
                android:id="@+id/gallery1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

         </LinearLayout>

    img xml :

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <ImageView
            android:id="@+id/img"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>

Comment: In this case i want to add Image list not the String array.
Answer: For this kind of behaviour you need to implement your own adapter. As you are using an Arrayadapter you should extend Arrayadapter and overwrite the getView method to change the view of the ListItem in the way you want it to. Have a look at this ListView Tutorial for more information on this topic. http://www.vogella.com/tutorials/AndroidListView/article.html
Comment: Yes i had work with adapters. But the case is this images are dynamically change. i want to add images to list and load to adapter.
Comment: Yeah, in getView() you has a variable position, set image for your view. If u have a List images, u can get Image i = images.get(position), and set this image into your view.
Answer: You can do it using custom adapter of Items. Each item is an ImageView as the following example:
MainActivity:
this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
setListAdapter(this.adapter);

And create the following adapter class:
ItemsAdapter:
private class ItemsAdapter extends ArrayAdapter<Item> {

private Item[] items;

public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
    super(context, textViewResourceId, items);
    this.items = items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.items_list_item, null);
    }

    Item it = items[position];
    if (it != null) {
        ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
        if (iv != null) {
            iv.setImageDrawable(it.getImage());
        }
    }

    return v;
}
}

Then add your desired action in the onItemClickListener
Comment: what about this getSystemService and getImage() method?
Comment: It display this error. The method getImage() is undefined for the type ClipData.Item
Comment: @anuruddhika, `Item` is a user defined object. Create a class called Item and do the setter and the getters for it :)


Logging out the current user in social user

Question: I am overriding the social user in social core but how can I log out the current user? If I log out the request linked with the social auth, I am getting an error saying that 'AnonymousUser' object has no attribute 'social_auth'.
def social_user(backend, uid, user=None, *args, **kwargs):
    provider = backend.name
    social = backend.strategy.storage.user.get_social_auth(provider, uid)
    if social:
        if user and social.user != user:
            logout(backend.strategy.request)

Any ideas?
Answer: The biggest question here is what you want logout to mean. If a user is logged into your application via their Google Account, they probably don't want want to logout from Google if they are using their own laptop, tablet, or desktop.
For this reason, python-social-auth does not include logout logic, and neither does OAuth2, really, but both Django and Flask include a logout mechanism which you can use to logout from only your web application.
You've tagged django, so you could include django.contrib.auth.views.LogoutView as one of your URLs, and link your "Sign-out" function to that URL, or you could write your own URL, and somewhere within call django.contrib.auth.logout. It is generally friendly to confirm to the user that they are logged out, and provide some sort of simple template page that confirms they're logout; this is the function of that view django.contrib.auth.views.LogoutView that I referenced above.
If you want to go farther, the URL to use for each backend could be quite difficult if you are supporting several such backends. See Logout link with return URL (OAuth) for more information on this.
You also should do something to figure out whether the user wants to logout completely; as this is not typical with OAuth2. Your solution will require some sort of user interface element. Here are some possibilities:

You could ask them via a form before they logout - "[ ] Do you want to logout completely from Google?". When the form is posted back, you decide whether to redirect to a logout URL for Google. This is a bit of a security risk, because they may click Sign-out and then go to lunch.
You could simply let them know know afterwards that they've been logged out of your application, but not out of google. Again, this can be a security risk.
You could ask when they login what they want to do, indirectly.  Maybe you present a login interface that includes a checkbox like "[ ] This is a computer that I trust" before the list of social backend buttons, and save that button check in the session. Then, when they sign-out, you can keep the "contract with the user" by simply doing it.

Because python-social-auth has such an excellent settings mechanism, you can store a backend specific LOGOUT_URL in the settings, for instance:
SOCIAL_AUTH_GOOGLE_OAUTH2_LOGOUT_URL='https://www.google.com/accounts/Logout'

Again for how to continue back to a confirmation URL, see Logout link with return URL (OAuth).
Answer: My answer below is long, and complete. The simplest answer is that python-social-auth doesn't handle logout, because OAuth2 doesn't handle logout. To logout of your own app, simply write your own view based on django.contrib.auth.views.LogoutView so that you can override the template cleanly:
from django.contrib.auth.views import LogoutView

# ...

class MyLogoutView(LogoutView):
    template_name = 'myapp/logout.html'

mylogout_view = MyLogoutView.as_view()


One input 4-state switch

Question: I have a wire and I need to go through 4 outputs - 4 states. I have found different switches like this, but there is not enough states...  Do you have any idea of how to do one?
Far far in the past I remember something like this:
Comment: 2 nand memory cells are the things that you need. but how to wire them is real challenge.
Comment: @Fennekin I have just edited the question. I need a simple trigger with 4 states, is that so hard to make?
Answer: I did a quick redstone work. I think that you will compact it.
I will explain it anyway.
there are 4 output states. (not considering 0th state)
1st state -> block in front of white wool
2nd state -> block in front of megenta wool
3rd state -> block in front of yellow wool
4th state -> block in front of blue wool
mechanism:
an dropper is facing in hopper. also hopper is facing in the dropper. so when the hopper is unlocked, swords will flow into the dropper.
the input button is not visible in this image. it is on the sandstone block directly next to the dropper.
when you press input button once , sword gets dropped in the hopper, the signal strength of comparator increases and you get output as stage 1. on second press you get output state 2, and so on...
when you are in 4th state and press the button again, hopper gets filled with anoter sword, thus signal strength of  comparator increases and with the pulse extender piston retracts thus flushing all swords from hopper back to dropper.

One input 4-state switch


redirecting subdomain to main domain with htaccess

Question: I am building a website with two main sections,
so I have created two subdomains:
web1.example.com
web2.example.com
since i'm building websites with codeigniter, I want to redirect to the index.php page. here's what I did:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^web1.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/web1 [R=301,NC,L]

it works as expected, but it changes the url to example.com/web1..
is there any way to keep the url web1.example.com, but still redirecting to example.com/web1?
I already am using .htaccess file:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    ErrorDocument 404 /index.php
</IfModule>

when I enter web1.example.com, the actual url to be executed should be:
example.com/web1, and file to be executed is index.php ..
Comment: What is your expected output URL
Answer: Didnt tested, Modify and try this
RewriteRule ^([a-zA-Z0-9-/]+).example.com$ http://example.com/$1 [L]
RewriteRule ^([a-zA-Z0-9-/]+).example.com/([a-zA-Z0-9-/]+) http://example.com/$1&$2 [L]

Edited 1
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.example\.com
RewriteRule ^(.*)$ http://example.com/index.php/%1&$1 [L,NC,QSA]

Comment: What is your expected output URL and What URL need to be executed
Comment: should I place .htaccess inside sub domain folder, or in root directory?
Comment: edited my question with current htaccess file..
tried to add your code to it, but nothing happens..
Comment: Also provide: example url, expected url, the file need to execute on that url
Comment: when I enter web1.example.com, the actual url to be executed should be: example.com/web1, and file to be executed is index.php ..

this is what you meant?
Comment: Yes, wats the parameter that pass to index.php
Comment: there could be countless number of parameters, URI segments..
there is one required param which is 'web1' or 'web2', depends on which sub-domain you entered..
Comment: where is the index.php file
Comment: example.com?index.php⊂=web1  Is this to be executed for web1.example.com
Comment: see the Edited 1 above
Comment: works, but I am redirected to example.com/web1 instead of staying in web1.example.com ..


visual studio 2017 html tag selector

Question: I'm looking for the tag selector that visual studio 2013 has but visual studio 2017 does not have or I just cant find the extension.

in the bottom right part of the image you can see the tags hierarchically and on click, dropdown pops up with "select tag", "select tag content" etc...
Now I cant find this on 2017 and I'm nearly having an hearth attack or cancer or sth.
where is that functionality on vs2017???
Answer: I've found the solution.
just navigate through
Tools > Options > Text Editor > Html > advanced
and set Enable Tag Navigator -> TRUE
jeez that has to be standard
Comment: I agree. it should be enabled by default. Noticed the same issue when opening .chtml files

visual studio 2017 html tag selector


Can we send command for Quectel M66 from STM32F103C8T6 via UART port?

Question: I am currently working with STM32F103C8T6 and Quectel M66 module. I need to send some command from STM32's UART port for creating a socket connection in M66 and to send some data via that socket to a server in Quectel M66. Is there any way to do that? And I am using FreeRTOS for this.
          And what kind of data are possible to send via UART port of STM32?
Any help would be greatly appreciated...Thanks in Advance
Comment: What do you mean by **what kind of data**. UART support **8 Bit** data transfer either of **char Type* or of **uint8_t** type. Generally **char** is also **8 Bit** data.
Answer: There's two ways you can achieve this:

Using AT commands and TCP/IP stack built into the module. In this mode you send AT commands to connect/listen/send/receive/close sockets.
Using PPP and TCP/IP stack inside the microcontroller. In this mode you initially configure the modem using AT commands (which you have to do in both approaches anyway), then you switch the modem to data mode, at which point it starts communicating with you using PPP protocol. You use this to integrate it with the TCP/IP stack in your microcontroller. That way you use all the functionality of the stack you choose (socket API, DNS etc.) and you're not limited to what API quectel provided. You can also take advantage of having multiple network interfaces connected to your microcontroller, for example to perform routing.

How you approach it is totally up to you. If you want just the basic socket functionality, first approach will probably be better for you as it's easier to get it to work. Second approach takes quite a bit more effort but yields better results / more flexible product for the future.
For AT commands documentation check out this link (especially the TCP/IP application note): https://www.quectel.com/product/m66.htm
Comment: Can I send AT commands to M66 via UART port as a string ( I mean uint8_t data type). Would M66 understand that?
        For example: UART_Transmit(&handler,"AT+QIOPEN",sizeof(AT+QIOPEN));                        Is it right?
Comment: You'll probably need to do line end to the command (making it "AT+QIOPEN\r\n") but yes, that's exactly what you do. AT commands are essentially a text based protocol.


Dockerfile - parameterized FROM

Question: I want to include arguments in the FROM section. Is this possible? In the Dockerfile, I have:
ARG VERSION
FROM tomcat:$VERSION

I build as following:
docker build --build-arg VERSION=8.0 .

I get the following error:
Please provide a source image with `from` prior to commit

I am using docker version 1.12.6.
Answer: Docker 1.9 has added support for build time arguments.
Reason for the error
Comment: if you want to use ARG, install latest stable docker version
Comment: (SUPPORTED VERSION)[https://docs.docker.com/release-notes/docker-ce/#17050-ce-2017-05-04]
Comment: Any idea why it is not working on my side? I am using Docker version 1.12.6.
Comment: it does not support ARG
Comment: I will try that out.
Comment: The answer is really that you need Docker 17.05 or later to use an ARG as a FROM argument: "But until recently (Docker's 17.05 release, to be precise), you weren't able to use an ARG to specify all or part of your Dockerfile's mandatory FROM command."

Dockerfile - parameterized FROM


How do I send a username and password to git's credential user prompt from my powershell script?

Question: I am using a script to checkout and update a list of branches. I am able to retrieve git credentials from the Windows Credential Manager and I need to respond to the prompt for git credentials using them.
How do I send text to the git user prompt from my script? I have tried ECHO and piping the text directly to the git call but neither method is working (the prompt still appears and nothing is typed in).
[PSCredential]$cred = Get-StoredCredential gitCred
$cur_head = "$(git rev-parse --abbrev-ref HEAD)"
$cred.Username |  git pull origin ${cur_head} -q

or
ECHO $cred.Username |  git pull origin ${cur_head} -q

Note: I am using the windows credential manager to store my git credentials, I do not want to put them in any other credential manager
Answer:
In a couple of my scripts I use this:
$env:GIT_USER="."
$env:GIT_PASS=$token
Invoke-Git config --global credential.helper "!f() { echo \`"username=`${GIT_USER}`npassword=`${GIT_PASS}\`"; }; f"

To pass an arbitrary username/password from the environment of the running powershell session. The code above passes a Personal Access Token, but you can easily set the environment variables with a different value.
You could also install the Git Cretential Manager (Core), which would automatically fetch the creds from the windows credential manager.
For those interested in the implementation of Invoke-Git:
function Invoke-Git {
<#
.Synopsis
Wrapper function that deals with PowerShells peculiar error output when Git uses the error stream.
.Example
Invoke-Git ThrowError
$LASTEXITCODE
#>
    [CmdletBinding()]
    param(
        [parameter(ValueFromRemainingArguments=$true)]
        [string[]]$Arguments
    )

    & {
        [CmdletBinding()]
        param(
            [parameter(ValueFromRemainingArguments=$true)]
            [string[]]$InnerArgs
        )
        if ($isDebug) { "git $InnerArgs" }
        git $InnerArgs
    } -ErrorAction SilentlyContinue -ErrorVariable fail @Arguments

    if ($fail) {
        $fail.Exception
    }

}

Comment: Nice, but it's worth clarifying what `Invoke-Git` is, given that it's not a standard cmdlet. Is it just a wrapper around the `git` executable with error handling? Out of curiosity: what is the benefit of defining the `f` function instead of using just the `echo` command alone?
Comment: Subbing `git` for `Invoke-Git` allows me to run it, and it works perfectly
Comment: Why a function... No clue, I'm not a king in bash and someone pointed me to this ages ago and it works. Why change it ;).
Comment: This looks useful over all, I would also like to know where `Invoke-Git` is coming from!
Comment: @jessehouwing, thanks for updating. Fair enough re function :) From what I can tell (using direct invocation of `git`), the following will do (the `!` prefix tells `git` that the value is a shell command): ``git config --global credential.helper "! echo \`"username=`${GIT_USER}`npassword=`${GIT_PASS}\`""``


Commutator subgroup having a complement

Question: Suppose we have a finite group $G$ such that $[G,G]$ has a complement in $G$. Then what are some "good" things we can conclude from this situation? I know that "good" is not well-defined, but I am sure there are people on here who would come up with some good facts. Thanks
Comment: well, all nonabelian group of order $pq$ has this property; $|G'|=p$ where $p>q$ and it has a complement.
Answer: A few observation;
Let $G=G'H$ where $G'\cap H=1$;
since $G/G'\cong H$ we must have $H$ is a abelian group.
If $H$ is normal in $G$ then $G'$ is a perfect group. (so, $G$ is not solvable)
since  $G= G'\times H\implies G'= G''\times H'$  but since $H$ is abelian $H'=e$
So we have $G'=G''$ so $G'$ is a perfect group.
You can set such group as an example, $G=A_5\times C_2$.
Comment: yes this is a nice observation and i have upvoted the answer, but i will wait and see if i get some other "good" observations before i accept it. Thanks
Answer: Another observation, if $H$ is a complement of $G'$, then $H$ is also a complement of each member of the lower central series $\gamma_{i+1}(G)$ for any $i\geq 1$. This can be proved by induction: if $G=HG'$, then it follows that $G'=H'[G',G]$, and this can be substituted in $G=HG'$. In particular, $G$ cannot be nilpotent.
In addition to Mesel's remarks: if $H$ is normal, then $H \subseteq Z(G)$, the center of $G$, since $H \cap G'=1$. In that case, $G=G'Z(G)$.
Comment: Thanks, this is nice as well.

Commutator subgroup having a complement


Unable to authenticate REST API request on dialogflow v2 and v2beta1

Question: Authorisation issue when we use this code to connect to dialogflow
Comment: Please refer https://stackoverflow.com/help/how-to-ask.
Answer: V2/V2beta1 of the API relies on a Google Cloud Platform Service Account for authentication, instead of the previously used client and developer access tokens.
Generating the Service Account key
In order to use the V2 API, you will need to create a new Service Account and obtain a private key associated with the Service Account. The key is downloaded as a JSON file upon creation of the Service Account.
Caution: Your project will have an existing service account, but this should not be altered. For additional client and developer API access, you should create a new service account.

Please first login into your Dialogflow console and select the appropriate project (only if you have multiple projects). Go to the settings of Dialogflow and click on the service account link as shown below:

Note: Also make sure to enable beta features and APIs.

Now this will redirect you to your GCP service account page. From there you need to click on  navigation menu (Top Left Corner) and select APIs & Services > Credentials.
Now Click on Create credentials and select Service account key.
Note: Please note that if you have multiple projects linked to your GCP choose the appropriate project from the drop down and choose your project from the all tab rather than recent tab.
Now Choose New service account from the drop down list. Give a name to this service account and please make sure to select the role to Owner. Select JSON (by default selected).
Now click on Create Button. Your JSON key file will be downloaded to your system.
Now use this JSON key file to authenticate your requests.

Now download V2/V2Beta1 API from nuget package manager on visual studio.
Please refer this code:
<code>var rFile = GoogleCredential.FromFile(jsonkeyfilepath);
        var scopeC = rFile.CreateScoped(DialogflowService.Scope.CloudPlatform);
        var response = new DialogflowService(new BaseClientService.Initializer
        {
            HttpClientInitializer = scopeC,
            ApplicationName = "project-name-here"
        }).Projects.Agent.Sessions.DetectIntent(
                    new GoogleCloudDialogflowV2beta1DetectIntentRequest
                    {
                        QueryInput = new GoogleCloudDialogflowV2beta1QueryInput
                        {
                            Text = new GoogleCloudDialogflowV2beta1TextInput
                            {
                                Text = "your text here",
                                LanguageCode = "en-US"
                            }
                        }
                    },
                    $"projects/projectid/agent/sessions/34141414")
                    .Execute();
        return (JsonConvert.SerializeObject(response.QueryResult));
</code>


Cells detection using deep learning techniques

Question: I have to analyse some images of drops, taken using a microscope, which may contain some cell. What would be the best thing to do in order to do it?
Every acquisition of images returns around a thousand pictures: every picture contains a drop and I have to determine whether the drop has a cell inside or not. Every acquisition dataset presents with a very different contrast and brightness, and the shape of the cells is slightly different on every setup due to micro variations on the focus of the microscope.
I have tried to create a classification model following the guide "TensorFlow for poets", defining two classes: empty drops and drops containing a cell. Unfortunately the result wasn't successful.
I have also tried to label the cells and giving to an object detection algorithm using DIGITS 5, but it does not detect anything.
I was wondering if these algorithms are designed to recognise more complex object or if I have done something wrong during the setup. Any solution or hint would be helpful!
Thank you!
This is a collage of drops from different samples: the cells are a bit different from every acquisition, due to the different setup and ambient lights
Comment: You need to indulge in some image pre-processing steps before feeding the images to the network. Normalization is a key aspect
Comment: @JeruLuke what do you mean by Normalization? I have tried to find an answer elsewhere, but I couldn't find a unique solution.
Answer: This kind of problem should definitely be possible. I would suggest starting with a cifar 10 convolutional neural network tutorial and customizing it for your problem.
In future posts you should tell us how your training is progressing. Make sure you're outputting the following information every few steps (maybe every 10-100 steps):

Loss/cost function output, you should see your loss decreasing over time.
Classification accuracy on the current batch of your training data
Classification accuracy on a held out test set (if you've implemented test set evaluation, you might implement this second)

There are many, many, many things that can go wrong, from bad learning rates, to preprocessing steps that go awry. Neural networks are very hard to debug, they are very resilient to bugs, making it hard to even know if you have a bug in your code. For that reason make sure you're visualizing everything.
Another very important step to follow is to save the images exactly as you are passing them to tensorflow. You will have them in a matrix form, you can save that matrix form as an image. Do that immediately before you pass the data to tensorflow. Make sure you are giving the network what you expect it to receive. I can't tell you how many times I and others I know have passed garbage into the network unknowingly, assume the worst and prove yourself wrong!
Your next post should look something like this:

I'm training a convolutional neural network in tensorflow
My loss function (sigmoid cross entropy) is decreasing consistently (show us a picture!)
My input images look like this (show us a picture of what you ACTUALLY FEED to the network)
My learning rate and other parameters are A, B, and C
I preprocessed the data by doing M and N
The accuracy the network achieves on training data (and/or test data) is Y

In answering those questions you're likely to solve 10 problems along the way, and we'll help you find the 11th and, with some luck, last one. :)
Good luck!
Comment: Thank you very much for your answer: it really gave me a great help to start. I've moved back to data preprocessing at the moment: I have found and customised some script in order to augment my dataset, but I can't find a way to normalize the images, as it seems that every website/user/tutorial on the web interprets "image normalization" in a different way... any suggestion? I'm using Matlab to edit images
Comment: Just use tensorflow's `tf.image.per_image_standardization`. Just feed it to tensorflow as the uint8 format (less cpu->gpu transfer) and convert to 32 bit and standardize in the graph. Other preprocessing steps you can see in the cifar10 tutorial. You can do brightness changes, flip the image randomly, randomly crop and shift the image, etc. All of these perturbations are beneficial.


extjs 3.2 add vertical scrollbar dynamically

Question: 2,I am displaying more than 15 records in gridpanel . But only 10 records are displaying, other records are hiding below. I want to add vertical scrollbar to gridpanel, how can i achieve this.
Comment: Show some code so we can understand where you getting problem.
Answer: You can use autoScroll : true config
OR
give overflow:auto css property to body of grid


Fix imperfection on wall (scratches / bumps)

Question: Everyone, at some point, start damaging walls.
A chair bump, a scratch and all in between.
I learnt how to make the surface flat again using fillers and then I tried painting carefully using the same paint but...
No joy.
It is always visible that some damage was there.
Paint ages and it is close to impossible to match the same color.
I know that the perfect solution is paint everything again but I'm also curious about some old trick or creative solution to make the wall look nice without painting the whole room.
Comment: @Pitto, in my experience if the paint is 2 years or more on the wall or in the can, you will not get optimal results using it to touch up patches.  That said One may get results that are acceptable because of shadowing,
Comment: Depending on the location of the patch, it is usually much easier to make it a design statement than trying to match and hide.  Most walls are painted one colour, but if there damage that you fix, can maybe paint a strip across the wall in a different colour.
Comment: Wait til you have a whole bunch of imperfections and bang out the whole wall at once?
Comment: For very small patches, ( 1/2 dollar or smaller)  I have found dabbing the paint with a brush rather than strokes removed the possible stroke marks and blended the edges finer.  Larger repairs I use a small roller and then dab the edges.  If the paint is old, either on the wall or in the can there is going to be "scars" no matter what you do.
Comment: Thanks to everyone for the great tips! A quesiton @rmdman which is (a very rough) time to consider a paint old?
Answer: One of the main reasons repairs show up is because the wall texture is different between the wall and the repair. Many times, DIYers will sand the repair smooth and then paint. If the wall had any type of texture, even just from a paint roller being used for the original paint job, the repair will stick out like a sore thumb. So try to match the existing texture. Don't paint the repair with a brush. Chances are, the wall was painted with a roller so use that for the repair. Feather the rolling out from the repair to blend in the new paint with the old. This only works if you're using the same paint, same can, as the old paint.
If you have leftover paint, you don't need to paint the whole room, just paint the one wall. You probably won't be able to tell the difference. If you don't have any leftover paint, get a contrasting color and paint the one wall as a accent wall.