How to solve "dpkg: error: 1 expected program not found in PATH or not executable"?

Question: I have installed the LAMP Server using the command sudo apt-get install lamp-server^. Thereafter, whenever I open the terminal the following error started to appear:
 bash: /home/gaja/.bashrccu: No such file or directory
 bash: /home/gaja/.bashrc: line 4: syntax error near unexpected token ('
 bash: /home/gaja/.bashrc: line 4: see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)'

I could get rid of this problem using the answer given here.
However, now the problem is that I cannot install any thing using the sudo apt-get command.
I am trying to become root and then re-run the sudo apt-get install lamp-server^ command which gives the following error output:
dpkg: warning: 'tar' not found in PATH or not executable
dpkg: error: 1 expected program not found in PATH or not executable
Note: root's PATH should usually contain /usr/local/sbin, /usr/sbin and /sbin
E: Sub-process /usr/bin/dpkg returned an error code (2)

Following is the complete output of running the commands:
gaja@gaja-System-Product-Name:~$ sudo su
[sudo] password for gaja:

root@gaja-System-Product-Name:/home/gaja# sudo apt-get install lamp-server^
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libdbi-perl' for task 'lamp-server'
Note, selecting 'perl-modules' for task 'lamp-server'
Note, selecting 'libaprutil1-dbd-sqlite3' for task 'lamp-server'
Note, selecting 'perl' for task 'lamp-server'
Note, selecting 'apache2-bin' for task 'lamp-server'
Note, selecting 'libapache2-mod-php5' for task 'lamp-server'
Note, selecting 'ssl-cert' for task 'lamp-server'
Note, selecting 'mysql-server-5.5' for task 'lamp-server'
Note, selecting 'mysql-client-core-5.5' for task 'lamp-server'
Note, selecting 'libclass-isa-perl' for task 'lamp-server'
Note, selecting 'mysql-server' for task 'lamp-server'
Note, selecting 'libapr1' for task 'lamp-server'
Note, selecting 'php5-readline' for task 'lamp-server'
Note, selecting 'libaprutil1' for task 'lamp-server'
Note, selecting 'libwrap0' for task 'lamp-server'
Note, selecting 'libdbd-mysql-perl' for task 'lamp-server'
Note, selecting 'apache2-mpm-prefork' for task 'lamp-server'
Note, selecting 'libhtml-template-perl' for task 'lamp-server'
Note, selecting 'mysql-client-5.5' for task 'lamp-server'
Note, selecting 'libaio1' for task 'lamp-server'
Note, selecting 'mysql-common' for task 'lamp-server'
Note, selecting 'libmysqlclient18' for task 'lamp-server'
Note, selecting 'mysql-server-core-5.5' for task 'lamp-server'
Note, selecting 'libterm-readkey-perl' for task 'lamp-server'
Note, selecting 'php5-mysql' for task 'lamp-server'
Note, selecting 'apache2-data' for task 'lamp-server'
Note, selecting 'apache2' for task 'lamp-server'
Note, selecting 'php5-common' for task 'lamp-server'
Note, selecting 'php5-cli' for task 'lamp-server'
Note, selecting 'libswitch-perl' for task 'lamp-server'
Note, selecting 'libaprutil1-ldap' for task 'lamp-server'
Note, selecting 'tcpd' for task 'lamp-server'
libaio1 is already the newest version.
libapr1 is already the newest version.
libaprutil1 is already the newest version.
libaprutil1-dbd-sqlite3 is already the newest version.
libaprutil1-ldap is already the newest version.
libclass-isa-perl is already the newest version.
libdbd-mysql-perl is already the newest version.
libdbi-perl is already the newest version.
libhtml-template-perl is already the newest version.
libswitch-perl is already the newest version.
libterm-readkey-perl is already the newest version.
libwrap0 is already the newest version.
perl is already the newest version.
perl-modules is already the newest version.
ssl-cert is already the newest version.
tcpd is already the newest version.
apache2 is already the newest version.
apache2-bin is already the newest version.
apache2-data is already the newest version.
apache2-mpm-prefork is already the newest version.
libapache2-mod-php5 is already the newest version.
libmysqlclient18 is already the newest version.
mysql-client-5.5 is already the newest version.
mysql-client-core-5.5 is already the newest version.
mysql-common is already the newest version.
mysql-server is already the newest version.
mysql-server-5.5 is already the newest version.
mysql-server-core-5.5 is already the newest version.
php5-cli is already the newest version.
php5-common is already the newest version.
php5-mysql is already the newest version.
php5-readline is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 230 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue [Y/n]? y
dpkg: warning: 'tar' not found in PATH or not executable
dpkg: error: 1 expected program not found in PATH or not executable
Note: root's PATH should usually contain /usr/local/sbin, /usr/sbin and /sbin
E: Sub-process /usr/bin/dpkg returned an error code (2)

root@gaja-System-Product-Name:/home/gaja# sudo apt-get install apache2
Reading package lists... Done
Building dependency tree
Reading state information... Done
apache2 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 230 not upgraded.
2 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue [Y/n]? y
dpkg: warning: 'tar' not found in PATH or not executable
dpkg: error: 1 expected program not found in PATH or not executable
Note: root's PATH should usually contain /usr/local/sbin, /usr/sbin and /sbin
E: Sub-process /usr/bin/dpkg returned an error code (2)
root@gaja-System-Product-Name:/home/gaja#

Some of the troubleshooting steps that I have taken on suggestion of other members:
$ ls -l /bin/tar
ls: cannot access /bin/tar: No such file or directory

$ apt-cache policy tar
tar: Installed: 1.26+dfsg-8 Candidate: 1.26+dfsg-8 Version table: *** 1.26+dfsg-8 0 500 in.archive.ubuntu.com/ubuntu saucy/main i386 Packages 100 /var/lib/dpkg/status

I have also tried running the following command after switching to root, but that doesn't help either:
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

Comment: We have consolidated all the information which was scattered around for the problem that you are facing. From now onwards, please comment below the answers to which you are replying... If it involves code then it would be better if you [edit] your question and format it properly.. See [editing-help](http://askubuntu.com/editing-help) for more information.. AND PLEASE DO NOT OPEN ANOTHER QUESTION ON THE SAME TOPIC, AS I SAID EARLIER [EDIT] THIS QUESTION...
Comment: Edit the question and include `sudo -i sh -c 'echo $PATH'` output.
Answer: The root's $PATH environment variable is not set properly, so dpkg cannot find tar to extract the packages.
Try the following after switchung to root:
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

And then run the apt-get command again.
Comment: I tried your solution but still the same problem exist
Answer: From your question and the following comments it is clear that tar is installed but the executable /bin/tar is missing. You need to add it manually as your dpkg will not work without tar.
First check the following files are already there,
ls -l /etc/rmt
ls -l /usr/lib/mime/packages/tar
ls -l /usr/sbin/rmt-tar
ls -l /usr/sbin/tarcat

I am not listing doc and man files. A complete list can be found here.
You can download the .deb package for tar manually from packages.ubuntu.com. Download the exact package for your architecture.
Next extract the .deb file in a system where archive manager is available. If you extract the .deb file there will be a directory named bin under the main directory. you need to Copy the executable tar from extracted bin directory to /bin/.
You can first put the executable tar to your home directory. Next use the following in terminal to copy it to /bin,
sudo cp tar /bin/
sudo chmod 755 /bin/tar

just check the owner of /bin/tar is root. and it must have execution permission for all. The output of ls -l /bin/tar should look like,
-rwxr-xr-x 1 root root ...

This should work. you may need to install the suggested packages if not installed already.
Comment: Sorry, I Couldn't extract the deb file into tar file.
Comment: try to extract the deb file on another computer. then bring the expanded folder to your computer using a flash drive or sftp.
Answer: I had a similar error while trying to do a distribution upgrade from Debian Squeeze to Wheezy (I know this is a Ubuntu Stack Exchange, but my solution may work for you). Here is the command I executed when I received the error:
sudo apt-get dist-upgrade

Here is part of the error:
dpkg: 3 expected programs not found in PATH or not executable.

I changed to the root user with the following command and tried again:
su root
apt-get dist-upgrade

And the installation succeeded without error.


Android chat, add new message showing

Question: I'm working on chat activity with firebase and recyclerview. I've encountered little issue. When new message appears im using notifyItemInserted and then smoothScrollToPosition. When few first messages come (till screen is not full filled with messages) they are showing really smooth and it looks like same as in Facebook Messenger, but when it comes to scrolling to new message which is out of height our screen it pops up in blink of an eye which looks not good. I thought it has something to do with view recycling by recyclerview or with that smoothscrolling, but I dont know how to handle this.
Some asked code:
    mMessagesList.add(message);
    mChatRecyclerAdapter.notifyItemInserted(mChatRecyclerAdapter.getItemCount()-1);
    rvChatMessages.smoothScrollToPosition(mChatRecyclerAdapter.getItemCount()-1);

Could You guys share some tips with me?
Thanks
Comment: Try posting some of your code where you insert into the recyclerview so we get an idea of what you're working with - whenever I use notifyItemInserted, I have the smooth pop in you're looking for.
Answer: There is lots of unknown in your question but generally speaking if you are using RecyclerView (as you mentioned), you could improve your UI experience by using reverseLayout set to "true" in your LinearLayoutManager (my guess). Doing so would make your messages appear at the bottom of the list. This still has its own issues if you do paging, depending on how you do paging etc.

An update (key points from chat below) :

Use reverse LinearLayoutManager (option of constructor) - not the same as stackFromBottom
Add data to beginning of data collection (.add(0, ...)
Call notifyItemInserted(0) on adapter
Comment: Thanks for your answer im using in my LinearLayoutMenager method: setStackFromEnd(true), and it is working perfect but this is not issue at all. When for example: first 7 messages arrive (and they fit on screen and there is no need to use scrollToPosition) they are showing in recyclerview really really smooth. But when it comes to scroll to new messag which is appearing outside the view (outside screen) and then we scroll to it , this message is not showing that smooth.
Comment: Are your new messages appearing always at the bottom of the screen? I'm trying to understand why scrollToPosition is needed. I can imagine scroll is needed when, for example, user is several pages up the list, but not when the list is always appended at the bottom - there is always never message at the bottom.
Comment: If all done right (and if I got your point correctly), you should be doing `notifyItemInserted(0)` and not `notifyItemInserted(mChatRecyclerAdapter.getItemCount()-1)`
Comment: Oh, and there is difference between stackFromEnd and reverse layout. Please do check I believe it will be helpful!
Comment: I just tested out your updated answer so: without method smoothScrollToPosition new message shows below screen (i have to scroll to it by hand), but with method smoothScrollToPosition its the same issue as before :(
Comment: Do you have maybe some other tips?

Android chat, add new message showing


Is there any example of using weighted loss for pixel-wise segmentation/classification tasks?

Question: I am doing FCN32 semantic segmentation on my data. I ran the algorithm to fine-tune for my data (grayscale images with only one channel), till 80,000 iterations; however, the loss and accuracy are fluctuating and the output image completely black. Even, the loss is so high after 80,000 iterations. I thought the classifier cannot do training well on my data. So, I am going to train from scratch.
On the other hand, my data has imbalanced class members. The background pixels are more than the other four classes. Some researchers are suggesting using weighted loss. Does anyone have any idea? Am I doing the right way? How can I add this weighted loss to train_val.prototxt?
I will be thankful if you know any resources/examples related to training with weighted loss, please share with me here.
Thanks again
Answer: You can tackle class imbalance using "InfogainLoss". This loss can be viewed as an extension to "SoftmaxWithLoss" that enables you to "pay" different loss value per label.
If you want to use "InfogainLoss" for pixel-wise predictions, you might need to use BVLC/caffe PR#3855.


How to send HTTP request and get json data back using Angular

Question: When a user clicks "Get HTTP Data" button the getData() method defined in the app.component calls http service's getData() method that is supposed to return the json data. But instead it returns the ZoneAwarePromise object:

export class HttpService {
  jsonFile = '../assets/products.json';

  getData(): Promise<any> {
    return this.http.get(this.jsonFile)
      .toPromise()
      .then(response => {
        console.log(">>> .then got response:", response);
      })
      .catch(this.handleError);
  }

Here is the link to the Stackblitz project:
https://stackblitz.com/edit/angular-ivy-ukgwct?file=src%2Fapp%2Fhttp.service.ts
How to fix this issue and make the http service to return the json data?
Answer: I have the fixed the issue in the stackblitz link. - https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.ts
The problem is, in the service, you do not subscribe to observables or listen to the promises using then or cathErrors during the creation( this is your case )
Rather, you should subscribe to the service in the component, where you are injecting it.
Comment: I can't see any changes on Stackblitz project. What script did you edit?
Comment: I created a fork and then added the changes. Check this link -  https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.ts
Comment: See if this helps - https://stackblitz.com/edit/angular-ivy-qmq58v?file=src%2Fapp%2Fapp.component.html


Displaying a large data set in a table cell

Question: What is the best way to display a large data set, e.g. 50 words, in a table cell?  I am thinking maybe a linkable piece of text such that when clicked, displays a popup box with the full text.  Another idea what to display a few words with a hover/tooltip option to display the rest of the text.
Thoughts?
Please refer to this jsfiddle for an example of the structure I am working with
Comment: What set up are we talking about here? If it's html a table cell could easily be the size of a screen. If a certain cell in a row/column is always going to be so large and displaying all data is always important it's easy enough to increase the size of the cell to display it all. Is it unusual that 50 words will be in this particular cell?
Comment: 50 words is perhaps the maximum content that will be displayed in the table cell though the average number of words will most likely be less.
Comment: All people have given suggestion but without any link, example or reference. Please provide some examples to do this. I also need to expand some data in multiple cells for a report. Thanks !
Answer: Both of your ideas are good, and here is a third.
Include a small link in the data cell saying "more" that when clicked, expands the table cell dynamically to show the full text. The link when expanded changes to say "less" which then collapses the table cell.
Deciding which options to choose will depend on the importance of the user being able to view the complete text in context.
Answer: I am assuming that its not about one cell, and that you will have a bunch of these cells in your table. If not just ignore the whole thing i wrote - and possibly notify me to remove my post :)
If yes, you will have to make some analysis of couple of things before you decide if you will go with popup or tooltip

frequency of reading that large part (if you are browsing for products, there is a good chance that i would like to see some more info about it frequently - which implies that popup will probably annoy me since it involves extra steps of closing and opening a window - so tooltip)
ability to compare them (wach out for a short term memory, you don't want an info to expire while person closes one window and opens the other - so tooltip again)
ability to focus on the content a person is reading (it is far more comfortable to use a popup instead of a tooltip, especially if there will be some complex actions in it - so popup)
content structure (if that content is consistently structured, than its easy to quickly skim through many data cells, since after the first 2 you learn how to read it. If its not you will probably spend more time in each - so popup)
size of that content (you dont want some HUGE tooltips on your page, especially if its bigger than a table cell - you will endup covering the other cells - so popup)
Answer: I explored all these options: hover, expand, twitter-esque sliding pane etc etc and all have pros and cons:
hover if it is unlikely word count will over run contents of cell. you can see the problem if every cell has to expand on hover and how annoying that would become.
expand seems to work pretty well if the hidden content is not too expansive. this approach also hands control back to the user that on hover does not
new window / sliding div or whatever works if the cell contents are really large, but then you have to ask yourself, why are you putting this kind of information in a table? Having said that, this approach is great for storing extra attributes that are tangentially linked and helpful to the object in the cell and I have used it as a way of allowing users to scan a list of objects, identify the most relevant record and display a div with all attributes associated with that record, an example of this might be a table of holiday notes where the cell lists the description of an activity for the user to identify and on click reveals a window, pane, whatever, of details related to the activity eg price of hire car, lunch details etc etc.
Not a good approach for when the user has to compare columns though.
But the bottom line is, whichever option you go with, test!
Answer: Maybe another solution... You can show the full content of this cell in a infobar under the table with no delay, when you roll over a row. But its depend on how fast must explore the user the cell informations. Otherwise the tooltip is a good solution in most cases.


How to throw an exception in a Promise catch block? (Unhandled promise rejection)

Question: I have a multiple functions that return a Promise. In case of an error they use reject. But I want to handle the errors in the catch block of Promise.all() call. But when running it causes an Unhandled promise rejection.
function errorFunc() {
    return new Promise((_, reject) {
    reject('rejected in errorFunc')
  })
}

Promise.all([
    errorFunc(),
]).catch(reasons => {
    //throw new Error('an error occured', reasons)
  console.log('an error occured')
})

As you can see the console.log works fine, but running when throwing an exception it fails.
I have read multiple articles and threads on unhandled promise rejection but I have not found a solution to that problem.
Here is the failing code on JSFiddle: https://jsfiddle.net/qkptbjnz/1/
How do I solve this issue? Or do you have a suggestion for a better error handling?
Edit I want to achieve some kind of validation like here: https://jsfiddle.net/89d5nLcw/
Comment: What's your goal here? You can handle the error in `catch` which is the intended way. No need to rethrow the error
Comment: It works just like with `try`/`catch`: when you re-`throw` an exception from the `catch` block, you will have to catch that again somewhere else, or your program crashes.
Comment: @JensV I have a "validateObject" functions which calls multiple other validation functions asynchronously. When everythings done I want to throw an exception if one of them failed.
Comment: @JensV https://jsfiddle.net/89d5nLcw/ this is kind of the idea
Answer: Well, you should not throw an error in catch section, this block is designed to handle the errors.

function errorFunc() {
    return new Promise((_resolve, reject) => {
    reject('rejected in errorFunc');
  });
}

Promise.all([
  errorFunc(),
]).catch(error => {
 console.log('an error occured', error);
})

like here you can see the message you threw above.
Comment: Yes that works but my handling of errors lays a layer above. What I try is to run multiple validation functions and catch all errors in a simple way. And after that, if any errors occured, I want to throw another error. Jus printing would continue the program although error occured here.
Comment: ok, im not sure, seems like you kinda try to catch the same error twice for some reason. `Promise.all` will throw an error if something happened, u dont have to catch it instantly. just make sure your "layer above" will catch it, and thats all.
Comment: well. all i can add is you dont need to catch the error to rethrow it again. just dont catch it until u need it =)
Comment: This is closer to what I want to achieve: https://jsfiddle.net/89d5nLcw/
Comment: Okay, thanks. I guess I'll have to rethink my structure.


How to use two different argument captors in one test method?

Question: I have a problem using captors to test two separate calls of the same method, but with different argument type.
I provided a code sample of what I'm trying to do here - basically I want to verify if certain method was called twice but with different type arguments using two separate captors, and then call some assertions on captured objects.
public class Foo {
}

public class Bar {
}

public interface MyClient {
  void doSomething(Object obj);
}

public class MyService {
    private MyClient client;

    void doSomething() {
        client.doSomething(new Foo());
        client.doSomething(new Bar());
    }
}

@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {

    @InjectMocks
    private MyService testObj;

    @Mock
    private MyClient myClient;

    @Captor
    private ArgumentCaptor<Foo> fooCaptor;

    @Captor
    private ArgumentCaptor<Bar> barCaptor;

    @Test
    public void testSomething() {
        testObj.doSomething();

        verify(myClient).doSomething(fooCaptor.capture());
        // ...do something with fooCaptor

        verify(myClient).doSomething(barCaptor.capture());
        // ...do something with barCaptor
    }
}

I'd expect this test would pass as is, because captors specify argument types, so shouldn't this work same as ArgumentMatchers.any(Foo.class) etc?
Currently I'm getting TooManyActualInvocations - 2 instead of 1.
How do we handle such cases? I don't like the idea of using one  captor and then cast the results.
Answer: Try to combine the captors with the isA matcher using the and operator from the AdditionalMatchers package.
import static org.mockito.AdditionalMatchers.and;

// ...

verify(myClient).doSomething(and(isA(Foo.class), fooCaptor));
verify(myClient).doSomething(and(isA(Bar.class), barCaptor));

Comment: Captor is not a matcher, I guess you meant `verify(myClient).doSomething(and(isA(Foo.class), fooCaptor.capture()))` etc, but still Mockito is unable to handle this situation when you try to call getValue: `org.mockito.exceptions.base.MockitoException:
No argument value was captured!
You might have forgotten to use argument.capture() in verify()...`


how do i redirect after logout in asp.net

Question: I've placed login status control on a page, and placed under LogoutPageUrl to Default.aspx.
However, after I logout it redirects me to
<code>...default.aspx?ReturnUrl= some stuff
</code>
So, it does not redirect me directly to default.aspx. How do I force 'real' redirect ?
Thanks
EDIT:, solved: this in linkbutton:
<code>        Session.Abandon()
        FormsAuthentication.SignOut()
        Response.Redirect("~/Default.aspx")
</code>
Comment: If you solved your problem, post the solution as a response and mark it as the answer.
Comment: and what is the problem with that? you still load the Default.aspx right?
Comment: The problem is that this extra url points to previous page which is not available to some roles, so some users may not login to the site.
Answer: Place linkbutton and this code onCLick()
<code>Session.Abandon()
FormsAuthentication.SignOut()
Response.Redirect("~/Default.aspx")
</code>
Comment: use web.config value is better than hard code:
Response.Redirect(FormsAuthentication.DefaultUrl, false); //redirect to website defaulturl


Why does water from outside spigots seem to "stutter" (starts and stops)?

Question: I live in a 1950s-built home in a warm climate.
When I run water from an outside spigot, such as to water plants, it's not uncommon for the output to "stutter" near the start and then again occasionally during operation. In other words, the water coming out stops for a half-second and there's a noise and then it's coming out again.
This behavior is not seen on any of the interior faucets.
What causes this "stuttering"? Is it a sign of a serious problem? And is there an easy way to fix this and get a smooth and continuous water flow from the outside spigots?
Comment: Do you have a shutoff for that valve? Have you verified that it is fully open?
Answer: Sounds to me like you have some air in the line.  It could just be because you have a length of pipe/hose after the valve, which partly empties out when you shut the valve, trapping air.  Or I supposed you could have a small leak somewhere in the system.  But I probably wouldn't worry about it.
Comment: I think that might be it because from the spigot there is a long hose attached that's wrapped around a barrel. Maybe water/air are getting trapped in the hose after shutoff and that would explain the "stuttering."
Comment: @ScottMitchell:  If that's the case ,then I go so far as to say it is definitely the cause and you don't need to worry about it.  (You should accept the answer)


Is it possible to activate a squad-bonus enchanced ammo type without overriding squad members' settings?

Question: If, for example, I get Shepard to activate Cryo Ammo (which has the +50% effectiveness for squad mates) then it replaces any ammo setting they my squad mates have active. If I then switch on one of their powers (which has the same squad bonus) then it overrides Shepard's ammo setting. The two ammo types become mutually exclusive.
This is a problem because it means only the person with the last ammo type activated has it at full effectiveness, and I can't diversify.
Except for the obvious of respec'ing and avoiding the squad bonuses (so each member has to manage their own ammo types, which is what I'll do if I really have to) is there any way to avoid overriding a squad mate's ammo setting when activating one on another member that has a squad bonus?
Answer: Only one Squad Ammo power can be active at a time. You don't need to respec everyone, just respec the people who you would rather have using ammunition other than Squad Ammo.
But no, there's no other way around this.
Comment: Damn, thought that would be the case, so thanks for the confirmation. Oh well, guess I'll need to have a tweak of people's skill sets at some point...
Answer: Since squad ammo only affects the weapon equipped at the time you can have all 3 members of your crew with a different ammo power. How this would work: this hypothetical crew would need to also have all 3 members with an ammo power, so let's take Garrus (AP) Vega (Incendiary) and Shepard could have any other, say Warp. Equip your main weapon on Shepard and activate the ammo type you want there, then switch weapons. Active the ammo type on Garrus with the weapon you want him to use, and then have him switch weapon. Lastly, have Vega active his ammo type on his primary weapon. Then have Shepard and Garrus both switch to their main weapon. The ammo power applied will be the type applied while it was equipped during all of those steps. By changing this around a little you can apply none native ammo powers to the whole crew, albeit at the -50% effectiveness penalty.


Cutting depth of a Jig Saw

Question: I'm looking at getting a hand held Jig Saw like the Bosch 150 CE because it has the longest cutting depth 15cm(6"). I'm wanting to do some end notching on 150mm x 150mm lumber.
For example:

What I'd like to know though is what happens when you attempt to cut through a larger piece then the blade is specified for, e.g. 200mm? Must the blade be able to extend past the other side of the material, or can you do a cut only part way into it? So if I wanted to notch a 200mm piece, could I do a 150mm cut, then flip the wood over and cut the remaining 50mm?
For example:

I asked several sellers at stores why all the Jig Saws they have only have it specified that they can cut to 150mm max, yet they sell blades for 200mm. Nobody could tell me why.
If this isn't how you would tackle a notch on pieces bigger than 150mm, could you point me in the direction of how you would do it? At the moment I'm using a hack saw and chisels and it takes too long considering how many I have to do.
Comment: I think what you propose will work, however, you will need to endure that your cut face is zeroed, so that the multiple passes on the jigsaw is accurate. the only concern is that you will be putting a lot of strain on that motor. dont expect it to last long at all!
Answer: Hand-held jigsaws are not the right tool for cutting large notches in a 6x6 post. Yes, the blade must extend past the wood - they only cut on the front of the blade, not the bottom. And the blade will drift quite a bit going through 6 inches of lumber. Jigsaws are meant for fine detail work, not large straight cuts.
However, a close cousin is the reciprocating saw like the Bosch RS35. Larger motor, much heavier blades. You still have the problem of squaring off the bottom of the notch, but if you use a large auger bit to make a series of holes you will be able to remove the bulk with one good hammer hit and then use a thinner blade or a chisel to flatten out the bottom.
If you have a large number and want to mass-produce the notches I would rent a 12 to 16 inch circular saw, line up all the posts, bind them together, and make a jig to hold the saw in position on the ends. Cut, move blade down a bit, repeat.
Comment: If the tip of your jigsaw blade bottoms out while cutting, it'll push the whole saw back into your hand. Feels kinda like the whole tool is doing pushups at 1740rpm.
Comment: I do have a reciprocating saw and with some long blades that can do the job but the problem was accuracy. Sometimes getting curved cuts. Lining a bunch up might do the trick although I'd have to lay them horizontally which could be problematic with my circular. Thanks for the tips
Answer: I would do this with multiple passes with a table saw, using a jig and standing the piece on its end to get the proper orientation. Carefully cutting it with a band saw would do pretty good to, but not everybody has a table or band saw. Compared to a jig saw, for this type of cut, you may do as good with a circular saw. It would not be the safe way to do it without making safeguards for your cutting.
Comment: Thanks for this.

I have a circular which I have used a bit for this but it doesn't feel the safest or the ideal method.

With a bandsaw, or jigsaw, I would do 2 cuts into the end, but then it seems like a bit of a hack job to do the perpendicular cut. Would you need a jig saw to clean it all up in the end, whether you did it with a band or table saw?

These logs I'm working with are up to 6m (20') in length making it really hard to manoeuvre.
Comment: It could all be done with a bandsaw, you would make a one cut straight into the bottom, start the other cut in, but you make a tight radius cut to steer it into the bottom, then remove the cut piece, then finish squaring in the bottom by coming back across the bottom, to finish the corner. I will make a few sketches to illustrate how to do this and use the circular safely. You will need a few clamps with the circular saw.
Comment: I just realized after I read your comment the second time on the lengths of your material, yes, that would be more than difficult on a table saw, or a band saw to for that matter
Answer: How many? A regular hand saw will do the job nicely if you don't need 30 of the things. Do two straight cuts, a couple diagonals, and a little work with a wood chisel to finish off the bottom.
Answer: I am sure you can do a partial depth cut with a jigsaw. I have done the same in a 4" thick wood piece, when the cutting depth of the blade was only 3-4/9". There was no problem of the saw "jumping up", as opposed to what the other responders have mentioned. The quality of cut was also O.K. (it depends upon the blade you use). I recommend Bosch T744D blade for a 6"-7" depth of cut.
Comment: Thanks, yeah I found with my blades I was also able to do a partial cut. I went nice and slow and didn't have issues with jumping back.

Cutting depth of a Jig Saw


Prove by mathematical induction $n < 2n$

Question: Prove the following by mathematical induction
$n < 2n$, for all positive integer $n$.
This is what I have done:
Step 1:
$n=1$: $1 < 2$
Step 2:
$k < 2k$
$n=k+1$: $(k+1) < 2(k+1)$
$k + 1 < 2k + 1 < 2k + 2 = 2(k+1)$
Hence $P(k+1)$ is true whenever $P(k)$ and since $P(1)$ is true.
I didn't write all necessary assumptions but can anyone help me to check if my method is correct or if it needs improvements. Thank you.
Comment: It seems correct. Just try to be more explicit in your steps by saying. "this is our induction hypothesis"... "this is what we'll prove"...
Comment: The argument looks fine but the presentation could use some improvement.
Comment: What is your definition of "$<$"?
Comment: when you say $k+11$
Comment: For $$k=1$$ the proof was given by the OP
Answer: We have to prove that $$n+1<2(n+1)$$ , adding $1$ on both sides of $$n<2n$$ we get
$$n+1<2n+1$$ and $$2n+1<2(n+1)$$ so the proof is finished.
Comment: This is induction


Tedious on connect event not firing in function

Question: I am trying to connect to Local SQL Server database using Tedious in node js.
function connectToSql() {
    sqlConnection.on('connect', function (err) {
        // If no error, then good to go...
        if (err) {
            console.log(err);
        } else {
            console.log('connected to SQL!');
            executeSelectStatement();
        }
    });
}

When I am invoking this function soon after its declaration, its working fine and prints 'connected to SQL!'. But when I am calling this function "connection" event of SocketIO.Server its not making sql call. My code is as below:
ioServer.on('connection', function (socket: SocketIO.Socket) {
    console.log('a user connected');
    connectToSql();
});

it only prints 'a user connected'
Any suggestions why is this happening?
Answer: It is likely that the SQL connection has already been established before the Socket.io connection takes place. That being the case, the connect event has probably already happened.
If you're looking to only establish the SQL connection after receiving a Socket.io connection, you probably need to new Connection(config); at that time while also subscribing to the connect event.
Do note that you probably do not want to establish an SQL connection for every Socket.io connection as with multiple people utilizing the application, a lot of additional overhead is taking place where it likely does not need to.
Comment: Reily, From where the call for SQL connection is being invoked? Since the SQL connection call is within the function and the function is invoked only in socket.io connection, how can it be already connected?
Comment: On Socket.io connection you're binding to the SQL `connect` event, not connecting to SQL. Binding to this event will let you know when the connection has been established with SQL, which is probably long before the Socket.io connection


Can I use epoxy grout on tiled shower and bathroom floors?

Question: I'm considering white grout for bathroom shower walls (the floor will be covered with a shower tub). Wanting to avoid problems with graying, mold and mildew in the shower and sink back-splash area, I thought I could grout those two areas with epoxy grout.
Is white epoxy grout a good idea for shower?
Another, more unlikely idea is to grout the floor tiles with white epoxy grout. I fear that the traffic and usage will discolor it anyway. Can you give some advice on that?
Answer: A lot of people like to tell horror stories of epoxy grout and over the years its uses has become a bit cloudy. However, epoxide resin based grouts are specifically formulated to resist chemical attack and to provide a durable, abrasion resistant waterproof finish that is hygienic and impervious.
The cured grout does not transfer taints to foodstuffs, permit the entry of bacteria, or dirt and is easily maintained in a sterile condition. With this in mind it makes a perfect food counter grout.
As for use in a shower base it is perfectly acceptable to use and in some cases preferred over cement based grouts as it does not allow water to penetrate.
As for staining and discoloring these will happen in a lot of situations it really depends on the quality of your water and what minerals it has in it. Over time they will tend to leech on any surface that has water coming into contact with it. Even plastic nozzles will do it. However most surface cleaners will remove such stains very easily as long as they are not left for extended periods to build up. I should also point out these stains wont appear over night. They can take months and or years so its not really something concern yourself with hugely.


Proof of series convergence

Question: Proove that if the series $\sum_{n=1}^{\infty} (n a_n)^2$
is convergent, than the series $\sum_{n=1}^{\infty} a_n$
is also convergent.
Comment: Could you rewrite the problem clearly, please? I can't understand!
Comment: Is $a_n$ supposed to be non negative ? What have you tried ? Where do this problem come from ?
Comment: Yes, it is supposed to be non negative.
Comment: I have seen a similar problem that uses the limit comparison test, but I am not sure if it is correct.
Comment: You will get more help here if you show what you've tried and what are your difficulties.
Comment: I have calculated a lim of a_n/(na_n)^2. The calculated limit is 0, so it is proven that the series converges, right? Thanks.
Comment: Why does $a_n/(na_n)^2=1/(n^2a_n)$ goes to $0$ as $n$ goes to infinity ?
Answer: Hint : $a_n = n a_n\times \frac{1}{n}$ and use the inequality
$$\forall (x,y)\in \mathbb{R}^2,\qquad 2xy\le x^2+y^2.$$

Proof of series convergence


three20 error after adding it to my project

Question: I have been trying to add the Three20 framework to my app. But I always end up getting this error:
<code>Undefined symbols:
"___restore_vfp_d8_d15_regs", referenced from:
+[TTEntityTables(TTSingleton) sharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) releaseSharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) allocWithZone:] in libThree20Core.a(TTEntityTables.o)
"___save_vfp_d8_d15_regs", referenced from:
+[TTEntityTables(TTSingleton) sharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) releaseSharedInstance] in libThree20Core.a(TTEntityTables.o)
+[TTEntityTables(TTSingleton) allocWithZone:] in libThree20Core.a(TTEntityTables.o)
ld: symbol(s) not found

collect2: ld returned 1 exit status
</code>
it seems like some kind of linker error to me, but I'm rather shure I followed all instructions on how to install the framework.
Somehow I get the suspicion, that it is a bug within the framework, but I'm not shure. Any ideas?
Answer: Make sure that, in the build settings, you've selected 'Standard' for the architectures and that 'Build Active Architecture Only' is unchecked.
Comment: Ok, I got it working now. The trick is to set this in each and every project of Three20. additionally I've set the BaseSDK to iPhone Device, instead of Simulator. I suppose this helped, too. Once again not only in my app, but in every part of Three20.
Comment: I checked. Both settings were as you suggest them.
Comment: As I had the same problem with device building and I googled for it and I got the above solution which solves the building problem with device.


Database Tables - To decouple or not?

Question: Is it better to create tables that store a lot of data that are related to an entity (User for example) or many tables to store said data?
For example:
User Table

Name
Email
Subscription Id
Email Notifications
Permissions

Or
User Table

Name
Email

Subscription Table

User ID
Subscription ID

Notification Table

User ID
Receives?

... etc
Please consider code in this as well, or I would have posted to ServerVault.
Comment: its called normalisation, and yes, you should normalise.
Answer: From a relational design standpoint what is important is the normal form you're aiming for.  In general, if the "column" would require multiple values (subscription_id1, subscription_id2, etc) then it is a repeating group, and that would indicate to you that it needs to be moved to a related table.  You've provided very general table and column notes, but taking a cue from the fact that you named "Email Notifications" and "Permissions" with plurals, I'm going to assume that those require related tables.

Database Tables - To decouple or not?


TFS, Source code, SharePoint

Question: How can I add my Sharepoint project as source code into TFS? I have the original directory in my host machine, and I make it as a shared folder between the host and VM.
When I try to debug the Sharepoint project (on VM) and deploy my changes, then attach the w3wp processes and start the web page, the "Service is unavailable" message appears.
How can I deploy my changes on the project and work on my project as a source code?
Comment: Are you asking how to get your project into TFS or how to deploy to SharePoint from Visual Studio?
Answer: The problem that you are experiencing isn't directly related to TFS or Source Control. In order to add your project to source control, you just need to open it and select "Add to Source Control". I recommend doing this from your host machine.
For a smooth operation, you should first create proper workspace mappings in TFS and put your project inside a TFS workspace. Please check this for more information:
http://msdn.microsoft.com/en-us/library/cc138514(v=vs.90).aspx
You should probably post the "Service is unavailable" part of your question to a Sharepoint forum since it's unrelated to source control.

TFS, Source code, SharePoint


Write a SQL query

Question: This image contain the question
i am trying to solve this sql problem Write a SQL query to print the total rainfall in the states where the total rainfall is greater than the average of all the cities in the table 'Rainfall.
expected output:
'Maharashtra', '45'
'Kerala', '45'
'Gujarat', '11'
Comment: Please read https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions
Comment: Welcome Ashish to stack overflow, can you please share what you have tried so far?
Comment: Welcome to Stack Overflow!  You are encouraged to make an attempt to write your code.  If you encounter a specific technical problem during that attempt, such as an error or unexpected result, we can help with that.  Please provide specific information about that attempt and what didn't work as expected.  To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources.
Comment: I have tried SELECT L.State, SUM(R.Rainfall)
AS Total_Rainfall
FROM Rainfall R
JOIN Location L
ON R.City = L.City
GROUP BY L.State
HAVING SUM(R.Rainfall) > (SELECT AVG(Rainfall) FROM Rainfall);
Comment: Please don't misuse comments to improve your question or to add clarifications. Edit your question instead.
Answer: The sql query would be
<code>SELECT * FROM Rainfall WHERE "Rainfall(dm)" > (SELECT AVG("Rainfall(dm)") FROM Rainfall) ;
</code>
I am not the best in SQL, But this should work.
Comment: No, it will not work. Please try out solutions BEFORE writing an answer. You can for example use fiddle sites like https://dbfiddle.uk/3aMmxpPT

Write a SQL query


Handling B64 encoded data in Python

Question: In my Google App Engine based app, I am fetching data from a SOAP webservice.
The problem is that one of the tag contains binary 64 encoded data. I decode it using
decodedStr = base64.b64decode(str(content))

It seems that the decoding is not done correctly a I get garbage data in decodeStr. I think the problem is that the content string is falsely parsed as a unicode string instead of simple byte string
Can any Python guru tell me how to handle b64 encoded data in Python?
For now I am using this workaround
fileContent = str(fileContent)
fileContent = fileContent[3:-3]
self.response.out.write(base64.b64decode(fileContent))

Comment: Wait...this is really confusing.  Manually excluding content is resulting in valid b64 decoded data?  Does 'content' include extraneous (non b64 encoded). Data?
Comment: The value sent by webservice does not contain any non encoded data. but when I convert it to str, the value is encapsulated by these characters  u'( . So Just to remove these characters I trim 3 characters. After that the b64decode function converts the data correctly.
Comment: It sounds like you have an answer to your question -- but I thought it might help to point out that if the string actually includes prefixed such as you quoted, then it is not a clean b64 stream. It sounds like the webservice is sending you a python-formatted unicode string, and your app is swallowing it with the unicode prefix. Actually, if the variable name 'fileContent' is an indication it came from a file, it sounds like someone streamed a unicode string to a file, and your app swallowed it whole from there (with the prefix)
Answer: You could try using base64.decodestring or if you were passed an url base64.urlsafe_b64decode.
Make sure that the data is not in base16 or base32.
Answer: Strange.  If the content were not b64 encoded, the call to decode should raise a TypeError exception. I assume that's not happening?
Which would lead me to wonder how you know the resulting decodedStr is not what your after?

Handling B64 encoded data in Python


gridfilters plugin + stateful grid

Question: I'm using on my grid:
plugins: {
   gridfilters: true
},

Using ExtJS 7, Classic
I'm able to save the state of columns (position, width, etc.) but I can't find a way to save the applied filters on each column.
I guess there's no documentation for that.
Is it possible? How should I proceed?
Thanks.
Comment: Try to get filters from the store of the grid, not the plugin.
Answer: If you are only using gridfilters it is easy:
    plugins: {
        gridfilters: true
    },

    stateId: 'myGridIdLikePersonell',
    stateful: true,

In case this does not work for you, please add a fiddle.

If you are using gridfilterbar it does not come out of the box.
Most stateful items, which are not as easy as 'width' (which has a getter and setter) are a bit more work.

[optional] create a plugin which mixes in Ext.state.Stateful
add a stateId and stateful:['gridFilter']
add a config gridFilter
on init add a listener to the grid store filterchange
onFilterChange grab the property and value from each filter to define the filter. Update your stateful gridFilter (setGridFilter from config-gridFilter)
override the loadState method to allow you to write the filter back to the store
add a funtion being called from loadState and add store.filter(filter)

Voila - thats it

gridfilters plugin + stateful grid


How can the below 3 select statements be included in a single mySQL view

Question: Need to create a single view that executes the below 3 select statements
I am able execute them in a SQL editor and get the ratio.
select @lag := count(twitter_handles) from handle_impressions where today_impressions > yest_impressions;
select @decay := count(twitter_handles) from handle_impressions where today_impressions < yest_impressions;
select @ratio := @lag/@decay;

The intent is to have a single view encapsulating the 3 select statements to return lag, decay and ratio
Comment: You're missing the case when `today_impressions = yest_impressions`. Is this intentional? You might also want to have some type of measure to prevent division by 0.
Comment: good catch, will change one of the comparison to <=. Thanks.
Answer: We can try writing a single query using conditional aggregation:
SELECT
    COUNT(CASE WHEN today_impressions > yest_impressions THEN 1 END) AS lag_val,
    COUNT(CASE WHEN today_impressions < yest_impressions THEN 1 END) AS decay_val,
    COUNT(CASE WHEN today_impressions > yest_impressions THEN 1 END) /
        COUNT(CASE WHEN today_impressions < yest_impressions THEN 1 END) AS ratio
FROM handle_impressions;


Ubuntu 12.04.4 64-bit & AMD HD7850 GPU, issue with additional drivers menu

Question: My girlfriend just installed a fresh copy of Ubuntu 12.04.4 64-bit on her PC. After installing and updating the system, Ubuntu has been using the Open Source drivers for her GPU - the AMD HD7850 with 1 GB of GDDR5.
The issue
Games such as Nexuiz, Xonotic, Half-Life 1, Starbound and even No More Room in Hell run extremly good, at a minimum of 60fps, 1080p and with high details, but Left for Dead 2 runs at a low framerate (20-30fps) at low details. Other games, such as Rust and Anna, don't run at all (black screen). For this reason, above all, I recommended installing the proprietary AMD video drivers for her GPU.
The question now is; which one is the stable/recommended driver?

They're all the same, they all have the exact same description. I assume one of those is recommended and the others are beta drivers, just like it was in Ubuntu 12.04.3 64-bit. Or maybe the Open Source AMD driver has become the recommended driver, I don't know.
Thanks!
Answer: As a general rule for myself, if they all say the same thing then I check the description, in which case it was the same again. Most of the time, the second and third entries are an update and an experimental driver. I'd pick from the top and work my way down if nothing changes. The thing is it removes the previous driver and stops using it when you click to install one of the others.
I'd recommend going to the Ubuntu Help Page for Binary Driver installation. I just last night, installed Ubuntu 12.04.4 LTS on my desktop running AMD 995 Black Edition CPU with HD Radeon 6970 GPU, and nothing would install and kept wanting to send error reports. Now I realize this isn't your problem, but to avoid the problem because it was a pain, try removing/purging all traces of any previous 'fglrx' drivers installed prior, and clean it out, then re-install, and not from menu but via command line. I've always had the best results doing everything by command line and while I'm also aware that some users are worried about messing something up, its also the best way to learn. At the very worst, you'll have to re-install 12.04.4 LTS which you can quite easily do.
Also take a look at AMD Driver and Support website and read up about their latest proprietary driver release as there are some instructions on there as well.
And ofcourse don't forget to check which one you need to if you do do it via the AMD website or by command line, 32bit or 64bit.
Binary Driver How To
AMD Support Website Catalyst 13.12 x86
Comment: Btw, she just installed the Amd driver via the first entry and now she is testing some of the games I mentioned in my question. As soon as she starts Steam, it tells her to install the newest "experimental" drivers for best performance. Because of this, I assume you were right and the first entry is the stable driver branch.
Comment: Hello b00mtastik, thanks for responding so quickly. The problem is: My gf won't be able to do anything past the official "additional driver menu" by herself. Command line and manual driver installation is not only extremly risky and can cause all sorts of other issues (system instability being one of them), but it's also way too complicated for her to perform by herself. She is using LTS as her stable work and gaming machine and a complete reinstall of 12.04.4 would be... disastrous. She chose LTS because of it's superior stability & she can't afford to do any kind of dangerous testing on LTS.
Comment: PS: I told her to try your suggestion by installing the first/top entry. I'll call her right now and then I'll comment and tell you how it went. Btw, is this a known bug? I didn't experience any of this on 12.04.3. If it's new, I would like to report this bug so it can get fixed asap.
Comment: Nope, it was a fresh install but the machine she is using right now used to be my PC - before I gave it to her. I used the same machine with Ubuntu 12.04.3 64-bit LTS and then I switched to a laptop. That's why I mentioned 12.04.3, because in that version of the OS I actually saw the description you mentioned: normal, updates and experimental.
Comment: Sorry I deleted my previous comment, was trying to edit and it wouldn't let me since it had been after 5 mins. I'm still getting used to this. Lol.
From my research, 12.04.4 LTS brought on some more hardware capabilities. And I've only experienced this in 12.04.4 LTS that it had repeated entries of the same thing with no visible differences in the drivers from the menu.

[Hardware Enablement Stack](https://wiki.ubuntu.com/PrecisePangolin/ReleaseNotes/UbuntuDesktop#LTS_Hardware_Enablement_Stack)

[OMG Ubuntu Article](http://www.omgubuntu.co.uk/2014/02/ubuntu-12-04-4-released-new-kernel)
Comment: No problem. Yeah, 12.04.4 also has a new Linux Kernel, which was backported from Ubuntu 13.10. The new Kernel comes with the new and improved Radeon Open Source driver and other goodies, which is nice. Btw, this is the driver that gets installed when you select the first entry in the additional drivers list of 12.04.4: http://s7.directupload.net/images/140220/bi3wv9w6.png
Comment: Yeah see after doing the "Additional Drivers" list I couldn't even open Catalyst. It just kept doing errors and trying to report it. Thats when I wen to the binary driver help page and purged everything fglrx and re-installed via command line and it worked. I'll have to log back on tonight on that machine to make sure it wasn't just a fluke, though I did reboot multiple times to be sure.
Comment: I'm not sure if I should ask her to try out the other entries or not. With the first driver, which you can see in the pic I linked above, all of her games are launching fine and working as expected now. The framerate in LFD2 has improved, but it's still in the 30ish fps-rate though. Hm... I have had some issues with the "-updates" drivers from the additional drivers menu in the past, so I might just tell her to skip the second entry and try the last one instead, which should be the newest experimental driver (so far your theory has been right about this).
Comment: Following the logic of how it previously used to be with "updates" second and "experimental" third, that would be a decent assumption, until we are informed otherwise. Glad it has improved but maybe the experimental could help more. I just know from past experience that games always had a lower frame rate on a linux system. But I never figured out the root cause except for Minecraft as I believed the OpenJDK7 was the cause there. Java has always moved faster on a Windows System for me, could be the same for other games.
Comment: Yeah, well it really depends on the system. So far I have had even higher fps-rates with several games on my Ubuntu setup than I had on Windows 7. I really depends on what driver, os, settings etc. you are running on. In any case, do you know where we could report this bug? Is launchpad.net the place to go for this?
Comment: Yeah, according to this link regarding [Reporting Bugs](https://help.ubuntu.com/community/ReportingBugs) LaunchPad is the place to do it. [LaunchPad Ubuntu 12.04.4 LTS](https://launchpad.net/ubuntu/+milestone/ubuntu-12.04.4)
Comment: Hello friend, I just created a new bug-report for the issue. Could you confirm it please, since you have had the same experience too? Link: https://bugs.launchpad.net/ubuntu/+bug/1282793
Comment: Confirmed by clicking on "This bug affects me too."
Comment: Thanks mate, I also gave you an up-vote for the answer you provided me above. Now let's just hope the issue gets fixed soon. :)
Comment: Sup Boom, I just wanted to let you know that the issue was fixed via Ubuntu-updates. Cheers
Answer: I'll answer my own question.
The issue mentioned in my question above was fixed yesterday. Ubuntu-updates popped up and offered a bunch of updates, including updates for the additional drivers menu and jocky. The entries are now listed and working as expected.
Screenshots


How to hide/show data depending on an observable value (condition)?

Question: I'm playing with angular 2 and NGRX but I'm not an RxJs expert...
I got how to declare actions, dispatch them and paint simple data
@Component({
  selector: 'view-container',
  template: `

Seccion {{ viewSection | async }}

    <map-section [hidden]="!isMapSection()"></map-section>
    <graph-section [hidden]="!isGraphSection()"></graph-section>
    <data-section [hidden]="!isDataSection()"></data-section>
  `
})
export class ViewContainer {

  private viewSection: Observable<MainViewSection>;

  constructor(
    private store: Store<AppState>,
    private mainviewActions: MainViewActions
  ) {
    this.viewSection = this.store.let(getMainViewSection());
  }
}

MainViewSection is a simple enum model:
export enum MainViewSection {
  Map,
  Graph,
  Data
};

I know how to display which section I'm getting from the Observable using {{viewSection | async}}, but how can I compare what I'm getting in order to hide one or another section?
Before NGRX I was doing something like this:
isGraphSection() {
  return this.viewSection === MainViewSection.Graph;
}

But now this.viewSection is an Observable. Any ideas on how to achieve this?
Thanks!
Answer: You can pipe it first then compare, something like this:
{{(viewSection| async) === 1}}


How to determine fill limits when using different gauge wires

Question: I'm installing the wiring for a mini-split system which requires 8 ga (40 amp) wire. There is an existing conduit for a dedicated circuit (12ga) for an over the stove microwave.  It's mounted on an exterior wall.   The run to the mini-split outdoor unit will follow the same route.  Maybe I'm being picky, but having a bunch of exterior mounted pipes/conduits looks tacky, so I'd like to combine the microwave circuit and the mini-split circuit into one conduit.  My question how to determine fill capacity when using 2 different gauge wires.  It will be 3 12 ga and 3 8 ga. I'm guessing 1"  would suffice, but I"m not sure.
Comment: The one advantage to pvc is it quick to put together , I looked at some thhn the other day and want to say it had like 5 listings I think it was thhn , thwn, thwn-2 , MTW  and something else soon other than high temp fixture wire THHN will be an everything wire well it's close now.
Comment: @Ruskes  I think you mean the circumference = Pi x R2  = Pi x D.
Comment: What type of conduit are you trying to use for this run? I suspect 1" will be rather on the generous side
Comment: @EdBeal  It will be THHN/THWN, for all wires   This is just a follow up comment to complete the post.   Thanks again for your answer.
Comment: First what type of wire are you talking individual conductors like THHN or UF multi conductor cables? (Standard Romex or NMB can not be used outside in conduit).  There are tables in the NEC starting in chapter 9 and conduit fill tables in annex C that can help but we need to know the type of conduit and type of wire. With more than 2 conductors or cables the cross sectional area max is 40% NEC chapter 9 table # 1. The next thing we need is your mini split 120/240 or straight 240 (this affects the number of wires) we add the cross sectional area for the different sizes to get the area then siz
Comment: "Conduit Fill Calculator" in your search engine of choice. You'll need to know the particular type of conduit, as the actual ID varies slightly. Likewise the type of insulation on the wires (but that's usually THWN in this sort of application.) If the conduit is metallic you don't need a ground, if the conduit is shared by two circuits you only need one ground of the largest size.
Comment: If two of the wires you are counting are ground wires, and this was not an existing conduit, you can do it with 1/2" EMT properly grounded, at a hair under 33% fill. If you actually need 6 wires 3/4" EMT or PVC-80 (which means PVC-40 is also fine, if not exposed to damage) but really, just use a calculator where you can enter your wires and conduit and see what the fill comes out as... Since it IS an exsisting conduit, what is the material and size? You add up the cross sectional area of the wires and divide by the cross sectional area of the conduit.
Answer: Let's be lazy and say you have 6ea # 8 or smaller thhn as thhn is normally duel rated as thwn / thwn-2 it can be used outside in conduit.
The fill tables will allow 6 conductors in 3/4 EMT table C.1,,  6 on rigid metal C.8 or going to 1" schedule 80 pvc 7 conductors so the type and size of conduit makes a difference, if the outside unit was protected by elevation and we sharpened the pencil 3/4 sch 40 may work table C.10 at 5# 6 so if 3# 8 and 3#12 it would be close.
The cost difference between 3/4 and 1" is significantly higher for 1" especially for conduit bodies that are normally used when exiting the structure. So it all depends on the type of conduit
As 3/4 EMT would be the smallest outside at mini split ground level it would look the best and EMT holds paint better than PVC so 3/4 EMT would be my choice.
Comment: @JACK   yeah.   All the wire at Home Depot and Lowes is locked up.  They won't even give it to you when they unlock the cages.  They bring it up to a certain cashier and say you have to go thru check stand x to get your wire.   I bought 500' of 8 gauge copper THHN today and the employee walked with me to the check out station.  a 2.5" 10' length of PVC conduit is now $71, probably about $10 a couple of years ago. Just nuts.
Comment: @GeorgeAnderson  hope you had an armed guard going out to your car.
Comment: I ordered a couple spools of #6 a few weeks ago and when they were delivering it they called me , I went out to the loading dock and there was an armored truck I did not see the platt small van on the other side the guy from platt saw my face and really thought it was funny, copper has gone nuts in the last year.
Comment: Thanks Ed and all for the rapid response.  UV to Ed!  I went ahead with 1" just to be safe and know it will make for an easier pull.  Not only that, I had a number of various 1" fittings left over from a previous project. And another, "not only that", I went to HD and they were completely out of both 1/2" and 3/4" pvc and the price difference wasn't all that bad between 3/4 and 1. $4 extra per stick for 1" and I only needed 7 sticks, so it becomes a $28 decision. So being on the safe side, I'll go with  1" . Prices for electrical stuff is just plain nuts right now.
Comment: @GeorgeAnderson   Oh yeah... prices through the roof.
Comment: @EdBeal & JACK.  Yeah, it's unreal.  15 years ago when I wired my new home, 12/2 was about $120 for a 1,000' spool. While it's down from it's high of about $1,000 for a 1,000 foot spool to about $700, it's still crazy prices.   I think the thing that really surprised me was the astronomical increases in PVC conduit.  I have some left overs from other projects and think I should go to a home depot parking lot sitting on a curb with a sign saying, hey bud want to buy some conduit, cash only. LOL
Answer: Physical space
If you have a multi-conductor cable with a sheath, you must take the widest width of the cable and treat it as a single wire of the wide dimension.
Multiple circuits can share a single ground wire. The ground wire must be large enough for the largest circuit.  #10 ground will suffice for 25-60A circuits.  However, you can only "fork" the ground with a splice, and a splice requires you treat the junction box as a junction box and follow the "box fill rules" (which I won't cover here).
With the above settled, we can talk about physical conduit fill, or how many wires you can have in the pipe.  You don't need to crunch numbers - there are online "conduit fill calculators" which will do that for you, such as Southwire's.
Gory details?  OK, you consider the inside diameter of the conduit to determine cross-section in area.  Then the diameter of the wires (or wide dimension of cables) to figure its cross-section.  The wire cross section is summed up and compared to the conduit.

53% for 1 wire
31% for 2 wires
40% for 3+ wires

Thermal derate.
Wire ampacity limit isn't just about copper/aluminum cross-section.  It's also about skin surface area - the wire must be able to shed the heat made.  That is why 1000 kcmil aluminum is barely more than double the ampacity of 250 kcmil aluminum - while it has 4x the cross-section it has less than 2x the skin for radiating heat.
With conduit, you now have a bunch of wires making heat in a confined space. So wires must be thermally derated with many wires in same pipe.
TLDR: with 3 or fewer circuits, you don't have much to worry about.
Long version:
For any given wire or cable, you look up the highest thermal rating the insulation permits, except with NM cable you use 90C (even though it is 60C wire) per 334.80.  You look this up on Table 310.15(B)(16).
For instance #8 copper and #6 aluminum THWN-2 is allowed 90C which is 55A.  However in practice you can only get 50A out of it because of 75C thermal limitations on terminals.
#12 copper NM-B is allowed 90C (for this calculation only) which is 30A.   However NEC 240.4(D) limits it to 20A.
Now the derates.
In 'normal' 120/240V split-phase power, all circuits count as 2 conductors under the thermal rules.  I'll talk under that assumption.
If you have 2-3 circuits (3-6 wires that count) you must derate that number to 80% of ampacity.  Now #8Cu/#6Al is limited to 44A, and #12Cu is limited to 24A.  That pinches on the formerly 50A #8Cu/#6Al, but doesn't bother the #12 wire at all since it's already limited to 20A.
If you have 4 circuits (7-9 wires which count) you must derate to 70% of ampacity.  Now #8Cu/#6AL is pinched worse down to 38.5A, and #12 copper is limited to 21A which is still no problem.
If you have 5-10 circuits (10-20 wires which count) you must derate to 50% of ampacity.  This is punishing for all wire sizes. #12 is now 15A wire, #10Cu is now 20A, And #8Cu/#6AL is now 27.5A wire (can't even run a dryer).  As such, "more than four" circuits in a conduit is really best avoided.
10-20 circuits (21-40 wires which count) is a brutal derate to 35% - forget it. You're using #6AL for a 20A circuit at this point. This is the fatal flaw with novice ideas of using one giant conduit pipe the full length of a house.
Your case
For your 40A circuit, assuming 2 circuits, #8 copper or #6 aluminum can handle 44A.  Note that you need a disconnect at the mini-split, and the disconnect will be rated for aluminum wire even if the mini-split isn't.
You need a 120V outlet within 25' of the mini-split outdoor unit for the serviceman's benefit. If you don't already have plans for that, change the disconnect to a 4+ space subpanel and stick a 120V breaker in there for the 120V receptacle.
For your 20A circuit, as we crunched in the above example, you are fine with #12.
Ground can be combined if you have an appropriate place to fork the splice, but let's assume we don't.   Also, grounds can be bare, and if so, they are much smaller diameter. But you must enter this manually into the fill calculator as they don't have it pre-programmed.

3 x #12 wires
1 x #10 Cu or #8 AL wire
2 x #8 Cu or #6 AL wire.

Plug those into the conduit fill calculator and it will spit out the pipe size needed.  No DIYer ever ever got fired for buying extra-large conduit!   3/4" conduit will do this without doubt. You could squeeze it into 1/2" conduit with #8 and bare grounds.
Oh, one other thing. If you go with EMT metal conduit the ground wires can go away.  Now you have 2x#12 and 2x#8, fullstop.  Now you can get it done in 1/2" conduit (31% fill for #8 and 39% fill for #6).
Comment: WOW, thanks for the thorough answer, Harper. I thought I had most of it covered, but missed the 120v outlet for service to the outdoor unit.  Thanks for that.   I'll probably just add another hot to the 120 v circuit and turn it into a MWBC, of course properly connected to opposite poles with handle tied breakers for the service outlet.


PHP: Arabic characters as array keys

Question: I want to implement a simple Arabic to English transliteration. I have defined a mapping array like the following:
$mapping = array('ﺏ' => 'b', 'ﺕ' => 't', ...)

I expect the following code to convert an Arabic string to its corresponding transliteration
$str = "رضي الدين";
$strlen = mb_strlen( $str, "UTF-8" );
for( $i = 0; $i <= $strlen; $i++ ) {
    $char = mb_substr( $str, $i, 1, "UTF-8" );
    echo bin2hex($char); // 'd8b1' for ﺭ
    // echo $mapping["$char"];
}

But $char does not match the keys. How can this be solved?
The source code is loaded in UTF-8.
EDIT
When I do bin2hex() on each key of $mapping I get values different than that I get with corresponding $char. For example, for ﺭ I get efbaad and d8b1. They obviously don't match and they are not converted.
foreach ($mapping as $k => $v) {
    echo $k . ' ' . bin2hex($k) . '
'; // 'efbaad' for ﺭ
}

Only 'ي' gets same values and is converted.
I do not know what's the problem!
EDIT2
This chart actually shows that both of these codes refer to ﺭ
Answer: I suggest you to use preg engine since it natively works well with UTF-8. mb_* is not a bad choice, of cause, but I think it's just more complicated.
I've made a sample for your case:
$sData     = "رضي الدين";
$rgReplace = [
  'ﺏ' => 'b',
  'ﺕ' => 't',
  'ن' => 'n',
  'ي' => 'i',
  'د' => 'f',
  'ل' => 'l',
  'ا' => 'a',
  'ر' => 'r',
  'ي' => 'i',
  'ض' => 'g',
  ' ' => ' '
];
$sResult   = preg_replace_callback('/./u', function($sChar) use ($rgReplace)
{
   return $rgReplace[$sChar[0]];
}, $sData);
echo $sResult; //rgi alfin

as for your code - try to pass encoding directly (second parameter in mb_* functions)
Comment: @Affan my knowledge of arabic language are _very_ basic :)
Comment: Thanks! I think there is some other problem with my environment as your code outputs the same what I get from my code. Only `ي` matches and is converted to `i`
Answer: The problem is that you didn't specify the encoding to both mb_strlen() and mb_substr(); the following works okay:
$str = "رضي الدين";
$mapping = array('ﺏ' => 'b', 'ﺕ' => 't', 'ر' => c);
$strlen = mb_strlen( $str, "UTF-8" );
for( $i = 0; $i <= $strlen; $i++ ) {
    $char = mb_substr( $str, $i, 1 , "UTF-8");
    echo $mapping["$char"];
}

PHP: Arabic characters as array keys


How do I adjust the Clock Indicator format?

Question: Recently I upgraded to Ubuntu 11.04. The clock indicator on the panel is not following my regional settings format.
I edited locales and in all applications I have the right format of date and time except clock indicator on the panel. Tried dconfig editor but keys for clock applet cannot be changed. Tried to purge indicator and reinstall it - still the same. Is there any way that
I could change formatting of datetime indicator?

Here is format I'm using system wide: %A, %d %B %Y, %I:%M:%S
Here is format of datetime-indicator that pops up: %a%B%d %H:%M:%S
Answer: Try the following:
gsettings set com.canonical.indicator.datetime time-format "'custom'"
gsettings set com.canonical.indicator.datetime custom-time-format "'%A, %d %B %Y, %I:%M:%S'"

That seems to do the trick for me.  You should be able to do the same using dconf-editor.
In dconf editor, it'd be something like this:
Comment: this dconf setting no longer exists in 18.04
Comment: Yes I found this sollution before but that is not working for me. There is no such schema as com.cannonical.indicator.datetime in my system for some reason. The only thing about time formatting I found is in schemas.apps.clock_applet.prefs. But when I try to change format to custom and formatting to what I want the message pops up: "Keys cannot be modified at this time". When I created new key that can be edited then I got warning: "This key has no schema". And now I'm stuck.
Comment: Finally I got it to work. This is how it worked in my case. First alt+F2 and gksudo dconf-editor (before I was starting gconf-editor). Nothing showed up o the screen but I beleive it started in background. Then I opened terminal and used commands that James posted above (thanks). And voila I got my clock indicator where I wanted :-)))
Comment: You shouldn't have needed to use `sudo`.  The preferences are per-user.
Comment: For some reason without sudo it did not work. Later on I downloaded dconf-tools from repository. And now I can see all schemas and do not have to use sudo. Glitch??? Anyway thanks, it's working now.
Comment: thanks for dconf-editor!  My preference: %e %b %Y %I:%M
%e = day with no left zero. Result:
4 Dez 2016 08:25
Comment: How do you use `dconf-editor` to change "Mon Dec 18 18:41" to "Mon, 18 Dec 18:41"?


How to find a keyboard shortcut, globally: ctrl-shift-P

Question: I've been using Sublime for quite some time now and bringing up the palate with Ctrl+shift+P has always been my go to shortcut. All this in Ubuntu 13.10.
However, I recently lost the ability to use this anymore and had to change it to Q instead of P. Now, I tried looking for shortcuts and seeing if something is overriding it but can't seem to do so. Is there any way, other than uninstalling everything, to find this assignment?
If anyone knows of a program which uses Ctrl+shift+P as a shortcut, please let me know.
Comment: ctrl-shift-P seems to be "print to file" for various random applications, and defined somewhere unfindable in Gnome.  At least, I spent over an hour trying to find it withough success.
Answer: It seems to me you don't have to uninstall everything, just do not launch anything.

Just restart and close all the applications that started up with the system. Application global shortcuts won't work if the application is not running.
Hit Shift+Ctrl+p to be sure this is an application global shortcut and not a system shortcut
Then, launch one by one and check if the global shortcut occurs (by pressing the keys while not focusing the launched application in order to be sure the shortcut is global).


Python invalid list node cassandra cluster

Question: I have 2 dc and 3 node:
DC1: cas01.dc01.net(172.16.3.15) and cas02.dc01.net(172.16.3.16)
DC2: cas01.dc02.net(172.16.9.3) for example.
Run following script:
  cluster = Cluster(['cas01.dc01.net', 'cas02.dc01.net', 'cas01.dc02.net'],auth_provider=auth,protocol_version=3, load_balancing_policy=DCAwareRoundRobinPolicy(local_dc='DC1'))
session = cluster.connect('test')

print '_dc_live_hosts:'
for k, v in cluster.load_balancing_policy._dc_live_hosts.items():
    print "DC name: %s; Node address: %s" % (k, [node.address for node in v])

print 'Cluster metadata:'
for host in cluster.metadata.all_hosts():
    print 'Datacenter: %s; Host: %s; Rack: %s' % (host.datacenter, host.address, host.rack)

and receive response:
_dc_live_hosts:
DC name: DC1; Node address: ['cas01.dc01.net', 'cas01.dc02.net', 'cas02.dc01.net', '172.16.3.15']
DC name: DC2; Node address: ['172.16.9.3']
Cluster metadata:
Datacenter: None; Host: cas01.dc01.net; Rack: None
Datacenter: None; Host: cas01.dc02.net; Rack: None
Datacenter: DC1; Host: 172.16.3.15; Rack: Rack1
Datacenter: DC2; Host: 172.16.9.3; Rack: Rack1
Datacenter: DC1; Host: cas02.dc01.net; Rack: Rack1

Why duplicate nodes?
If you specify a list of IP address:
cluster = Cluster(['172.16.3.15', '172.16.3.16', '172.16.9.3'],auth_provider=auth,protocol_version=3, load_balancing_policy=DCAwareRoundRobinPolicy(local_dc='DC1'))
...

list of nodes is correct:
_dc_live_hosts:
DC name: DС1; Node address: ['172.16.3.16', '172.16.3.15']
DC name: DС2; Node address: ['172.16.9.3']
Cluster metadata:
Datacenter: DС1; Host: 172.16.3.16; Rack: Rack1
Datacenter: DС1; Host: 172.16.3.15; Rack: Rack1
Datacenter: DС2; Host: 172.16.9.3; Rack: Rack1

Please help.
Comment: What are your seeds ? What snitch do you use ? You can find the answers in your cassandra.yaml file. If it is a PropertyFileSnitch, can you include the content of your cassandra-topology.properties ?
Comment: Node cas01.dc01.net: - seeds: "cas01.dc01.net,cas02.dc01.net"         Node cas02.dc01.net: - seeds: "cas01.dc01.net,cas01.dc02.net"          Node cas01.dc02.net: - seeds: "cas01.dc02.net,cas01.dc01.net" endpoint_snitch: PropertyFileSnitch
topology:                                                           cas01.dc01.net=DC1:Rack1
cas02.dc01.net=DC1:Rack1
cas01.dc02.net=DC2:Rack1
Answer: A short description of how the driver works that will clarify your question:

the list of nodes that are passed in to the Cluster constructor are the initial contact nodes
The driver selects one of these to create a control connection. It's a good practice to pass more than 1 node so the driver can attempt different connections if one of the nodes is not accessible immediately.
using the control connection established at step 1, the driver retrieves information about the cluster topology from the system tables. It uses these details to populate the cluster metadata objects.
The information in the system tables (specifically peers table) reflects the configuration of each of your nodes (based on broadcast_address, rpc_address, etc.)
Answer: I am not sure this is the only problems but :

all nodes must have the same seeds
seeds list must include at least one node of each datacenter

Try this :
    - seeds : "172.16.3.16, 172.16.9.3"


If $V_c = \frac{321.8}{225.5}V_k$, and the equation is $V_k + V_c$, how do I get $V_k(1+\frac{321.8}{225.5})$?

Question: It takes Kim twice as long to run $2,255$ decimeters as it takes Cara to run $1/10$ of a mile. They start $1$ kilometer apart and begin running toward each other. How far, to the nearest meter, will Kim have run when they meet? Assume that $1$ mile = $1.61$ kilometers.
Comment: $V_k+V_c$ is not an equation.  Your title refers to partial results on the problem.  You should explain how they are linked.
Answer: Answering the question in the title, if you have
$$V_c=\frac {321.8}{225.5}V_k\\
V_c+V_k=\frac {321.8}{225.5}V_k+V_k=\left(\frac {321.8}{225.5}+1\right)V_k$$
by the distributive principle.


Log4j2 in async mode still blocks on java.util.concurrent.lock under heavy load

Question: I am trying to log in a low-latency environment.
2 high priority threads are calling log.error() in a tight loop (1Mmessages/s)
I want to use Async logging (with the disruptor) and to discard any excess messages. So the calling thread should NEVER block.
However, the jstack clearly shows it is blocking about 100 times/s.
Is it my configuration which is wrong ?
Or is the blocking inevitable if the buffer fill up ?
<code>java -Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
-Dlog4j2.AsyncQueueFullPolicy=Discard
-Dlog4j2.DiscardThreshold=Trace
-DAsyncLogger.RingBufferSize=2000000 TestLog

"TT0" #14 prio=5 os_prio=0 tid=0x00007fe8cc690800 nid=0x2463 runnable [0x00007fe8ae70d000]
   java.lang.Thread.State: RUNNABLE
        at sun.misc.Unsafe.unpark(Native Method)
        at java.util.concurrent.locks.LockSupport.unpark(LockSupport.java:141)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer.unparkSuccessor(AbstractQueuedSynchronizer.java:662)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer.release(AbstractQueuedSynchronizer.java:1264)
        at java.util.concurrent.locks.ReentrantLock.unlock(ReentrantLock.java:457)
        at com.lmax.disruptor.BlockingWaitStrategy.signalAllWhenBlocking(BlockingWaitStrategy.java:72)
        at com.lmax.disruptor.MultiProducerSequencer.publish(MultiProducerSequencer.java:218)
        at com.lmax.disruptor.RingBuffer.translateAndPublish(RingBuffer.java:934)
        at com.lmax.disruptor.RingBuffer.publishEvent(RingBuffer.java:444)
        at com.lmax.disruptor.dsl.Disruptor.publishEvent(Disruptor.java:245)
        at org.apache.logging.log4j.core.async.AsyncLogger.logMessage(AsyncLogger.java:285)
        at org.apache.logging.log4j.spi.AbstractLogger.logMessage(AbstractLogger.java:727)
        at org.apache.logging.log4j.spi.AbstractLogger.logIfEnabled(AbstractLogger.java:716)
        at org.apache.logging.log4j.spi.AbstractLogger.debug(AbstractLogger.java:232)
        at TestLog$WriteToFile.run(TestLog.java:53)
        at java.lang.Thread.run(Thread.java:745)

"AsyncLogger-1" #12 daemon prio=5 os_prio=0 tid=0x00007fe8cc96f800 nid=0x2460 waiting on condition [0x00007fe8b4187000]
   java.lang.Thread.State: WAITING (parking)
        at sun.misc.Unsafe.park(Native Method)
        - parking to wait for  <0x00000007104a0f28> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
        at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
        at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
        at com.lmax.disruptor.BlockingWaitStrategy.waitFor(BlockingWaitStrategy.java:45)
        at com.lmax.disruptor.ProcessingSequenceBarrier.waitFor(ProcessingSequenceBarrier.java:55)
        at com.lmax.disruptor.BatchEventProcessor.run(BatchEventProcessor.java:123)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:745)
</code>
Comment: I am showing the stack trace of 1 writer and the log4j2 thread
Answer: The LMAX Disruptor allows you to choose what the background thread should do when it's waiting for work to arrive.
By default Log4j2 uses the BlockingWaitStrategy. This gives the behavior you are seeing, which is appropriate for most situations but perhaps not in ultra low latency use cases.
If you can dedicate a core to the background thread you can use the BusySpin wait strategy.
See https://github.com/apache/logging-log4j2/blob/master/log4j-core/src/main/java/org/apache/logging/log4j/core/async/DisruptorUtil.java
Comment: I am concerned about the "TT0" which is the main application thread.
It appears to be accesing a SYNCHONIZE data structure, which i find suprising. If every time i do a jstack i see it, then i guess it is spending a lot of time there.
Comment: Yes this will also go away if you use the BusyWait strategy. Currently the application thread needs to take a lock to notify the background thread that it should wake up because work has arrived.
Comment: Great. This makes sense.


Scroll to Section

Question: I have the following code, my question is how would I go about adding to this so that when a user clicks on a link a scroll to is added so that it takes them to the class .instructors section
<?php if($hasSections): ?>

                        <?php foreach ($sections as $section): ?>
                            <a href="#section<?php echo $section['id']; ?>">

                                    <img src="<?php echo $section['image']['url']; ?>" />

<?php echo $section['title']; ?>

                        <?php endforeach; ?>

                        <?php foreach ($sections as $section): ?>

                            <section id="section<?php echo $section['id']; ?>">

<?php echo $section['title']; ?>

                                    <?php echo $section['content']; ?>

                        <?php endforeach; ?>

                <?php endif; ?>

The idea is that when a user clicks on a link the text changes and the page scrolls down to the text.
Comment: Do you have a fiddle or example we can see ? It's hard to understand how you're organizing your html.
Comment: I have edited the above
Answer: this should animate a scroll to the '.instructors section'
 function changeSection(sectionID) {
        $sections.stop(true).hide(); //Stop animating and hide all sections
        $sections.filter('#' + sectionID).stop(true).fadeIn(); //Display the section with the same ID as the section link that was clicked

        $sectionLinks.removeClass('selected'); //Remove the selected class from all section link  tags
        $sectionLinks.filter('[href="#' + sectionID + '"]').addClass('selected'); //Add the "selected" class to the section link that was clicked

        $('html, body').animate({
            scrollTop: $sections.offset().top
        }, 2000);

  }

Comment: Thanks Ran, this scrolls down to the text on entering the page but what I should have explained is that when a link is clicked the text inside the instructors section changes so every time a link is clicked the page should scroll down.
Comment: Oh i see! we have created a bug, it happends because we call this function on the page load, put the new code i have added to you remove it from the changeSection function and put it in youre click handler   - (  $sectionLinks.click(function(e) ) - this should do the trick, good luck!
Answer: I have created a "helper" function in JS about scroll
function goToByScroll (id) {
    // Reove "link" from the ID
    id = id.replace("link", "");
    // Scroll
    $('html,body').animate({
        scrollTop: $("#" + id).offset().top
    },
        'slow');
}

you should pass the id and will work.
goToByScroll('section1');

Should locate the window in this id
Comment: Hi - I am not sure where all this goes?

Scroll to Section


How to construct a dynamic String in Java?

Question: I am trying to do something in my Application but I am stuck & unable to find a way forward. Here is my problem:-
I want to create Oracle Queries programatically. 2 such queries for e.g. are DROP TABLE tableName & ALTER TABLE tableName PRIMARY KEY (col1, col2, col3....);
In my class i have created these 2 final static Strings :-
private static final String DROP_TABLE = "DROP TABLE %1$s";

createDropStmt() {
    System.out.format(DROP_TABLE, tableName);
}

As you can see, this approach will work fine with DROP statements but not with PK's beacuse I don't know how may columns are going to be there till runtime. (private static final String PRIMARY_KEY = "ALTER TABLE %1$s PRIMARY KEY {don't know what to put here}"`)
So, my question is how to do this kind of thing for PK so that my template string can dynamically take values & construct the query.? Does Java have a clean way to do it or my approach should be different?
Thanks
Comment: How will the DDL statement exactly look like for the primary key case? I just need a little more info to imagine what values are used in your case.
Comment: DDL statement for PK will look like this :-ALTER TABLE orders ADD PRIMARY KEY (ORDER_ID, ITEM_NO, ITEM NAME);
Comment: Thanks, I oversaw that you already mentioned sth. like that in your question.
Answer: If you have multiple primary key columns then you have to join their names with commas. The java.util.Formatter doesn't offer a way to concatenate arrays or lists of values. You have to do that for yourself.
When you don't want to write your own joiner, you could use the Joiner from the Guava libraries like this:
Joiner.on(",").join(primaryKeyColumns);

and then insert this into the ALTER TABLE statement.
Comment: Commons Lang also has StringUtils.join
Answer: Have a look at PreparedStatement.
There are also some frameworks around that simplify sql usage in Java (http://www.jooq.org/ as one random example).
I really would not use String concatenation for query-construction. Its in the OWASP top 10 (sql injection).
Comment: I don't want to execute the query. I just want to put those created queries in a file.
Comment: a) You cannot use bind variables for table names.  b) You'd still have the same problem with the flexible number of parameters (for that primary key case).
Comment: sorry I got Your question wrong. Something like Apache Velocity might bring in some flexibility to create actual string from a parametrized snippet.


Change image with MouseOver

Question: I'm new to javascript and Html , Typed a code that changes the image when the mouse hovers over, it works but i was wondering if there is any better solution because it is very long and repetitive ;
Here is the code :
<doctype html>

Answer: Simple answer is :

Answer: You want to make one function and give them an argument as to which image to display. Something like this:
function rollover(img, src) {
   img.src = src
}

Then call the same function on over and out:

This is even easier if you load a library such as jquery. Here's an example using it. You don't even have to have the events repeated. Just give each image a class

Then assign events using the class name (classes are identified by the leading .)
$(document).ready( function() {
     $('.rollover').mouseover( function(e) {
         this.old_src = this.src; // remember what the old src was
         this.src = 'image1.jpg';
     });
     $('.rollover').mouseout( function(e) {
         this.src = this.old_src;
     });
});

You wrap it in $(document).ready(...) to ensure the page has loaded before the events are attached.
Comment: For this method, he may need to import JQuery, but he is "new to javascript and Html" . Please mention that too.
Answer: All the above answers are good. I just want to add you could also use data-* attributes.

In JS:
function rollover(img)
{

     img.src = this.dataset.hoverImg;

 }
function mouseaway(img)
{

   img.src = this.dataset.normalImg;

}

Answer: You could store all the information required in each image tag, that way you wouldn't have to create extra functions for each one.
For example

document.addEventListener('DOMContentLoaded', () => {
  Array.from(document.querySelectorAll('img[data-src-enter]')).forEach(img => {
    img.setAttribute('data-src-out', img.src)
    img.addEventListener('mouseenter', () => {
      img.src = img.getAttribute('data-src-enter')
    }, false)
    img.addEventListener('mouseout', () => {
      img.src = img.getAttribute('data-src-out')
    }, false)
  })
})

Change image with MouseOver


PYTHON3 python my interpreter inform to me that has numpy but when I execute my entire code print wrong message

Question: >>> import numpy
>>> numpy.std(arr)
1.4142135623730951
>>>

my interpreter print correct answer
but my entire code
import numpy

def addarr(N,K,score):
    arr=[]
    a=10000
    this = int(N)-int(K)+1

    for j in range(0,this):
        for i in range(j,j+int(K)):
            arr.append(score[i])
            print(i)
        print("asdfasdfasdfasfasdf")
        print(arr)
        b = numpy.std(arr)

        if a>b:
            a=b
    return a

if __name__ == "__main__":
    NandK = input()
    N, K = NandK.split()

    string = input()
    score =[]
    score = string.split()
    print(score)

    print(len(score))
    answer = addarr(N,K,score)
    print(answer)

My entire code print wrong message about numpy
   b = numpy.std(arr)
['1', '2', '3']
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line 3242, in std
    **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/_methods.py", line 140, in _std
    keepdims=keepdims)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/numpy/core/_methods.py", line 107, in _var
    arrmean = umr_sum(arr, axis, dtype, keepdims=True)
TypeError: cannot perform reduce with flexible type

how can I fix it..
I already install "numpy" with pip3
I using the python3 and my version is 3.7
I have been try import numpy as np but It isnt working too.
It is my INPUT
5 3
1 2 3 4 5

Comment: Python 3.7 is still pretty new. How certain are you that your libraries are compatible with Python 3.7? I'm still on Python 3.6 myself.
Comment: Can you provide both input you are passing to reproduce the issue?
Comment: /prac  python3
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43)
Comment: I input "5 3 \n 1 2 3 4 5"
Comment: Try by casting your var first. ```N = int(N) and K = int(K)``` inside addarr method
Comment: sure I alread it ..
Answer: There are two ways to solve it.
One is change arr.append(score[i])  to  arr.append(int(score[i])).
Another is to uncomment this line # arr=[int(x) for x in arr] in the following code.
import numpy

def addarr(N,K,score):
    arr=[]
    a=10000
    this = int(N)-int(K)+1

    for j in range(0,this):
        for i in range(j,j+int(K)):
            arr.append(int(score[i]))
            print(i)
        print("asdfasdfasdfasfasdf")
        print(arr)
        # The next line can trun ['1', '2', '3'] to [1,2,3]
        # arr=[int(x) for x in arr]
        b = numpy.std(arr)
        print('b=',b)
        if a>b:
            a=b
    return a

if __name__ == "__main__":
    NandK = input()
    N, K = NandK.split()

    string = input()
    score =[]
    score = string.split()
    print(score)

    print(len(score))
    answer = addarr(N,K,score)
    print(answer)


Can't create a delta lake table in hive

Question: I'm trying to create a delta lake table in hive 3.
I moved the delta-hive-assembly_2.11-0.3.0.jar to the hive aux directory and set into the hive cli
SET hive.input.format=io.delta.hive.HiveInputFormat;
SET hive.tez.input.format=io.delta.hive.HiveInputFormat;

but when I try to create the table it throws the following error:
[2b8497c1-b4d3-492e-80a5-ec4db4119018 HiveServer2-Handler-Pool: Thread-133]: Exception occured while getting the URI from storage handler: Expected authority at index 22: deltastoragehandler://: Unsupported ex
java.net.URISyntaxException: Expected authority at index 22: deltastoragehandler://: Unsupported ex
    at org.apache.hadoop.hive.ql.metadata.DefaultStorageHandler.getURIForAuth(DefaultStorageHandler.java:76) ~[hive-exec-3.1.3000.7.1.7.0-551.jar:3.1.3000.7.1.7.0-551]
    at org.apache.hadoop.hive.ql.security.authorization.command.CommandAuthorizerV2.addHivePrivObject(CommandAuthorizerV2.java:210) [hive-exec-3.1.3000.7.1.7.0-551.jar:3.1.3000.7.1.7.0-551]

The create statement:
CREATE EXTERNAL TABLE default.test_delta
( id INT, activ INT)
STORED BY 'io.delta.hive.DeltaStorageHandler'
LOCATION '/dev/delta/tessttt';

It's anyone that know why this error occurs ?
Comment: I am trying to create a delta table in hive 3 using the query mentioned in the accepted answer. I have a question on what should be specified in the location? Is it any path on the hdfs? does it have to be a path to an already existing delta table?
Answer: You need to add in the properties of the table the following: TBLPROPERTIES('DO_NOT_UPDATE_STATS'='true');
Example
CREATE EXTERNAL TABLE default.test_delta
( id INT, activ INT)
STORED BY 'io.delta.hive.DeltaStorageHandler'
LOCATION '/dev/delta/tessttt'
TBLPROPERTIES('DO_NOT_UPDATE_STATS'='true';

The solution also works for iceberg format.
Inspired by: https://github.com/delta-io/connectors/issues/279
Comment: I am trying to create a delta table in hive 3 using the query mentioned in the accepted answer. I have a question on what should be specified in the location? Is it any path on the hdfs? does it have to be a path to an already existing delta table?

Can't create a delta lake table in hive