Should a informational box for a wide form be centered, left or right aligned?

Question: I am working on updating the layout and styles of our existing application.  At the top of a very wide table that has lots of checkboxes and fields is a information box.  We need to explain some basic information to the user.
The original information box is centered and 600px wide.  It has a comfortable amount of text per line.  However it looks very out of place compared to the rest of the design, I would rather it be anchored to the side or the whole width of the table.
The following image has the three possible layouts I am contemplating.

The first seems like too many words for each line.  The second and third seem better. If someone has links to how other sites successfully execute instruction sections on the top of very wide forms would be the best resource for me.
Comment: I also thought maybe have the instructional box be as wide as the form, but have padding on the sides of the text to make it readable.
Comment: Your second thoughts should answer your question perfectly, I am sure.
Answer: The most readable box will be the one aligned to the left and taking up no more than half of the width.
The text needs to be aligned to the left because you're working with a table in a left-to-right language. People don't read tables completely - they scan them for the records they need, which is similar to the way people "read" web content: the F-shape. Since you want users to read the instructions, you'll have to present information in the layout most comfortable to them. (If you want to adapt the layout to a right-to-left language, you'll have to change the alignment accordingly.)
When your text takes up the entire 1200px across (I realize the actual text a bit less wide to account for padding), it's too wide to be read comfortably. On my 15.6" diagonal screen with 1920×1080px resolution, such a text box will measure about 8.5" (~21.6cm) wide. When you go to a lower resolution or greater diagonal screen size, that distance is going to increase.
The optimal width of a column, according to this answer on UX.SE is between 40 and 75 characters depending on the font size.
Comment: Interesting,I would have assumed that people read in a z shaped pattern,thanks for the link about the F-shape
Comment: Z-shape applies to books. In a table, like on a web-page containing extra info, people are going to follow the F-shape.
Comment: I am wanting to have some sort of set width for each of these boxes.  There will be many instances and I don't want them to sized randomly due to text size but follow some sort of pattern.  This application is not using the grid system either.
Comment: @EricH: When I said that the optimal width is 40-75 characters, I didn't mean the box should be of a random size in that range. Sorry, if that's how it came off. Obviously, you need to size it to keep it in balance with the surrounding elements.
Comment: @dnbrv: it may even be advisable to keep the box the same width as the table, keeping the box and the table visually "connected". Drawback could be that it may look peculiar to have a very wide box with narrow text.
Comment: F-shape is for web pages. This box is for an application and "basic information", not for google:s top results.
Comment: @JOG: The "basic instructions" are for a table and those are consumed like webpages: by scanning the content.
Comment: @MarjanVenema: Yes, that's a good point. Though I'm concerned with the standard viewport being 1200px-wide in general. Desktop applications must be "responsive" by default.
Comment: @dnbrv: Aha thx, I missed that this actually was for a web page. Still, since the application is unknown and the purpose of the box is quite unclear, I would not necessarily treat the info box as a google top result. :)
Comment: @JOG: It's for a desktop app but the text precedes a table. Tables are laid out (and thus consumed) similarly to web pages. Hence, the F-shape applies.
Answer: Does the user really have to see this box every day?
You wrote that it is for "basic information". How much focus do you want to put on this small box with basic information? The F-shape reading pattern mentioned in another answer might be unrelated. It is more concerned about how human eyes scan a page, and less about where to place information or provide help text in any given application. How you should layout your info box is totally dependent on its content and purpose.
Is this basic information worthy the prime spot of your application?
Is the info box context sensitive, and changing on user actions? Consider if maybe just a small mouse over pop up could be enough? Or putting it somewhere else completely, like in a corner or collapsed behind a help button.
Back to your design, if needed, your first instinct seems good to me. Not too wide to read, and centred to look pretty. You wrote:

The original information box is centered and 600px wide. It has a comfortable amount of text per line. However it looks very out of place

Maybe a designer can help you to make that original solution look more in place? These sketches are ugly, but just to show how I am thinking:

Good luck! :)
Comment: Good point re: necessity.
Comment: I value your input and yes this application needs to display this information everytime.  The users tend to not be experts in any application and need to be reminded everytime. Also it maintains accountability for the user.  If the user made a mistake the application owner does not have to do work overtime to fix issues due the error being there "fault"
Comment: I am thinking about how to make the message more context sensitive and less just a message at the top, but it does not seem obvious at first.
Comment: If there is a save button, you could pop at its press. And later even add logic for when it needs to pop or not. But I guess that's another question. :)
Answer: I am in favor of the first option primarily because your user will read from left to right and back and the in a zig-zag manner and once he has finished reading his eyes would follow the natural path back to the start of the text box.However in the case of the right aligned,the user has to scan all the way to the right,read the text and then scan to the start of the box.
I also prefer the longer approach because you want them to get to the form quickly in one continuous flow and the more lines you have(due to the shorter length) ,the longer it will take
Answer: Regarding readability, your text should not have more than 50 characters per line, with standard font size of 16px and line height of 1.45. You can experiment by yourself to see that.
It can be floating with little arrow pointing to exact row. Otherwise I would go with positioning it left.


how to make partitions before installation?

Question: my laptop is having 320GB hard disk. I want partition it with

195 GB as one part(here i want install os),
4GB for swap
70GB as one partition,
50 GB as one partition.

I'm new to do this partition setup. Can anyone please tell me how to do it simply and give me step by step procedure?
Comment: 13.04 is not supported - please do not install an unsupported operating system.
Answer: Please see How to Partition. This will detail everything you need to know. It is a complicated topic, so please review the referenced help article to fill the gaps in your knowledge before proceeding. Ask a new question if you have more specific questions.


Getting Pixel Values "Under" Current Window

Question: I'm trying to make, essentially, a screen capture program, that captures the pixel values under the current window. (I'm working in C#, in Visual Studio 2015.) However, for various reasons, the window itself needs to be opaque (for filters and such). How can I best achieve this?
Comment: I belive it is not possible.
Answer: It is possible to find the window below yours and get a screenshot of it even if it is hidden with the method: PrintWindow (see PInvoke.net as well)
See Copying content from a hidden or clipped window in XP?
Answer: It is very simple to do in Winforms.  Just set the form's Opacity value to 99%.  Now Graphics.CopyFromScreen() will not see your window anymore.
Except when the window underneath yours is also a layered window, then it also won't be visible to CopyFromScreen() for the same reason.  Then you have to set Opacity to 0, copy and set it back to 0.99.  Very quick, probably good enough for what you want to do.


Makeshift Junction Box Cover

Question: I'm about to cover up some junction boxes in my ceiling, they need a cover and I got the wrong size at the store.
I have some metal flashing laying around from working on my roof would this be safe to use if I cut it to size and screw it on?
Comment: Electrical boxes, enclosures, covers, etc. must be "listed" for the purpose, yes?
Comment: Why can't you just go back to the store?
Comment: Yeah -- this would be a good time to take advantage of whatever return policy the store provides, too
Comment: I can, it's just a 45 minute drive from me.
Comment: Only use metal to cover your junction box if the box is metal too.
Answer: Don't knock yourself out making a special trip, but do go get correct, listed box covers eventually when you get a chance.  Homebrew covers are not legal.     Most of the covers I use are on the order of a dollar, so I don't worry too much about keeping a few in stock.

Makeshift Junction Box Cover


Converting Trac Wiki into Sphinx project

Question: Is there tool support for the conversion of Trac Wiki pages into reStructuredText or Sphinx pages?
There is a tool for the conversion of Trac to MediaWiki and this works quite well.
Thus, a conversion from MediaWiki to <code>.rst</code> would be nice as well.
Answer: After consulting with some friends, I found out that pandoc can convert MediaWiki to reStructuredText.


typedef struct and enum, why?

Question:
Possible Duplicates:
Purpose of struct, typedef struct, in C++
typedef struct vs struct definitions

In code that I am maintaining I often see the following:
typedef enum { blah, blah } Foo;
typedef struct { blah blah } Bar;

Instead of:
enum Foo { blah, blah };
struct Bar { blah blah };

I always use the latter, and this is the first time I am seeing the former. So the question is why would one use one style over the other. Any benefits? Also are they functionally identical? I believe they are but am not 100% sure.
Answer: In C++ this doesn't matter.
In C, structs, enums, and unions were in a different "namespace", meaning that their names could conflict with variable names. If you say
struct S { };

So you could say something like
struct S S;

and that would mean that struct S is the data type, and S is the variable name. You couldn't say
S myStruct;

in C if S was a struct (and not a type name), so people just used typedef to avoid saying struct all the time.
Comment: `enum`, `union`, and `struct` have the same issue.
Comment: Yea, I re-read your answer and realized that and then deleted my comment. Oops. Thanks!
Comment: @anio: Haha okay, no problem.
Answer: They are for C compatability. A normal
  struct Bar { blah, blah };

doesn't work the same with C;

typedef struct and enum, why?


Making bootable Ubuntu USBstick: fat32 or vfat?

Question: I am trying to make a bootable USB stick, for an Ubuntu workstation,
on an Ubuntu laptop.
All goes well until I actually try to make the bootable stick.
(Startup Disk Creator). Then (soon) it says "input - out put error"
and stops.
The USB stick is vfat. Can that be the problem? Should it be
fat16 or fat32 ?  Is that worth trying, or is it likely to be
something else?  Many Thanks.
Comment: Did you check the ISOs MD5 sum?
Comment: Do you want to install from it, or run it later?
Answer: Give it a try! I consider Fat32 the best filesystem for Live USBs.
Install GParted (disk manager) running this command in a terminal (Ctrl+Alt+T):
sudo apt-get install gparted

Insert your USB stick. Backup its content. Open nautilus and unmount it.
Then run GParted from a terminal with the command
sudo gparted

Click the tab GParted > Devices and choose your USB stick.
Right click the USB stick "strip" (probably named /dev/sdb or sdc) and click Format to > Fat32. Apply your actions with that green "V" below the "Device" tab.
Then make the process with Startup Disk Creator again. Things should be fine.


Consolidate click handlers with two attributes

Question: I have a function that takes one argument:
function magic(el){
 ...
}

I have a bunch of click handlers on mixed elements/classes calling function:
$('#div1').click(function(){ magic('#other-div'); });
$('.crazy-div').click(function(){ magic('.mystery-div'); });
$('#doomed-divv').click(function(){ magic('#shady-div'); });
$('#secret-div').click(function(){ magic('form'); });
$('#div2').click(function(){ magic('p'); });
...

Is there a nice way to consolidate these down? Perhaps with an associative array?
Comment: There are no associative arrays, but an object with an iteration over keys as elements and values as parameters to the magic function would do it.
Answer: It's enough to create an object containing a key-value asignment (what ID to be passed as an argument when a specific ID is clicked) and then use $.each to iterate through the keys and asign a click function for each of them.
var a = {
   '#div1' : '#other-div',
   '#doomed-divv' : '#shady-div'
};
$.each(a,function(key,value){
    $(key).click(function(){
        magic(value);
    });
});

JSfiddle.


Powershell Exchange Module remote mailbox issue

Question: I have created a scripts that automatically creates a user in Exchange and than adds a license to it from o365 however i need the box at the bottom where it says "automatically update email addresses based on the email address policy applied to this recipient" to automatically be checked off when the account is created.

Here is the main component that create the remote mail box:
New-RemoteMailBox -Alias $identAlias -Name $name -FirstName $return[0] -LastName $return[1] -UserPrincipalName $eAddress  -Password (ConvertTo-SecureString -String 'xxxxxxx' -AsPlainText -Force) -ResetPasswordOnNextLogon $true

Please help!
Comment: Have you tried [get-mailbox](http://exchangeserverpro.com/manually-configuring-email-addresses-for-exchange-server-2013-recipients-using-powershell/) then change the property manually then get mailbox again and compare properties
Comment: No. I can't figure out which parameter controls that
Answer: To apply to all users
Get-mailbox | Set-mailbox -EmailAddressPolicyEnabled $true

and to restrict by domain
Get-mailbox | Where {$_.EmailAddresses -like '*@domain.com'} |
 Set-mailbox -EmailAddressPolicyEnabled $true

and remotely
Get-mailbox | Where {$_.EmailAddresses -like '*@domain.com'} |
Set-RemoteMailbox EmailAddressPolicyEnabled

Comment: Can this be used with set-remotemailbox instead of just set-mailbox?
Comment: Initial check, [yes it can](https://technet.microsoft.com/en-us/library/ff607302%28v=exchg.150%29.aspx). Existing mailbox will require [enable](https://technet.microsoft.com/en-us/library/ff607313%28v=exchg.150%29.aspx)
Comment: im sorry im a little confused what you mean by enable. could you possibly give me an example?
Comment: an example is in the link : Enable-RemoteMailbox "Kim Akers"


how to properly merge these 2 query into one update?

Question: This currently work but I would like to change the update statement to include the action of the insert below it, is it posssible?
<code>UPDATE cas
    SET [Locked] = CASE WHEN cas.Locked <> @TargetState AND cas.LastChanged = filter.SourceDateTime THEN @TargetState ELSE cas.[Locked] end,
    OUTPUT inserted.Id, inserted.Locked, CASE WHEN inserted.Locked = @TargetState AND
                                                   inserted.LastChanged = filter.SourceDateTime THEN 1
                                              WHEN inserted.LastChanged <> filter.SourceDateTime THEN -1 -- out of sync
                                              WHEN deleted.Locked = @TargetState THEN -2 -- was not in a good state
                                              ELSE 0 END --generic failure
    INTO @OUTPUT
    FROM dbo.Target cas WITH(READPAST, UPDLOCK, ROWLOCK) INNER JOIN  @table filter ON cas.Id = filter.Id

INSERT INTO @OUTPUT
SELECT filter.id, NULL, when cas.id is not null -3 --  row was/is locked
                                           else -4 end --not found
FROM  @table filter left join dbo.target cas with(nolock) on filter.id = cas.id
WHERE NOT EXISTS (SELECT 1 FROM @OUTPUT result WHERE filter.id = result.UpdatedId)
</code>
Comment: Yes, it is possible. It is called [`MERGE`](https://msdn.microsoft.com/en-us/library/bb510625.aspx).
Comment: I don't see how @Fredou gets what he wants with a `MERGE` statement.
Comment: @lad2025 i'm currently looking at merge and i'm not yet sure how to do it with table hints and pickup the row that was locked and not found, currently i'm only doing one generic check for both
Answer: I do not think what you want is possible.

You start with a table to be updated. Let's say this table contains a set of IDs, say, 1 to 6
You join onto a temp table containing a different set of IDs that may partially overlap (say, 4 to 9)
You issue the update using an inner join. Only rows 4 to 6 are updated
The output clause picks up data only for modified rows, so you only get data for rows 4 to 6
If you flipped this to an outer join (such that all temp table rows are selected), you still only update rows 4 to 6, and the output clause still only kicks out data for rows 4 to 6

So, no, I see no way of achieving this goal in a single SQL statement.
Comment: that is exactly the behavior i saw when i tried it with a update with different type of join, i'm currently looking at merge and not sure, like you said, if it's possible.


How to convert lists to a dataframe using a reference dataframe as a map?

Question: So, I have this dataframe which has three columns that I am trying to use as a map to link three different lists into a (source-target) 2 columned dataframe.
Here is the 3-columned mapping dataframe that I am using as reference:
COLOR   PATTERN     DAY
red     chequered   monday
blue    dots        monday
-       cross       monday
magenta leaves      thursday
yellow  -           friday
-       custom      saturday
red     leaves      friday
-       chequered   wednesday
blue    cross       sunday
green   -           sunday
red     cross       tuesday
yellow  dots        -
yellow  stripes     -
magenta custom      -

Example input
color=['blue', 'red', 'yellow']
patter=['stripes', 'custom']
weekday=['sunday', 'tuesday', 'monday', 'friday']

Desired output
blue    monday
blue    sunday
red     monday
red     tuesday
red     friday
yellow  stripes
yellow  friday

How should I go about it?
Comment: Are your list items variables or strings?
Comment: The list items are strings, yes.
Answer: color=['blue', 'red', 'yellow']
patter=['stripes', 'custom']
weekday=['sunday', 'tuesday', 'monday', 'friday']

# boolean indexing
new = df[(df['COLOR'].isin(color) & df['DAY'].isin(weekday)) | (df['COLOR'].isin(color) & df['PATTERN'].isin(patter))]

# new conditions
cond = [
    new['DAY'] != '-',
]
# your choice list
choice = [
    [new['COLOR'].values.tolist(), new['DAY'].values.tolist()]
]

# numpy.select to create list
data = np.select(cond, choice, [new['COLOR'].values.tolist(), new['PATTERN'].values.tolist()])

# create new dataframe and transpose
final_df = pd.DataFrame(data).T

        0        1
0     red   monday
1    blue   monday
2  yellow   friday
3     red   friday
4    blue   sunday
5     red  tuesday
6  yellow  stripes


How do I put values from a file into a string and calculate the values in Java?

Question: I have a .csv file and I understand how to read it in Java, my problem is I want to be able to put the values of what is inside the file into a string and then read the string so I can calculate these values.

Alice Jones,80,90,100,95,75,85,90,100,90,92 Bob
  Manfred,98,89,87,89,9,98,7,89,98,78

Those are the values, now how could I add up all the integers next to each name and create an average? MY biggest problem was when I read the file it was in a While loop and then was able to print out the lines just as it looks above into the console but when I wanted to print the values outside of the While loop it said the string doesn't exist so therefore I can't calculate the values if there is nothing in it.
 import java.io.*;
 import java.util.*;

 public class Grades {
public static void main(String args[]) throws IOException
 {
 try{
 // Open the file that is the first
 // command line parameter
 FileInputStream fstream = new FileInputStream("filescores.csv");

 BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
 String strLine;
 //Read File Line By Line
 while ((strLine = br.readLine()) != null)   {
 // Print the content on the console
 String line = strLine
 System.out.println (strLine);
 }
 //Close the input stream
 in.close();
 }catch (Exception e){//Catch exception if any
 System.err.println("Error: " + e.getMessage());

 }
 }
 }

Comment: Show us that code. Probably your are facing problem with scope of variable.
Comment: You want to keep a reference to the values you visit while iterating through your `while` loop. You'll then have access to them so you can sum them or whatever.
Comment: Split on commas, iterate over the results (skipping the first), convert to a number, and add them.
Comment: Please don't use DataInputStream to read text. It is redundant and confusing. Please remove it from your example as this bad code gets copied a lot.
Answer: I would suggest to implement a plain old java object (POJO) and store the data there:
public class MyRow {
    public final String name;
    public final int[] values;

    public MyRow(String name, int[] values) {
        this.name=name;
        this.values=values;
    }
}

And split your string and put it in a simple List<MyRow>:
MyRow splitData(String line) {
    String[] parts=line.split(" ");
    int[] vals=new int[parts.length];
    // starting with one for skipping the name
    for(int i=1; i<parts.length; i++) {
        vals[i-1]=Integer.parse(parts[i]);
    }
    return new MyRow(parts[0], vals);
}

So basically your read loop will look like this:
List<MyRow> data = new ArrayList<MyRow>();
while((strLine = br.readLine()) != null) {
    // Print the content on the console
    System.out.println (strLine);
    data.add(splitData(strLine));
}

Now all the data are in the data List.
Answer:
when I wanted to print the values outside of the While loop it said
the string doesn't exist

As I commented you have scope issue in your code. However I dont see anything outside of while loop that your are printing or doing anything. You can use following code snippet to print the line outside of while loop.
ArrayList<String> lines = new ArrayList<String>();// Updated <String>

 while ((strLine = br.readLine()) != null)   {
   // Print the content on the console
   lines.add(strLine);
   System.out.println(strLine);
 }

for(int i = 0; i < lines.size(); i++){
 System.out.println(lines.get(i));
}

Variable Scope
EDIT for comment

Note: Grades.java uses unchecked or unsafe operations.
Note: recompile with -Xlint: unchecked for details.

The above are just warning given by compiler to make you aware about unsafe collection use.
See here for more details.
Comment: I used the code you gave me and I'm still receiving an error. This is what I got this time.  Note: Grades.java uses unchecked or unsafe operations.      Note: recompile with -Xlint: unchecked for details.
Comment: @TomManolakis I updated the answer. And that not error, just a warning. [See here](http://stackoverflow.com/questions/197986/what-causes-javac-to-issue-the-uses-unchecked-or-unsafe-operations-warning). You also have to add  `import java.util.ArrayList;` above the class.


Pandas cut method excludes lower bound

Question: I am trying to bin a dataframe column that contains ages in the range 0 to 100.
When I try and use a bin to include the zero ages it does not work.
Here is an demo using a list with the range of my data:
pd.cut(pd.Series(range(101)), [0, 24, 49, 74, 100])

The zero value in the range returns NaN from the cut.
Any way around this?
Answer: IIUC you need to set include_lowest argument to True. From docs:

include_lowest : bool
    Whether the first interval should be left-inclusive or not.

For your case:
pd.cut(pd.Series(range(101)), [0,24,49,74,100], include_lowest=True)

In [148]: pd.cut(pd.Series(range(101)), [0,24,49,74,100], include_lowest=True).head(10)
Out[148]:
0    [0, 24]
1    [0, 24]
2    [0, 24]
3    [0, 24]
4    [0, 24]
5    [0, 24]
6    [0, 24]
7    [0, 24]
8    [0, 24]
9    [0, 24]
dtype: category
Categories (4, object): [[0, 24] < (24, 49] < (49, 74] < (74, 100]]

Comment: Why is `include_lowest=True` not the default value?
Comment: I really should have read the docs on that one. Anyway, thanks.
Comment: I was looking for this as well. I saw the `right` argument and looked for `left` but missed `include_lowest`.

Pandas cut method excludes lower bound


Would powerline networking be suitable for Steam link?

Question: Some weeks ago I was interested in purchasing a steam-link module, I was curious how they planed to transfer the pre-calculated data to my living room without notable performance loss (delay).
After a bit of digging I figured out they advise to avoid using wireless LAN. What lets me assume now, steam link lets my machine calculate the data and then induces it to send the calculated data over the network to the Steam link so it can screen it on the TV. This conformed with my fear and the given warning of the system shouldn't be run on a wireless LAN, since the latency of the data exchange would be horrible and for most games not playable.
If I would like to place Wire through my living room down the stairs to the routing point, I would just place my PC in the living room plugging the wire to the PC and just connect the PC to my TV... No need for the Steam link at all. So it was an closed topic for me.
Today I stumbled on Amazon on a Powerline Network adaptor, and I was asking my self, what would be the latency on the wire?
If I were to set up two of these adapters, one in my living room next to a Steam link module, and the second one close to my computer just connecting my computer with it. Would this be fast enough data transfer, so that I can use Steam link as intended without an notable delay?
Or are there other pitfalls with these devices which prevent a satisfying usage together with Steam link?
Comment: Should be fine, this is quite similar to a wired network just over power lines. I suggest you check reviews on the different brands as some are better than others. The latest models get very good average speeds and latency.
Answer: Steam Link is essentially streaming rendered gameplay and user input back and forth between multiple devices. This will require a reasonable amount of network bandwidth but more importantly, stable and low latency.
It's not likely that you'll experience bandwidth related issues as a result of using power line networking so we'll concentrate on latency.
The latency and quality of signal when using power line networking is entirely dependant on the environment - that is, the electrical wiring within your home. This varies wildly from building to building so even generic advice probably wouldn't apply.
Some people report latency increases of 20+ms as a result of using power line networking which is where the issues will start occurring. Adding an extra 20+ms of latency will result in noticeable input lag and an overall inferior gaming experience.
Your best bet is to get actual numbers and that's going to involve testing such technologies within your own environment. Due to the variances in the quality of electrical wiring, many people find it works fine and many people find WiFi to be more stable. Your mileage will vary based entirely on the electrical wiring within your own environment.
Comment: Is there any way to test what the latency would be without purchasing the device?
Comment: Nope... it's entirely dependant on the quality of the wiring in your environment
Comment: And sending my own ping out on the power line with some selfmade tools would probably result in the building on fire and leaving me reliable for the damage-cost without any insurance willing to pay, right? x'D
Comment: You might be able to ask your question on Electronic Engineering. I think if you know how your house is wired up, you can start to get an idea. If your "route" through the power system takes you through your fuse board, this is a bad sign, but if it stays on the same circuit, this would be a better sign.
Comment: +20 ms seems a huge increase to me, since it's more or less an Ethernet connection using electric wires. Was it properly measured? Was it compared to Ethernet?


Why does my aliases change to a different element?

Question: I have the following code:
cy.get('input:checkbox').first().as('firstCheckbox').then(() => {

    cy.get('@firstCheckbox').should('be.checked').click()
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('be.visible')
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('not.exist')
    cy.get('@firstCheckbox').should('not.be.checked').click()
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('be.visible')
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('not.exist')
    cy.get('@firstCheckbox').should('be.checked')

})

after cy.get('@firstCheckbox').should('be.checked').click() the checkbox is moved to the last index position instead of the first.
According to my understanding of aliases this should not matter, because I reference it with ('@') and it doesn't matter at which position it is. Unfortunately the next cy.get('@firstCheckbox') accesses the new first element and not the one I originally referenced. I can't figure it out from the documentation either.
where is the error?
https://docs.cypress.io/guides/core-concepts/variables-and-aliases
https://docs.cypress.io/api/commands/as
Update for @agoff:
it seems to work better with your code but there is a new problem I notice with the new code.
if you uncheck the checkbox then the class is reloaded with js causing it to briefly disappear from the dom. After that it can't find it anymore and the test aborts.
I also tried with reload but it can't find the element anymore. How to deal with this?
the checked checkbox class has the name custom-control-input ng-untouched ng-pristine ng-valid. after unchecking the class name changed to custom-control-input.ng-untouched.ng-valid.ng-dirty for a second and then the element is removed and reloaded to the DOM with with the class name custom-control-input ng-untouched ng-pristine ng-valid. the problem is here that the second cy.wrap($el) tries to find the element custom-control-input.ng-untouched.ng-valid.ng-dirty although the initial element with the class custom-control-input ng-untouched ng-pristine ng-valid was searched and found. that's something else I don't understand.
Comment: What do you mean by this line `the checkbox is moved to the last index position instead of the first.` ?
Comment: if i uncheck the checkbox then the index of the element changes from 0 to last position.
so it is coded on our website.
Answer: It happens if during the click event the app removes the input and appends a new one at the end. Then your alias is invalid, because it points to an element no longer in the DOM.
If I move the element within the click handler, your code works.
If I clone the element within the click handler, your code fails.
What to do?
Refresh your alias after the click()
cy.get('input:checkbox').first().as('myCheckbox').then(() => {

  cy.get('@myCheckbox').should('be.checked').click()
    .then(() => cy.get('input:checkbox').last().as('myCheckbox'))  // it's last now!

  cy.get('.globalMessage-display > :nth-child(1) > .alert').should('be.visible')
  cy.get('.globalMessage-display > :nth-child(1) > .alert').should('not.exist')

  cy.get('@myCheckbox').should('not.be.checked').click()
    .then(() => cy.get('input:checkbox').last().as('myCheckbox'))

  cy.get('.globalMessage-display > :nth-child(1) > .alert').should('be.visible')
  cy.get('.globalMessage-display > :nth-child(1) > .alert').should('not.exist')

  cy.get('@myCheckbox').should('be.checked')
})

The alias command has another trick as well.
If the element is cloned and replaced, the original element becomes detached from DOM.
The cy.get('@alias') detects detached elements and replays the original command to automatically refresh.
It doesn't work with .first() because the element changes position.
But if you use a data-cy attribute instead of .first(), your code will work.
cy.get('input:checkbox[data-cy="first-checkbox"]')
  .as('myCheckbox').then(() => {

  cy.get('@myCheckbox')
    .should('be.checked').click()    // cloned and moved to another position

  ...

  cy.get('@myCheckbox')                 // detached by previous click
    .should('not.be.checked').click()   // so alias replays original get
                                        // with [data-cy="first-checkbox"]
  ...
  cy.get('@myCheckbox').should('be.checked')  // as above
})

Here's the Cypress code that does it
let { subject, alias, command } = aliasObj

const resolveAlias = () => {

  if ($dom.isElement(subject)) {          // if this is a DOM element

    const replay = () => {
      cy.replayCommandsFrom(command)
      return undefined
    }

    if ($dom.isDetached(subject)) {     // is it detached?

      subject = subject.filter((index, el) => $dom.isAttached(el))  // all detached?

      if (!subject.length) {
        return replay()                // perform the replay
      }
    }

Comment: works pretty well! Ty mate
Answer: I think you are confusing and misusing aliases. When you use the .then(), you've already yielded the found element. So, instead of using the alias, you can reference the object directly (after wrapping it). I believe that something like this should fix your problem...
cy.get('input:checkbox').then(($el) => {
  cy.wrap($el).should('be.checked').click()
              .and('not.be.checked').click()
              .and('be.checked')
})

Comment: updated my initial question
Comment: Updated my answer -- you might be able to get around it by chaining the shoulds (now written as `and()`) instead of re-wrapping the element?
Comment: works but what do I do if I want to run other code between `clicks`? Then the code does not work unfortunately.
and it is not very stable. sometimes it works, sometimes it breaks off after the `clicks` because it is too fast. `.wait` did not help there either
Comment: What exactly are you trying to do? My answer was in response to the provided code, and mimics that exact behavior. I think I'm a little confused about what exactly you'd like to do, from start to finish.
Comment: sorry for the confusion. i thought the simplified code above would be enough to get a solution.
I have updated it so that the full extent of the test can be seen.
Comment: When you uncheck the box and it goes to the last index, does checking it always return it back to the first index?
Comment: yes, thats right.


vexflow javascript produces no output

Question: I am not sure what I am missing, but my vexflow test page simply does not output anything. Any help will be appreciated. This is the url to the test page http://www.gratun.org/test/vexflow.php.
I include the script /vexflow-debug.js in the head section. Then I have the javascript

And the div in the body

Then nothing appears, no output at all from the script. Thank you.
Answer: There is a confusion on all the samples at vex-flow, the scripts are quite all over the place on different morphing and intentionally obfuscated. Here is what I did. Download all resources in /var/www/html/JAZZ folder.
wget http://vexflow.disqus.com/embed.js
wget http://static.vexflow.com/css/bootstrap.min.css
wget http://static.vexflow.com/css/bootstrap-editable.css
wget http://static.vexflow.com/css/alertify.core.css
wget http://static.vexflow.com/css/alertify.default.css
wget http://my.vexflow.com/css/app.6d53e562a278d7dfcfee5ad978ac34d4.css
wget http://static.vexflow.com/js/support/ace/ace.js
wget http://static.vexflow.com/js/support/jquery.min.js
wget http://static.vexflow.com/js/support/bootstrap.min.js
wget http://static.vexflow.com/js/support/bootstrap-editable-inline.min.js
wget http://static.vexflow.com/js/support/alertify.min.js
wget http://static.vexflow.com/js/support/vexflow-min.81.js
wget http://static.vexflow.com/js/support/tabdiv-min.81.js
wget http://static.vexflow.com/js/support/underscore-min.js
wget http://static.vexflow.com/js/support/paper.min.js
wget http://my.vexflow.com/js/app.9da856e68cab5dda7469337bb6f6f2eb.js -C ./theapp.js

Then I created a simple page as: see it's source here
http://220.127.116.11/muzikian/

vexflow javascript produces no output


Coupon Collector when $n=3$

Question: Suppose we have $3$ different types of coupons $C_1,C_2,C_3$, and the probability we draw each coupon is $p_1,p_2$ and $p_3$ for $C_1,C_2$ and $C_3$ accordingly. How many times in average will we have to draw until we get a coupon of each type?
I said the following:
Observe the last coupon drawn. With probability $p_1$ it is $C_1$. Now observe the first coupon drawn, it must be different than $C_1$ since otherwise the trial wouldn't have ended. With probability $p_2$ it was $C_2$, and in the middle we would've needed to draw $C_3$ once, and for that to happen we would need $\frac{1}{p_3}$ draws. Doing the same logic for all possibilities of last coupon drawn, we get that the average number of draws is:

$p_1 \cdot (1 + p_2 \cdot (1 + \frac{1}{p_3})) + p_1 \cdot (1 + p_3 \cdot (1 + \frac{1}{p_2})) + p_2 \cdot (1 + p_3 \cdot (1 + \frac{1}{p_1})) + p_2 \cdot (1 + p_1 \cdot (1 + \frac{1}{p_3})) + p_3 \cdot (1 + p_1 \cdot (1 + \frac{1}{p_2})) + p_3 \cdot (1 + p_2 \cdot (1 + \frac{1}{p_1}))$

However, I feel that something is off with this. Any guidance towards whether this is correct or where a mistake has been made?
Comment: Why is the probability that $C_1$ is drawn last equal to $p_1$?  If $p_1$ is very near $1$ then it is highly unlikely that $C_1$ is drawn last.
Comment: I'd do it with states.  Index the states according to which coupons have been seen.  Thus $S[1,3]$ refers to the state in which $C_1,C_3$ have been seen (and $C_2$ has not).  Then proceed by backwards induction.
Comment: You're right. That doesn't make sense. However, I still have no intuition regarding the way you suggest. Care to explain more?
Comment: It's more a matter of computation then of intuition. If you are in $S[1,3]$ then you expect $\frac 1{p_2}$ trials before you are done.  Similarly for $S[1,2],S[2,3]$.  Now, the answer $E=E[\emptyset]=\sum p_i\times (E[i]+1)$ so all you need to do is to compute $E[1],E[2],E[3]$ (where, of course, $E[1]$ denotes the expectation from $S[1]$ and so on).
Comment: This is a very standard technique so it is worth your spending some time on it.  Just focus on the transitions.  $S[1]$ can only move to $S[1,2]$ or $S[1,3]$ (or stay in $S[1]$).  What is the probability that it moves to $S[1,2]$?
Comment: Probability that $S[1]$ moves to $S[1,2]$ is the probability that we have drawn coupon $1$ any number of times after the first one and then have drawn coupon $2$, ie $p_1^{k} \cdot p_2$ for some $0 \leq k < \infty$
Comment: Well, no.  The probability of that transition can't be a function of an unknown parameter like $k$.  Think of it this way:  If you are in $S[1]$ then drawing $C_1$ is irrelevant...the only relevant moves are drawing $C_2$ or $C_3$.  So, ignore $C_1$ and focus on the the $p_2+p_3$ probability that you don't draw $C_1$.  Of that, $p_2$ is explained by $C_2$ so the answer is $\frac {p_2}{p_2+p_3}$.
Comment: An another way to see it:  Let $P$ denote the answer.  Say you are in $S[1]$ and you draw a coupon.  Three things can happen, according to which coupon you draw.  If you get $C_2$ you win.  If you get $C_3$ you lose.  If you get $C_1$ you play again.  Thus $P=p_2\times 1 +p_3\times 0+p_1\times P\implies (1-p_1)P=p_2\implies P=\frac {p_2}{1-p_1}=\frac {p_2}{p_2+p_3}$.
Comment: The idea behind the backwards induction I am proposing to solve your original problem is similar.  I already computed the expected number from states like $S[1,2]$ (it is just $\frac 1{p_3}$).  Let's get $E[1]$, the expected number from $S[1]$.  Again, say you are in $S[1]$ and you draw a coupon.  three things can happen and we see that $E[1]=p_1(E[1]+1)+p_2(E[1,2]+1)+p_3(E[1,3]+1)$.  Recursively, the only unknown there is $E[1]$ so you can solve for it.
Answer: This solution steps through the process from beginning to end.  As noted in the comments, you can also approach this recursively.  The recursive approach is laid out here.
Definitions:
S[0] = starting point
S[1,2,3] = ending point
S[x,y] = state of having Cx and Cy, order you got there doesn't matter
Level 0 = S[0]
$L_1$ = S[1], S[2], and S[3]
$L_2$ = S[1,2], S[1,3], and S[2,3]
$L_3$ = S[1,2,3]
$E_x(L_y)$ = Expected number of steps to get from $L_x$ to $L_y$
Solution:
$E_0(L_1) = 1$
$E_1(L_2) = \frac{p1}{1-p1} + \frac{p2}{1-p2} + \frac{p3}{1-p3}$ (each term is probability times expected wait time)
If exiting S[1] the possible expected wait times at next level are:
$\frac1{p2}$ with probability $\frac{p3}{p2+p3} = \frac{p3}{1-p1}$ if you step to S[1,3], and
$\frac{1}{p3}$ with probability $\frac{p2}{p2+p3} = \frac{p2}{1-p1}$ if you step to S[1,2]
Similarly for exiting S[2] and S[3].
Weighting the three possible $\frac1{p_x}$ $L_2$ to $L_3$ waiting times by the ways of getting to the various S[x,y]
$$\begin{align}
E_2(L_3) &= \frac1{p_1} \cdot ({p_2}\cdot \frac{p_3}{1-p_2} + {p_3}\cdot \frac{p_2}{1-p_3})
\\&+ \frac1{p_2} \cdot ({p_1}\cdot \frac{p_3}{1-p1} + {p_3}\cdot \frac{p_1}{1-p_3})
\\&+ \frac1{p_3} \cdot ({p_1}\cdot \frac{p_2}{1-p_1} + {p_2}\cdot \frac{p_1}{1-p_2})
\end{align}
$$
Combining all $E_x(L_y)$ above gives
$$\begin{align}E_0(L_3) &= E_0(L_1) + E_1(L_2) + E_2(L_3)
\\&=1 + \frac{p_1}{1-p_1} + \frac{p_2}{1-p_2} + \frac{p_3}{1-p_3}
\\&+ \frac1{p_1} \cdot ({p_2}\cdot \frac{p_3}{1-p_2} + {p_3}\cdot \frac{p_2}{1-p_3})
\\&+ \frac1{p_2} \cdot ({p_1}\cdot \frac{p_3}{1-p_1} + {p_3}\cdot \frac{p_1}{1-p_3})
\\&+ \frac1{p_3} \cdot ({p_1}\cdot \frac{p_2}{1-p_1} + {p_2}\cdot \frac{p_1}{1-p_2})
\\&= 1+\frac{p_1}{1-p_1}\cdot(1 +\frac{p_2}{p_3} + \frac{p_3}{p_2}) + \frac{p_2}{1-p_2}\cdot(1 +\frac{p_1}{p_3} + \frac{p_3}{p_1}) + \frac{p_3}{1-p_3}\cdot(1 +\frac{p1}{p_2} +\frac{p_2}{p1})
\end{align}$$
For $p_1=p_2=p_3=0.33$ the result is 5.5

Coupon Collector when $n=3$


How many samples are required to estimate the frequency of occurrence of an output (out of 8 different outputs)?

Question: I have $N$ marbles and to each of them corresponds  a 1 or 2 or 3 or ... or 8.(i.e., there's 8 different kinds of marbles)
How many samples are required to estimate the frequency of occurrence of each kind (within a given confidence interval and confidence level)?
( If the answer is lengthy, a hint or a link to an online reference suffices.)
Comment: what is your distribution?
Comment: @al-Hwarizmi We don't know the distribution. It's like the problem of an election poll (with 8 candidates), where you want to see how many samples is needed to predict the results within a certain confidence interval.
Answer: This is quite straight forward in socio-economic statistics. An example in health care is given here. There also a general calculator.
Hope this helps.
Comment: That's for a two state problem (2 kinds of marbles). I want it for an 8 state problem.
Comment: @Monopole wouldnt the Variance for P give you a formula for sample size $S$ of number of candidates $q=8$, such as $S=q(1-q)/Var(P)$ - random sampling and Bernouli random variable assumed?


Can't install Google App Engine tools for Android

Question: I tried to install the GAE tools for Android and the plugin but I received this error:
Cannot complete the install because one or more required items could not be found.
  Software being installed: Google App Engine Tools for Android 2.5.2.v201203300216-rel-r37 (com.google.gdt.eclipse.mobile.android.feature.feature.group 2.5.2.v201203300216-rel-r37)
  Missing requirement: com.google.gdt.eclipse.mobile.android 2.5.2.v201203300216-rel-r37 requires 'bundle com.android.ide.eclipse.adt 12.0.0' but it could not be found
  Cannot satisfy dependency:
    From: Google App Engine Tools for Android 2.5.2.v201203300216-rel-r37 (com.google.gdt.eclipse.mobile.android.feature.feature.group 2.5.2.v201203300216-rel-r37)
    To: com.google.gdt.eclipse.mobile.android [2.5.2.v201203300216-rel-r37]

Has anyone else received this?
Comment: if you have got the solution then please tell me, because i am also getting the same problem
Comment: I tried later and it worked.  Looks like it was fixed.
Answer: It is usually caused by your proxy configuration. This error appears to me while trying to download from a network that blocked the content.


Can I write some output to the current document and some to shell output?

Question: I'm using gedit and trying to wrestle it into a real IDE. What I want is to map ctrlshift| to run my tidy tool when the file type is "text/html" and my autopep8 tool when the file type is "text/x-python".
As it turns out (and I think this is a bug), gedit doesn't care what filetype you've specified. If you have a key combo set, it will run a tool whether or not the filetype matches. Related, but maybe not a bug, I can only set the keyboard shortcut to one external tool.
So I wrote one external tool that runs on ctrlshift| and runs autopep8 if the document is Python and tidy if the document is HTML:
#!/bin/sh
# [Gedit Tool]
# Save-files=document
# Shortcut=<Primary><Shift>bar
# Output=replace-document
# Name=Tidy by Filetype
# Applicability=all
# Input=document

if [ $GEDIT_CURRENT_DOCUMENT_TYPE = "text/x-python" ]; then
    autopep8 - -v -a
elif [ $GEDIT_CURRENT_DOCUMENT_TYPE = "text/html" ]; then
    #-i auto indents, -w 80 wrap at 80 chars, -c replace font tags w/CSS
    exec tidy -utf8 -i -w 80 -c "$GEDIT_CURRENT_DOCUMENT_NAME"
elif [ $GEDIT_CURRENT_DOCUMENT_TYPE = "text/css" ]; then
    #TK CSS tidy
else
    echo "This seems to be " $GEDIT_CURRENT_DOCUMENT_TYPE " I don't know how to tidy that."
fi

That second to last line is the one that is breaking my heart. If I don't define any action for that last else it just deletes my existing document. If I run ctrlshift| and the file-type isn't one that I've accounted for, I'd like it to report the file type to the shell output, not replace the document contents with

This seems to be  application/x-shellscript  I don't know how to tidy
  that.

Is there a way to write my tool so that I write some output to the shell and some to the document?
Comment: I assume you probably just want to `cat "$GEDIT_CURRENT_DOCUMENT_NAME"` to replace the current document with itself. Have you tried writing the message to stderr (i.e. `echo "this seems to be ..." >&2`)?
Comment: @MarkkuK. Thank you! But why put your answer in a comment? I can't accept it there.
Answer: Having no experience with trying to make gedit more usable, I did find this: https://wiki.gnome.org/Apps/Gedit/Plugins/ExternalTools?action=AttachFile&do=view&target=external-tools-manager-with-gedit-3.png
The key construct here is
echo "..." > /dev/stderr

At least that should stop you from clobbering the contents of your file if it the mime-type doesn't match, but I'm not sure where it'll print out (hopefully somewhere sane).
Edit (for a more complete answer):
You will also need to cat $GEDIT_CURRENT_DOCUMENT_NAME to replace the file contents with itself.  This was pointed out by @markku-k (thanks!)
Comment: I still need `cat $GEDIT_CURRENT_DOCUMENT_NAME` or else it clobbers the contents of my file with nothing, but redirecting output to `stderr` does indeed put it in the Shell Output pane.


IOError: [Errno 2] No such file - Paramiko put()

Question: I'm uploading a file via SFTP using Paramiko with sftp.put(localFile, remoteFile). I make the necessary directory first if needed with
    makeCommand = 'mkdir -p "' + remotePath + '"'
    ssh.exec_command(makeCommand)

this was works sometimes but I'm occasionally getting the following error:
    sftp.put(localFile, remoteFile)
    File "build/bdist.macosx-10.8-intel/egg/paramiko/sftp_client.py", line 565, in put
    File "build/bdist.macosx-10.8-intel/egg/paramiko/sftp_client.py", line 245, in open
    File "build/bdist.macosx-10.8-intel/egg/paramiko/sftp_client.py", line 635, in _request
    File "build/bdist.macosx-10.8-intel/egg/paramiko/sftp_client.py", line 682, in _read_response
    File "build/bdist.macosx-10.8-intel/egg/paramiko/sftp_client.py", line 708, in _convert_status
    IOError: [Errno 2] No such file

despite the fact that the local file definitely exists (and localFile is the correct path to it) and the remote path is made.
There is discussion here and here on a similar problem but none of the points raised there have helped me. My server supports the df -hi command.
Has anyone any advice on this or a possible solution?
EDIT
After suggestions below I tried changing the working directory with sftp.chdir(remoteDirectory) but this call produced the exact same error as above. So it seems this isn't just an upload issue. Any ideas?
Answer: The put method has a confirm parameter which is enabled by default, which will do a stat on the file after transfer.
In my case, the remote server i was transferring the file to, immediately moved any transferred files to another location to get processed which was causing the stat to fail. Setting the confirm parameter to False resolved this.
def put(self, localpath, remotepath, callback=None, confirm=True):

From the paramiko source sftp_client.py:

:param bool confirm:
   whether to do a stat() on the file afterwards to confirm the file
   size (since 1.7.7)
Comment: Oh my god. This is definitely what I was looking for! My remote server immediately moves any transferred files to another location, and I was facing the same problem. Thank you so much!
Answer: It seems to be a remote folder permission problem. Although the remote folder was made before the file was uploaded, it appears the permissions on the folder were preventing an upload.
The problem is linked to this issue - if I set open permissions on the folder I'll be uploading to before I upload, the program can upload fine. Although for a permission issue I should be getting IOError: [Errno 13] Permission denied, since I made the changes I haven't encountered any errors.
I'm not sure if it's the response the server is giving Paramiko which is the issue, or a bug in Paramiko itself which is causing IOError: [Errno 2] No such file instead of a Errno 13,  but this appears to have solved the problem.
Answer: The IOError is local, so (for whatever reason) it seems that your local python cannot find localFile. Safety checking this before the call might help tracking down the problem:
if os.path.isfile(localFile):
    sftp.put(localFile, remoteFile)
else:
    raise IOError('Could not find localFile %s !!' % localFile)

If you're positive that localFile does exist, then this could just be a path problem - is localFile on an absolute or relative path? Either way, the if statement above will catch it.
EDIT
Tracing through the paramiko files shows that line 245 of sftp_client.py (the one throwing the exception) is actually
fr = self.file(remotepath, 'wb')

which is quite misleading as paramiko throws an IOError for a remote file! My best guess now is that remoteFile is either a missing directory or a directory you don't have access to.
Out of interest, can you list the remote dir
sftp.listdir(path=os.path.dirname(remoteFile))

to check that it's there (or maybe it's there and you can write to it)?
Comment: Thanks, go to know it's local. Strangely, I tried opening the file just before uploading, just checking it could be opened, and now it's uploading fine. So if basically have just open it to see first then close it and upload and for some reason that is working now. No idea why. Will add the check like you suggested for safety until I work out the cause!
Comment: Scratch that, it was a coincidence it worked. Uploads were working for about an hour, and now I'm getting the same error. Even if I check the file exists and can open the file, I get the above error when trying to upload?
Comment: Hi, thanks for the edit. Ya I can list the remote directory, and I ca access it. I had a guess that maybe Paramiko was expecting a file to be present at the remote location? So I'm trying a 'touch ' using `ssh.exec_command()` to make a blank file first. Strangely my app will upload fine for some time, then randomly stop working with the error again.
Comment: Strangely, even `sftp.listdir()` is throwing the same error now, even if I make that directory first to be sure it exists?
Answer: Are you sure the directory has been created and it is your remote working directory?
Paramiko has its own methods for creating new directories and navigating the remote file system. Consider using something like:
sftp.mkdir(remotedirectory)
sftp.chdir(remotedirectory)
sftp.put(localfile, remotefile)

Comment: The remote file is definitely made, I'm certain. For a file put/get it isn't necessary to `chdir` if you pass to whole path to the file. Uploads are working at the moment, since I introduced a retry and `touch`, but as a backup, to `chdir` and then put the file could be an option. Could implement this as a fallback if the error arises from the first attempt.
Comment: I tried this as you suggested, and strangely `sftp.chdir()` produces the same error. See my edit above.
Comment: Can you confirm that the directory you are attempting to write to or chdir into already exists. Also, check to see if there is anything in syslog that may be of use.
Comment: Yes, certain it does. As I mentioned above I can even use `touch` to create a file at that location.
Answer: I faced the same issue. it was a silly mistake.

Just use sftp.stat(your remote directory) to check if it's there.
then use sftp.put(localfileabsolutepath, remotedir+filename)

It will work for sure.
Answer: Had the same issue. In my case it was a timing problem:
self.mkdir(remote_dir)
sftp.put(local_file, remote_file)

The mkdir() function, which had
ssh.exec_command(f"mkdir -p {remote_dir}")

in it, didn't finish fast enough.
Changing the original code to
self.mkdir(remote_dir)
sleep(0.01)
sftp.put(local_file, remote_file)

fixed it.


Prove $x^2=y^3$ where $x,y\in \mathbb{Z}$ implies $x=a^3$ and $y=b^2$ where $a,b\in\mathbb{Z}$

Question: I feel like I'm meant to use the uniqueness of prime factorization and show that since $\text{lcm}(3,2)=6$ each prime should appear 6 times, but how would I justify this?
Comment: Can you prove the simpler statement that if $n = x^2$ then the maximum exponent of any prime factor of $n$ is even?
Answer: Use the unique prime factorization.
First not that if $p$ is a prime factor of $x$ then $p|x^2$ so $p|y^3$ so $p|y$.  And if $q$ is a prime factor of $y$ then $q|y^3$ so $q|x^2$ so $q|x$. So $x$ and $y$ have the exact same prime factors.
So if the distinct prime factors of $x$ are $P=\{p_1, p_2, ..... p_n\}$ the $x = \prod\limits_{k=1}^n p_k^{a_i}$ for some $a_i \ge 1$ and $y = \prod\limits_{k=1}^n p_k^{b_i}$ for some $b_i \ge 1$.
Now $x^2 = y^3$ so
$(\prod\limits_{k=1}^n p_k^{a_i})^2 = (\prod\limits_{k=1}^n p_k^{b_i})^3$ so
$\prod\limits_{k=1}^n p_k^{2a_i}=\prod\limits_{k=1}^n p_k^{3b_i}$ so (because the is a unique prime factorization of the value $x^2$ which is $y^3$) we have:
$2a_i = 3b_i$ which means $2|3b_i$ for each $b_i$ and $3|2a_i$ for each $a_i$.  And as $2,3$ are primes that means $2|b_i$ and $3|a_i$ for each $b_i$ and each $a_i$.
So each $b_i = 2c_i$ for some integer $c_i$.  So $y = \prod\limits_{k=1}^n p_k^{b_i} = \prod\limits_{k=1}^n p_k^{2c_i}= (\prod\limits_{k=1}^n p_k^{c_i})^2$.  So $y$ is a perfect square.
So each $a_i = 3d_i$ for some integer $d_i$.  So $x = \prod\limits_{k=1}^n p_k^{a_i} = \prod\limits_{k=1}^n p_k^{3d_i}= (\prod\limits_{k=1}^n p_k^{d_i})^3$.  So $x$ is a perfect square.
That's it.
Answer: Write $x^2 = \prod_{i=1}^k p_i^{l_i}$, for some positive finite integer $k$ where $p_i$ is the $i$-th prime and $l_i$ is a nonegative integer. Then as $\prod_{i=1}^k p_i^{l_i}$ is a square [because $x$ is an integer] each $l_i$ must be a multiple of 2.
As $\prod^k_{i=1} p_i^{l_i}$ is also a cube [because $y$ is an integer] each $l_i$ must also be a multiple of 3. Thus each $l_i$ must be a multiple of 6.
Then $x = \prod_{i=1}^k p_i^{\frac{l_i}{2}}$ [because $x^2 = \prod_{i=1}^k p_i^{l_i}$]   and $y = \prod_{i=1}^k p_i^{\frac{l_i}{3}}$ [because $y^3 = \prod_{i=1}^k p_i^{l_i}$], which as $l_i$ is a multiple of 6, implies that $\frac{l_i}{2}$ is a multiple of 3, which implies that $x$ is a cube; namely
$x= \left(\prod_{i=1}^k p_i^{\frac{l_i}{6}}\right)^3$ with each $\frac{l_i}{6}$ an integer. Likewise $y$ is a square, namely $y= \left(\prod_{i=1}^k p_i^{\frac{l_i}{6}}\right)^2$ with each $\frac{l_i}{6}$ an integer..
Comment: It's also possible for $x$ to be negative (whereas $y$ must be positive since its cube is positive).
Answer: Here's an alternate proof which uses unique factorization in a different way: Given $x^2 = y^3$ with $x,y \ne 0$, define $a := \frac{x}{y}$.  Then $a^2 = \frac{x^2}{y^2} = \frac{y^3}{y^2} = y$ and $a^3 = \frac{x^3}{y^3} = \frac{x^3}{x^2} = x$.
It remains to show that $a \in \mathbb{Z}$.  We do know that $a \in \mathbb{Q}$ and that $a^2 = y \in \mathbb{Z}$.  Now, look at one of the standard proofs that $\sqrt{2}$ is irrational using unique factorization; this will generalize in a fairly straightforward manner to show the desired fact that if $a \in \mathbb{Q}$ and $a^2 \in \mathbb{Z}$, then $a \in \mathbb{Z}$.
(This can also be viewed as a corollary of the fact that $\mathbb{Z}$ is integrally closed, since $\mathbb{Z}$ is a unique factorization domain and any unique factorization domain is integrally closed.)
Answer: Here's a proof by infinite descent that $x$ is necessarily a perfect cube. The proof that $y$ is a perfect square is of the same exact spirit.
Without loss of generality assume that $x,y$ are positive. Suppose there were to exist pairs of positive integers $(x,y)$ with $x^2=y^3$ but $x$ not a perfect cube. Choose the pair $(x_0,y_0)$ with $x$ minimal. Clearly $x_0,y_0>1$. Consider some prime $p$ dividing $x_0$ and write $x_0=px_1$. Then $p\mid y_0^3\implies y_0=py_1$ for some $y_1\in\mathbb Z_{\geq 0}$. So $$p^2x_1^2=p^3y_0^3\implies x_1^2=py_1^3\implies p\mid x_1$$ Write $x_1=px_2$, again with $x_2$ a positive integer. Then $$p^2x_2^2=py_1^3\implies px_2^2=y_1^3\implies p\mid y_1$$ Next let $y_1=py_2$. We have that $$px_2^2=p^3y_2^3\implies x_2^2=p^2y_3^3\implies p\mid x_2$$ Finally, take $x_2=px_3$. Our equation becomes $$p^2x_2^2=p^2y_2^3\implies x_3^2=y_2^3$$
So $(x_3,y_2)$ is a pair of positive integers satisfying $x_3^2=y_2^3$, but clearly $x_3<p^3x_3=x_0$. A contradiction $\blacksquare$


How to directly invoke the system shell in Go (golang)?

Question: As per the golang documentation, go does not make a call to the system's shell when you are using exec.Command().
From the golang.org documentation on the "os/exec" package:

Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells.

This presents a problem. Because of this design choice you cannot use piping when executing a command. Therefore the following code does not execute as desired.
package main

import (
        "fmt"
        "os/exec"
)

func main() {
        exec.Command("echo", "Hello", ">>", "~/thing").Run()
        cmdOut, _ := exec.Command("cat", "~/thing").Output()

        fmt.Println(cmdOut)
}

Instead of printing out the contents of a file that should contain the word 'Hello,' it instead prints out a blank newline. I have tried directly invoking bash like this:
package main

import (
        "fmt"
        "os/exec"
)

func main() {
        exec.Command("bash", "-c", "echo", "Hello", ">>", "~/thing").Run()
        cmdOut, _ := exec.Command("cat", "~/thing").Output()

        fmt.Println(cmdOut)
}

This, however, produces the same result as the original code. How can I directly invoke the system shell when using golang?
Answer: The second argument should be one string. In shell command you need to pass it as one string too. Also ~ is interpreted by bash. You can safely assume that sh exists. Bash shell is not a must.
package main

import (
 "fmt"
 "os/exec"
)

func main() {
 exec.Command("sh", "-c", "echo Hello >> ~/thing").Run()
 cmdOut, _ := exec.Command("sh", "-c", "cat ~/thing").Output()
 fmt.Println(cmdOut)
}


Color cycles for charts

Question: I've been trying to create a plot with many (~1000s) of boxplots using Bokeh (v0.8.1). I noticed that whenever I try to use the bokeh.charts.BoxPlot function I hit an error with plots with more than 6 boxplots.
import numpy as np
from bokeh.charts import BoxPlot
test = {}
for i in range(0,7):
    test[str(i)] = np.random.normal(0,1,100)
plot = BoxPlot(test)
show(plot)

Stacktrace:
ipython-input-321-6a3614410bf5> in <module>()
      4 for i in range(0,7):
      5     test[str(i)] = np.random.normal(0,1,100)
----> 6 plot = BoxPlot(test)
      7 show(plot)
/opt/pkg/python27/lib/python2.7/site-packages/bokeh/charts/builder/boxplot_builder.pyc in BoxPlot(values, marker, outliers, xscale, yscale, xgrid, ygrid, **kw)
     79     return create_and_build(
     80         BoxPlotBuilder, values, marker=marker, outliers=outliers,
---> 81         xscale=xscale, yscale=yscale, xgrid=xgrid, ygrid=ygrid, **kw
     82     )
     83

/opt/pkg/python27/lib/python2.7/site-packages/bokeh/charts/_builder.pyc in create_and_build(builder_class, values, **kws)
     38     chart_kws = { k:v for k,v in kws.items() if k not in builder_props}
     39     chart = Chart(**chart_kws)
---> 40     chart.add_builder(builder)
     41
     42     return chart

/opt/pkg/python27/lib/python2.7/site-packages/bokeh/charts/_chart.pyc in add_builder(self, builder)
    113     def add_builder(self, builder):
    114         self._builders.append(builder)
--> 115         builder.create(self)
    116
    117         # Add tools if supposed to

/opt/pkg/python27/lib/python2.7/site-packages/bokeh/charts/_builder.pyc in create(self, chart)
    161     def create(self, chart=None):
    162         self._adapt_values()
--> 163         self._process_data()
    164         self._set_sources()
    165         renderers = self._yield_renderers()

/opt/pkg/python27/lib/python2.7/site-packages/bokeh/charts/builder/boxplot_builder.pyc in _process_data(self)
    185                 out_x.append(level)
    186                 out_y.append(o)
--> 187                 out_color.append(self.palette[i])
    188
    189         # Store

IndexError: list index out of range

It appears that whatever predefined color list for the BoxPlot function has run out of colors for new boxplots.
Is there a way to either define a new color list (ideally, a cycle that will simply repeat colors if it runs out) or disable coloring entirely?
Answer: Cycle colors implementation to repeat colors on bokeh.charts have been added in recent versions (IIRC 0.8). It seems like it's a bug. Stack Overflow is really not the best place for such discussion and to track issues.
I've opened an issue related to the cycle_colors/palette bug on charts that also contains a quick way you can use to bypass the problem. You can see it here. Basically you can explicitly build and pass you own big enough palette. If you'd like to help or provide other feedbacks please use the related GH issue mostly because it's easier for us to track.
Thanks!
Comment: Thanks for the reply! I should have put the version of Bokeh I was using in my question, so apologies for that. I'm on 0.8.1 right now, upgraded to 0.8.2 just to be sure, which caused me to encounter a different error upon trying to import bokeh.charts. I will report the new bug on github and once that's resolved come back to this to see if the new version fixes this issue.
Comment: The import error I was facing had something to do with me upgrading from 0.8.1->0.8.2. On a fresh install of Bokeh, this error still exists in 0.8.2, so I posted this particular problem to github.
Comment: @schultzmattd I've updated the answer with better details and a link to the related GH issue.

Color cycles for charts


Netsuite - Set line item value for department

Question: I am trying to make custom mass update on netsuite with JS script but its not working.
Code:
function updateDepartment(rec_type, rec_id)
{
  var transaction = nlapiLoadRecord(rec_type, rec_id);
  transaction.setLineItemValue ('item','department', nlapiGetContext().getSetting('SCRIPT','custscript_dept_update'));
  nlapiSubmitRecord(transaction, false, true);
    }

Answer: nlobjRecord.setLineItemValue needs a line number. You'd need to do something like:
var dept = nlapiGetContext().getSetting('SCRIPT','custscript_dept_update');
for(var i = transaction.getLineItemCount('item'); i> 0; i--){
  transaction.setLineItemValue('item', 'department', i, dept);
}

Comment: Hello I used below code, it works but not changing the department.                               `function updateDepartment(rec_type, rec_id)
     {
    var transaction = nlapiLoadRecord(rec_type, rec_id);
      var dept = nlapiGetContext().getSetting('SCRIPT','custscript_dept_update');
for(var i = transaction.getLineItemCount('item'); i> 0; i--){
  transaction.setLineItemValue('item', 'department', i, dept);
}
  }`
Comment: You still need to submit the record that you loaded; you have `nlapiSubmitRecord` in your question, but then I don't see it in your comment.
Comment: Note that line items are 1-indexed, not 0-indexed.  bknights has it right but just to point that out -- not obvious when everything else in Javascript is 0-based.


Does Armor/Magic Resist affect percentage damage?

Question: Is % based spell damage like Liandry's Torments passive or Amumus Despair (W) affected by Magic Resistance? Same goes with Botrk and armor.
Comment: EVERYTHING, gets reduced by armor and mr unless the spell/item specifically states that it does **true damage**, if it does not say it is true damage it will have to go through the opponents defense first. Here is a fun little **[Damage Chart](http://forums.euw.leagueoflegends.com/board/showthread.php?t=1011838)** showing how much armor/mr reduces the attackers damage.
Answer: Yes it is !
The % damage in those effects is doing magic damage once calculated, so let's say its 10% magic dmg on 1000hp, then the result will be 100dmg, to which you apply the % of magic resistance so to finish the example let's say 50% magic resist. You apply this 100dmg x 50% MR = 50dmg.

"Enemies in the area will be dealt a percentage of their maximum
  health plus a base amount as magic damage each second. "

That's amumu Despair skill (the W), as you can see it clearly is magic damage once calculated, so resistance apply to it.

"dealing true damage equal to a flat amount plus a percentage of the
  target's maximum health"

And that is vayne's W, where it is stated that it is true damage, so no resistance is applied
I just noticed you asked for botrk too, sorry. It will work exactly the same way but with armor as the % from botrk is calculated as physical damage. So once the % is calculated based on target's hp, the % damage reduction from armor will apply. So, botrk is really efficient against high hp, low armor champions, but if they start to build a lot of armor you will need a black cleaver or a last whisper to penetrate armor if you want the effect of botrk to still be important.
Comment: have you got a source for this?
Comment: "Enemies in the area will be dealt a percentage of their maximum health plus a base amount as magic damage each second. " That's amumu Despair skill (the W), as you can see it clearly is magic damage once calculated, so resistance apply to it, and that is vayne's W " dealing true damage equal to a flat amount plus a percentage of the target's maximum health", where it is stated that it is true damage, so no resistance is applied
Answer: Yes, physical and magical damage will get reduced by armor and magic resistance.
There is also the common misconception that you "have" to buy percentage damage against Tanks. While this is true to a certain degree, it will only help if they have a lot of HP without resistances, If someone has 200 Armor and 3000 life, a Bloodthirster with some crit will often do just as well as a BotrK.
The percentage is calculated first and the damage reduction after. So if you have our favorite spin to win champion with 100 armor (50% dmg reduction) and 1000 HP, your blade will do a passive 40 physical damage.
The same goes for effects like Brand Passive and Amumu W of course just with Magical damage and magic resistance.


How to update and access subkeys of a dict in a dict [python]

Question: I am using a dict in a dict to count four parameters related to 20 items.
resi = {'a': {'x': 0, 'y': 0, 'z': 0}, 'b': {'x': 0, 'y': 0, 'z': 0}, ...}

The function 'count' counts the frequency of parameters x, y, z occurring with 20 items.
re: a key in main dict resi; bas : a key in the nested dict
def count(re, bas, aa = resi) :
    t = aa[re]
    t[bas] += 1
    print aa

When the function is called, count updates the parameter in all main keys. I also tried
aa[re][0][bas] += 1

This shows a key error. How do I update a specific key in main dict?
Comment: Are you saying that if you update `resi['a']['x']`, that `resi['b']['x']` also changes? If so, please share the code that *created* the `resi` to start with.
Comment: I'm not entirely sure what you are trying to do here. What are the values you pass into `count()`?
Comment: re and bas are strings four characters long! Does that affect ?
Comment: It sounds as if each nested dict is a copy of *one* dict instead of separate objects.
Comment: Yes I created `resi` from `dict.fromkeys(res, second_dict)` and `resi[b][x]` also changes when I change `resi[a][x]`.
Comment: All your values point to *one* mutable dict, and then what you see is expected behaviour. Use Ignacio's technique to create a new dict for each value (use `dict(second_dict)` in that loop to create a copy).
Comment: @Martijn I used `resi = dict((k, second_dict) for k in ('a', 'b', ...))` to create the dict, still ended up with the same results.
Comment: I've expanded my comment into an answer below. You need to create *copies* of `second_dict`.
Answer: You goofed up creating the dict in the first place.
resi = dict((k, {'x':0, ...}) for k in ('a', 'b', ...))

Comment: How do I access each item in this dict? Same format I used before?
Answer: You need to create unique dicts for the subdict, you cannot reuse the same second_dict value and expect this to result in separate dictionaries for your nested structure.
Use:
resi = {k: dict(second_dict) for k in res}

instead; dict(second_dict) creates a fresh copy of second_dict for each key.


$dh/dt$ given $dV/dt$

Question: I have a textbook problem whose answer is different from the one I got.

The problem goes:

A conical egg timer is letting sand through from top to bottom at a rate of $0.02\,\mathrm{cm^3s^{-1}}$.
find an expression for the rate of change of height ${\dfrac{dh}{dt}}$.

(There is a diagram showing the full height of the conical egg timer as $5\,\text{cm}$ and the radius of its base as $2\,\text{cm}$. The value of $h$ is the height of the sand in the conical egg timer.)

My Attempt:

What I understand from this question is that:

The conical egg timer is an upside-down cone, so its volume is ${V={\frac{1}{3}{\pi}r^{2}h}}$, which is also the same as the volume of the sand within it at the beginning.

The rate of change of volume of the sand within the conical egg timer with respect to time is ${\dfrac{dV}{dt}}=-0.02$.

The diagram shows the radius at the base of the conical egg timer (or "top" since it is upside-down) to be ${2}$ and its full height from base to "point" to be ${5}$.

The sand exits from the "point" so its height decreases from its base (the top).

The question is asking me to find the rate of change of the height of the sand within the timer with respect to time, or ${\dfrac{dh}{dt}}$.

Given this information, I attempted to answer the problem:

If I am correct, the values given at the start are:
${\dfrac{dV}{dt}}=-0.02$
and (at the very beginning, when the cone is full of sand, assuming it starts full)
$h=5$ and $r=2$.

First, I differentiated the volume ${V}$ with respect to ${h}$, giving ${\dfrac{dV}{dh}={\frac{1}{3}}{\pi}{r^{2}}}$ (using the power rule for differentiation).
$\to {\dfrac{dV}{dh}={\frac{1}{3}}{\pi}{r^{2}}}$

Secondly, I used the relationship of the derivative of a function and the derivative of its inverse to get ${\dfrac{dh}{dV}}={\dfrac{1}{\dfrac{dV}{dh}}}={\dfrac{1}{\frac{1}{3}{\pi}r^{2}}}={\dfrac{3}{{\pi}r^{2}}}$ (using the inverse function theorem (I don't fully understand why derivatives of inverses are reciprocals to one another but that's the rule I used)).
$\to {\dfrac{dh}{dV}}={\dfrac{3}{{\pi}r^{2}}}$

Thirdly, I multiplied ${\dfrac{dV}{dt}}$ and ${\dfrac{dh}{dV}}$ to get ${\dfrac{dh}{dt}}=-0.02 \times{\dfrac{3}{{\pi}r^{2}}}={\dfrac{-0.06}{{\pi}r^{2}}}={\dfrac{-3}{50{\pi}r^{2}}}$ (using the chain rule for differentiation).
$\to {\dfrac{dh}{dt}}={\dfrac{-3}{50{\pi}r^{2}}}$

Then, I used the initial values of the height and radius of the sand in the cone to write ${\dfrac{dh}{dt}}$ in terms of $h$.
The initial values of $h$ and $r$ are the values found in the diagram:
$h=5$ and $r=2$
$\to {\dfrac{dh}{dt}}={\dfrac{-3}{50{\pi}r^{2}}}={\dfrac{-3}{50{\pi}({2})^{2}}}={\dfrac{-3}{200{\pi}}}={\dfrac{-3}{40h{\pi}}}={\dfrac{-3}{8{h^{2}}{\pi}}}={\dfrac{-3}{8{\pi}h^{2}}}$ (replacing $r$ in the equation with $2$ and then replacing every multiple of $5$ in the equation with $h$).
$\to$ my answer is ${\dfrac{dh}{dt}}={\dfrac{-3}{8{\pi}h^{2}}}$.

C) The answer given in the textbook however, is ${\dfrac{dh}{dt}}={\dfrac{-1}{8{\pi}h^{2}}}$.

Question:

I'd like to ask for help with regards to finding where I made my error(s), so I hope my working is easy to follow- I am also unsure about whether this is the correct way to answer the question in the first place - thanks.
Comment: This is a very thoroughly written up question for a new contributor. Welcome to math.se!
Answer: Note that in a cone, the radius isn't constant. More specifically, the radius is dependent on the height (you can use similar triangles to find their ratio). When you try to find $\frac{dV}{dh}$, you must consider that $\frac{dr}{dh}\neq 0$.
It would be better to substitute an expression relating $r$ and $h$ and then find $\frac{dV}{dh}$.
Comment: What I was trying to say is that you made your mistake when you found $\frac{dV}{dh}$.$V=\frac{1}{3}\pi r^2h=\frac{1}{3\tan^2 x}\pi h^3$. So $\frac{dV}{dh}=\frac{\pi h^2}{\tan^2 x}$ and $\frac{dh}{dt}=-\frac{.02\tan^2 x}{\pi h^2}=-\frac{1}{8\pi^2 h}$
Comment: Using the relationship between h and r where $\frac{h}{r}={\tan x}$, where $x$ is the angle between the radius and the length going from the radius to the point of the cone, the equation $\dfrac{dh}{dt}=\frac{-3}{50{\pi}r^{2}}$ can be written in terms of h by rearranging $\frac{h}{r}={\tan x}$ into ${\frac{1}{r^2}={\frac{\tan^2{x}}{h^2}}}$and then substituting ${\frac{1}{r^2}}$ into $\dfrac{dh}{dt}=\frac{-3}{50{\pi}r^{2}}$ to give ${\dfrac{dh}{dt}}={\frac{-3{\tan^{2}x}}{50{\pi}{h}^2}}$
Comment: After this, using the initial values of $h=5$ and $r=2$ to get the value of ${\tan^2 x}$ as ${\tan^2 x = {\frac{25}{4}}}$, and the property of similar triangles that given the same angles, the trigonometric function values for those angles are the same, regardless of the lengths of the sides of the triangle containing them, substituting ${\tan^2 x = {\frac{25}{4}}}$ into ${\dfrac{dh}{dt}={\frac{{-3}{\tan^2 x}}{50{\pi}h^2}}}$ still gives ${\dfrac{dh}{dt}={\frac{{-3}}{8{\pi}h^2}}}$ however (if I am correct).

$dh/dt$ given $dV/dt$


How to delay a JQuery window reload?

Question: What am I missing?  I can't seem to delay this even though the syntax seems correct.
window.location.reload(true).delay(800);//true= hard refresh

Comment: `setTimeout(function() { window.location.reload(true); },800);`
Comment: Per https://api.jquery.com/delay/ `delay()` "set(s) a timer to delay execution of subsequent items in the queue".  Your `reload` comes before `delay`
Comment: Can't you just use the `setTimeout` thing?
Comment: Check out this answer.  http://stackoverflow.com/questions/4544126/jquery-delay-not-working
Answer: reload() doesn't return anything that I know of; certainly not  a jQuery object, or any object on which delay() could be called.
Not that it matters - reload() takes effect immediately.
You want to use setTimeout() to delay the actual call to reload()
setTimeout(
  function() {
    window.location.reload(true);
  }, 800);

Comment: even if it returned something it would not work as delay is for delaying the next queue element and not the previous.

How to delay a JQuery window reload?


SQL Bulk insert ignores first data row

Question: I am trying to import a pipeline delimited file into a temporary table using bulk insert (UTF-8 with unix style row terminator), but it keeps ignoring the first data row (the one after the header) and i don't know why.
Adding | to the header row will not help either...
File contents:
SummaryFile_20191017140001.dat|XXXXXXXXXX|FIL-COUNTRY|128
File1_20191011164611.dat|2|4432|2|Imported||
File2_20191011164611.dat|3|4433|1|Imported||
File3_20191011164611.dat|4|4433|2|Imported||
File4_20191011164611.dat|5|4434|1|Imported|INV_ERROR|
File5_20191011164611.dat|6|4434|2|Imported||
File6_20191011164611.dat|7|4434|3|Imported||

The bulk insert throws no error, but it keeps ignoring the first data line (File1_...)
SQL below:
IF OBJECT_ID('tempdb..#mycsv') IS NOT NULL
DROP TABLE #mycsv

create table #mycsv
    (
        tlr_file_name   varchar(150) null,
        tlr_record_id   int null,
        tlr_pre_invoice_number  varchar(50) null,
        tlr_pre_invoice_line_number varchar(50) null,
        tlr_status  varchar (30) null,
        tlr_error_code  varchar(30) null,
        tlr_error_message   varchar (500) null)

bulk insert #mycsv
from 'D:\TestData\Test.dat'
with (
    rowterminator = '0x0A',
    fieldTerminator = '|',
    firstrow = 2,
    ERRORFILE = 'D:\TestData\Import.log')

select * from #mycsv

It's really bugging me, since i don't really know what am i missing.
If i specify FirstRow = 1 th script will throw:
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 2 (tlr_record_id).
Thanks in advance!
Comment: I'm baffled.  Your first row contains column headers.  You don't really want them in your table, do you?  You *want* to skip the first row.
Comment: Yes, sorry, i copied the wrong version, which throws error...  edited
Comment: I think you need to add "|||" three delimiters to the header, to match the data rows, else header is ignored, and "first" data row is treated as row 1, and skipped. See full answer below. Problem solved?
Answer: "UTF-8 with unix style row terminator" I assume you're using a version of SQL Server that doesn't support UTF-8. From BULK INSERT (Transact-SQL)

** Important ** Versions prior to SQL Server 2016 (13.x) do not support code page 65001 (UTF-8 encoding).

If you are using 2016+, then specify the code page for UTF-8:
BULK INSERT #mycsv
FROM 'D:\TestData\Test.dat'
WITH (ROWTERMINATOR = '0x0A',
      FIELDTERMINATOR = '|',
      FIRSTROW = 1,
      CODEPAGE = '65001',
      ERRORFILE = 'D:\TestData\Import.log');

If you aren't using SQL Server 2016+, then you cannot use BULK INSERT to import a UTF-8 file; you will have to use a different code page or use a different tool.

Note, also, that the above document states the below:

The FIRSTROW attribute is not intended to skip column headers. Skipping headers is not supported by the BULK INSERT statement. When skipping rows, the SQL Server Database Engine looks only at the field terminators, and does not validate the data in the fields of skipped rows.

if you are skipping rows, you still need to ensure the row is valid, but it's not for skipping headers. This means you should be using FIRSTROW = 1 and fixing your header row as @sarlacii points out.
Of course, that does not fix the code page problem if you are using an older version of SQL Server; and my point stands that you'll have to use a different technology on 2014 and prior.
Comment: Then the file isn't a valid Delimited File, @LeviTheOne and cannot be imported by processes that expect a valid Delimited File (such as `BULK INSERT`). It's not the fault of the import process if the file is malformed; that's the exporters problem and they need to fix their set up.
Comment: i tried converting the file in ANSI but the result is the same. Also tried adding `Codepage = 'ACP'`but still ignored. I have SQL server 2016, 2014, 2008R2 and on each of them the first lins is ignored. I'll try importing every line then, and just delete the first from temp table.
Comment: I've just updated my answer to account for this, @LeviTheOne , prior to your comment. You need to fix your header and not skip it; there is no header skipping with `BULK INSERT`
Comment: Ok, by correcting the header and updating the data type from `int` to `varchar` for `tlr_record_id` is working, (imports including the header) but what if i can't modify the file? In the normal flow i can't modify the file, only read data from it.
Comment: Interesting, but I'd expect BULK INSERT to work like:
once i specified a row terminator the first thing should be to split the data in rows, then, split a row into columns:
if the number of col. sep. + 1 doesn't equals the number of columns from table just fill the table row with default(Type) or null, or if there are more separators, then shift the data into a new row (where do the same). TO avoid this kind of problems, it would be nice to have an eager validation on file structure, and the only reason when error should be raised is when cast exception occurs. Why/where am i wrong?
Comment: Also i accepted this answer since it helped the most,  and sorry for the delay on response time
Answer: To import rows effectively into a SQL database, it is important to make the header formatting match the data rows. Add the missing delimiters, like so, to the header and try the import again:
SummaryFile_20191017140001.dat|XXXXXXXXXX|FIL-COUNTRY|128|||

The number of fields in the header, versus the data fields, must match, else the row is ignored, and the first satisfactory "data" row will be treated as the header.
Comment: there is no `Load data local infile` in MS-SQL

SQL Bulk insert ignores first data row


Can I convert a Ubuntu 14.04.1 64-bit server to an ESXi 5.5 VM?

Question: I need to convert a physical ubuntu 14.04.1 64bit server to VMWare ESXi 5.5 virtual machine. Found that VMWare converter 5.5.3 a) do not support trusty (release notes).  b) Converter's server side (source) scripts or utilities faults during conversion if try to convert.
Does anyone have successful experience? What are the tips to success?
Answer: Are you trying to hot clone? If so, you need to use VMware vCenter Converter Standalone 4.0.1 I believe. First create an account at my.vmware.com, then search for "VMware vCenter Converter Standalone". On the "License & Download" tab at the bottom of all the 5.x downloads is 4.0.1.
I just tried what you're attempting. I found 4.0.1 to be the last supported version for Linux. I installed it on my Ubuntu 14.04 laptop (that also has VMware player). To run after installing, issue:
sudo /etc/init.d/vmware-converter start
I tried to do the P2V but got stuck on the "destination" section during conversion -- it kept asking me for credentials but didn't realize it was asking for an ESXi host somewhere else on the network to "accept" the VM. I never did succeed though because I don't have hardware support for an ESXi host, and also don't know if I could alternatively use VMware Player on my laptop to "accept" the VM.
I am not 100% positive on my answer I'm just giving feedback because I just did this last week. Or tried to anyway.
See diagram about hot cloning Linux on top of page 15 here, 4.0.1 User guide: http://www.vmware.com/pdf/converter_standalone_guide401.pdf


OpenXava Impossible to execute Add files action Member not found in model

Question: I'm experimenting with OpenXava files stereotype and embedded class and finding a strange error. First of all, if I create a record and attach a bunch of files to it before saving it for the first time, everything works. If I, however, first create a record (Temple), leave everything in the embedded record (Library) blank, save (saves successfully, it says), then go back to edit it, I get the following message: "Impossible to execute Add files action: Member library.documents not found in model Temple"
I have not been able to find anything useful via google on this.
Is this something I'm doing wrong or an error in OpenXava library.
I'm using: OpenXava version 5.1.1
Tomcat that comes with it: Apache Tomcat Version 7.0.50
Oracle 11g
Here's my Temple and the inner Library class:
<code>package org.openxava.zen.model;

import javax.persistence.*;

import org.openxava.annotations.*;

@Entity
public class Temple
{
    @Id @Column(length=3) @GeneratedValue @ReadOnly
    private int id;

    @Version
    private Integer version;

    @Column(length=50)
    private String name;

    @Stereotype("IMAGES_GALLERY")
    private String photos;

    @Column
    private String address;

    @Embedded
    private Library library;

    @Embeddable
    public static class Library
    {
        @Stereotype("FILES")
        @Column(length=32)
        private String documents;

        public Admittance getAdmittance() {
            return admittance;
        }

        public void setAdmittance(Admittance admittance) {
            this.admittance = admittance;
        }

        @Column
        private Admittance admittance;

        public enum Admittance {MEMBERS_ONLY, COMMUNITY, EVERYONE};

        public String getDocuments()
        {
            return documents;
        }

        public void setDocuments(String documents)
        {
            this.documents = documents;
        }
    }

    public Library getLibrary() {
        return library;
    }

    public void setLibrary(Library library) {
        this.library = library;
    }

    public Integer getVersion() {
        return version;
    }

    public void setVersion(Integer version) {
        this.version = version;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhotos() {
        return photos;
    }

    public void setPhotos(String photos) {
        this.photos = photos;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

}
</code>
Full stacktrace:

Dec 01, 2014 4:09:46 PM org.directwebremoting.util.CommonsLoggingOutput info
  INFO: Exec: Module.request()
  Dec 01, 2014 4:09:46 PM org.openxava.model.impl.MapFacadeBean validate
  WARNING: WARNING!: Member library.documents of Temple not validated: Type unkown (property, reference, collection)
  Dec 01, 2014 4:09:46 PM org.openxava.controller.ModuleManager manageRegularException
  SEVERE: Member library.documents not found in model Temple
  org.openxava.util.XavaException: Member library.documents not found in model Temple
      at org.openxava.model.impl.MapFacadeBean.convertSubmapsInObject(MapFacadeBean.java:1675)
      at org.openxava.model.impl.MapFacadeBean.setValues(MapFacadeBean.java:1337)
      at org.openxava.model.impl.MapFacadeBean.setValues(MapFacadeBean.java:198)
      at org.openxava.model.MapFacade.setValues(MapFacade.java:635)
      at org.openxava.actions.AddFileToFilesetAction.execute(AddFileToFilesetAction.java:27)
      at org.openxava.controller.ModuleManager.executeAction(ModuleManager.java:493)
      at org.openxava.controller.ModuleManager.executeAction(ModuleManager.java:401)
      at org.openxava.controller.ModuleManager.execute(ModuleManager.java:358)
      at org.apache.jsp.xava.execute_jsp._jspService(execute_jsp.java:196)
      at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
      at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
      at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
      at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
      at org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:605)
      at org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:544)
      at org.openxava.web.servlets.Servlets.getURIAsStream(Servlets.java:66)
      at org.openxava.web.dwr.Module.getURIAsStream(Module.java:205)
      at org.openxava.web.dwr.Module.request(Module.java:64)
      at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
      at java.lang.reflect.Method.invoke(Method.java:606)
      at org.directwebremoting.impl.ExecuteAjaxFilter.doFilter(ExecuteAjaxFilter.java:34)
      at org.directwebremoting.impl.DefaultRemoter$1.doFilter(DefaultRemoter.java:428)
      at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:431)
      at org.directwebremoting.impl.DefaultRemoter.execute(DefaultRemoter.java:283)
      at org.directwebremoting.servlet.PlainCallHandler.handle(PlainCallHandler.java:52)
      at org.directwebremoting.servlet.UrlProcessor.handle(UrlProcessor.java:101)
      at org.directwebremoting.servlet.DwrServlet.doPost(DwrServlet.java:146)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:409)
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1044)
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
      at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
      at java.lang.Thread.run(Thread.java:744)
Answer: This issue is addressed in OpenXava forums:
https://sourceforge.net/p/openxava/discussion/419690/thread/fde016f3/


How to change circle to rectangle when mouse hovers on the heat map charts

Question: Demo: http://jsfiddle.net/GreatFusion/tb5y1ztg/
when mouse hovers on the block it shows a big circle extends out of the block. How to make the circle smaller or some other methods to reshape the circle? Absolutely,If I set the plotOptions.series.states.hover.enabled to false can hide the circle,but in this case, I cannot set theborderWidth,color.e.g.
Seems there is no marker attribute in heat map.
Thank you!
Comment: what circle? i don't see any circle. http://jsfiddle.net/tb5y1ztg/1/
Comment: Thanks for your answer. But if you set the `chat.width:300`,you will find the circle.
Answer: You can control it by hover staates or halo options.
Answer: You just need to set:
hover:{
   enabled:false,
   borderColor:'#FF0000'
}

and that circle will disappear (for all widths and heights). Idk what bordercolor you're talking about but the border color of the hover detail window still shows.
See the DEMO here
Comment: If the set `hover.enabled:false`,`hover.borderColor:'#FF0000'` will not work. And I cannot see the red border when mouse on a block in your demo. Thank you.
Comment: i can see the border... http://tinypic.com/r/n4bf5d/8  it will be of the same color as tile whether hover enabled or disabled.
Comment: Thanks for your answer. What you mean is the border color of tooltip. I want to set border color on the block itself.
Comment: You can compare these two cases:`hover:{enabled:false,borderColor:'#FF0000'}` and `hover:{enabled:true,borderColor:'#FF0000'}`. You will find the red border in the second case.
Comment: i really don't see the difference.. http://jsfiddle.net/tb5y1ztg/3/  make a case where there is border
Comment: Ok,You can compare these two cases:`hover:{enabled:false,borderColor:'#00FF00'}` and `hover:{enabled:true,borderColor:'#00FF00'}`. When mouse hovers on the tile,you will see the green border.You cannot miss it.


There is a short way to write if(!is_null($foo) && !is_null($bar))?

Question: So, I am writing a function that receives two arguments, and before I do anything with these variables, I want to check if they are not null.
if (!is_null($foo) && !is_null($bar)) {
    /* do something */
}

The problem is that I think we are repeating code, and in some cases when the variable name is a little bit bigger, it becomes painful to write every time.
So, there is a way to shorten this code?
Comment: There isn't really a shorter way to check if a variable is turly `NULL`.
Comment: You're not putting every individual statement in a seperate `if` block, right?
Comment: Where do you think the repeating code coming from? From your example you only need that 1 if statement to check if both are not null? What else are you wanting?
Comment: the only way would be to define a function which does this stuff - would look like `myCheckFunction(myValuesArray)`
Comment: try `if(count(array_filter(func_get_args()))==func_num_args()){ }`, can be used in all functions
Comment: I just want to know if there is a way to avoid writing `!is_null` for each argument i want to check. If it is the only way, i'll be ok with that, but i want confirm with you guys.
Comment: Ignore my last comment, works not only for `NULL` also for `` and `false`
Answer: You can use isset which returns FALSE if variable is null. You can set there a lot of variables so code will be shorter:
if (isset($foo, $bar))

Answer: You can write your own function to check this:
function is_any_null() {
    $params = func_get_args();
    foreach($params as $param) {
        if (is_null($param))
            return true;
    }

    return false;
}

Now you can use it like this:
if (!is_any_null($foo, $bar)) {
    /* do something */
}

Comment: Interesting approuch.
Answer: is_null() checks a variable to determine if the value is NULL. It can be used in an if statement. It depends on what you would like to do in that if statement. For example, if you would like to do an echo, you can make it a bit shorter using the `elvis``operator:
echo (is_null($foo) && is_null($bar)) ?: 'The values are not null';

Or you could make it a one liner by leaving the { and } out of your code and putting everything on one line.
if (!is_null($foo) && !is_null($bar)) die("NULLLLL");


iphone simulator(10.3) time not showing according to timezone in mac OS (10.13)

Question: I have update my mac os to 10.13 beta version now it showing GMT time for my old simulator with ios version 10.3. its not displaying as per mytimezone(IST). even after reset it and region change of simulator its continuous showing GMT time only.
Comment: Just started running into this today.
Comment: I am seeing this, too. The simulator's time zone is GMT for some reason. I'm still investigating.
Comment: yeah this issue occur on Mac OS 10.13
Comment: yes. but due to this during developing not able to get local time.
Comment: I have fixed it , you can see it in below
Answer: Apple says there are currently no plans to fix this, as per http://www.openradar.me/34812060
Answer: This fixed for me :
<code>export TIMEZONE="Australia/Sydney"
sudo rm -rf /etc/localtime
sudo ln -s /usr/share/zoneinfo/$TIMEZONE /etc/localtime
</code>