Failure to convert FileStream length to int

Question: I have inherited a printer helper class that can be used to send information directly to a printer. It can handle a file, string, or raw bytes. For files and strings it first converts them to bytes, and uses the bytes method to do the sending.
My problem is the file method is failing to set all the necessary variables for the bytes method to succeed. See the method below:
// Open the file.
FileStream fs = new FileStream(szFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

// Create a BinaryReader on the file.
BinaryReader br = new BinaryReader(fs);

// Dim an array of bytes big enough to hold the file's contents.
Byte[] bytes = new Byte[fs.Length];
bool bSuccess = false;

// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);
int nLength;
nLength = Convert.ToInt32(fs.Length);

// Read the contents of the file into the array.
bytes = br.ReadBytes(nLength);

// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);

// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);

// Send the unmanaged bytes to the printer.
bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);

// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);
return bSuccess;

The point of failure seems to be nLength = Convert.ToInt32(fs.length); coming out as 0, even though the stream itself has all the correct data. If I put a breakpoint at that point then it will always work. If I put it below at the SendBytesToPrinter call, it nLength will be 0.
My workaround for now is to have use Thread.Sleep(1000); right before the conversion, but that's too hacky for my taste.
Is there some characteristic of the FileStream that is causing this issue, or is something wrong with the code here?
EDIT: To clarify something, I'm fully aware of the difference between a long and int. The files used do not cause a problem with this. I can run the same file through a dozen times with and without the pause and it will always fail without the pause.
EDIT #2: Brandon's answer didn't solve the problem directly, but the new approach to working with the file revealed an issue with the download method used to get the file in the first place. I'm marking his answer as accepted because not only did it lead me to the real problem, but it's a cleaner way of handling the method in general.
Answer: Instead of relying on the filestream for length, maybe you can rely on the length of the returned byte array:
// Read bytes in from file, capture length of returned array
var bytes = File.ReadAllBytes(szFileName);
var nLength = bytes.Length;

// Your unmanaged pointer.
IntPtr pUnmanagedBytes = new IntPtr(0);

// Allocate some unmanaged memory for those bytes.
pUnmanagedBytes = Marshal.AllocCoTaskMem(nLength);

// Copy the managed byte array into the unmanaged array.
Marshal.Copy(bytes, 0, pUnmanagedBytes, nLength);

// Send the unmanaged bytes to the printer.
var bSuccess = SendBytesToPrinter(szPrinterName, pUnmanagedBytes, nLength);

// Free the unmanaged memory that you allocated earlier.
Marshal.FreeCoTaskMem(pUnmanagedBytes);

return bSuccess;


Excel - How to persist function in column when row data is cut or deleted?

Question: is is possible in Excel to have some sort of fixed function defined for a entire column? This function needs to persist when a row is deleted, and it needs to 'exist' when new row data is added...
So in the example below, If I cut row 1 to row 3 (so the worksheet is empty), I want the 'new' row 1 to have the function in column D already defined (which is actually: multiply the value from C from the same row with 10)... Is this possible?

-----------------------------------------
|    A    |    B    |    C    |    D    |
-----------------------------------------
|    1    |    1    |    1    |=C1 * 10 |  --- ROW 1
-----------------------------------------
|    1    |    1    |    1    |=C2 * 10 |  --- ROW 2
-----------------------------------------
|    1    |    1    |    1    |=C3 * 10 |  --- ROW 3
-----------------------------------------
|         |         |         |         |
-----------------------------------------
|         |         |         |         |
-----------------------------------------
Answer: In Excel 2007 this type of functionality is built in, so long as the data is marked as a table.
Select your data range and click on 'Insert - Table' alternately Ctrl-l or Ctrl-t
Add a new column heading and your formula next to the last column of data.  The table will automatically expand to include the new column.  It will automatically copy the formula down to all rows.
Any new rows added will automatically have the formula included.
Comment: A yes there is, tables are not very intuitive ;)
Comment: They are called Lists in 2003, renamed tables in 2007 and they have been greatly improved.
Answer: If you copy the cell with the function in it, then click the column header (to select all of it) that you want the function to persist in, then right click - paste special - formuals, that should do the trick.
Comment: I'm not pasting... i'm cutting?
Comment: Write the function at least once, then paste it into every cell of the column using paste special. Then when you cut row 1 and paste into 3 the function will be there already.
Comment: Again: I'm NOT pasting, only cutting
Comment: I need to cut the formula, because I need the value in another workbook (where I AM pasting)..... I think you should lay off the pills ;)
Comment: So you are pasting :)... any way, am totally lost.


CMAKE - Changing outdir macro through cmake

Question: Reading others questions here I found that is possible to change the outdir macro inside de visual studio. I really searched but didn't found/understand how to do it.
It's kind simple. I just want to change the Project property -> Configuration Properties -> General -> Output Directory. Because I know that will change the outdir macro.
I understand that is throught set_target_property using some kind of cmake PROPERTY but I really didn't found how.
Answer: It's pretty straightforward as you suspected.  You need to look at the ARCHIVE_OUTPUT_DIRECTORY, LIBRARY_OUTPUT_DIRECTORY, and RUNTIME_OUTPUT_DIRECTORY target properties to modify the outdir path.
These all have config-specific variants too (e.g. ARCHIVE_OUTPUT_DIRECTORY_DEBUG) and can all be initialised by the global CMake variables of the same name with a CMAKE_ prepended.
So, you can do e.g.
set_target_properties(MyExe PROPERTIES RUNTIME_OUTPUT_DIRECTORY <custom path>)

or, to affect all targets,
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY <custom path>)

NB. From the docs:

Multi-configuration generators (VS, Xcode) append a per-configuration subdirectory to the specified directory.

Here's an example showing this behaviour.  It writes its own trivial C++ source files, so all you should need to do is copy this to a folder, invoke CMake then try building the resultant solution in Debug, Release, MinSizeRel and RelWithDebInfo.  Tested with VS2012.  The executable always ends up in <build dir>/Exes/Debug regardless of build type, and similarly the library is always in <build dir>/Libs/Debug.
cmake_minimum_required(VERSION 2.8.11 FATAL_ERROR)
project(Example)

file(WRITE lib.hpp "void Print();\n")
file(WRITE lib.cpp "#include<iostream>\nvoid Print() { std::cout << \"Hello World\\n\"; }\n")
file(WRITE main.cpp "#include \"lib.hpp\"\nint main() { Print(); return 0; }\n")

set(ArchiveOutputDir ${CMAKE_BINARY_DIR}/Libs/Debug)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG ${ArchiveOutputDir})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_MINSIZEREL ${ArchiveOutputDir})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELEASE ${ArchiveOutputDir})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_RELWITHDEBINFO ${ArchiveOutputDir})

set(RuntimeOutputDir ${CMAKE_BINARY_DIR}/Exes/Debug)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${RuntimeOutputDir})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_MINSIZEREL ${RuntimeOutputDir})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${RuntimeOutputDir})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${RuntimeOutputDir})

add_library(MyLib lib.cpp lib.hpp)
add_executable(MyExe main.cpp)
target_link_libraries(MyExe MyLib)

Comment: I tried with all of then. Didn't work, I'll read more about then but just to make sure.

What I'm trying to do is change that $(outdir) macro that is set as Release or Debug. It's add automaticaly on the Additional Library Dependecies. For example, I wish to change all to be always Debug, doesn't mather if I'm really on Debug on VS
Comment: Did you set the `CMAKE_ARCHIVE_OUTPUT_DIRECTORY_DEBUG` variable (or whichever) *before* your `add_library` or `add_executable` calls?  These default CMake variables are used to initialise the local target properties at the point where they are declared.  To have e.g. all your libs created in the same directory regardless of build type, simply set all versions of `CMAKE_ARCHIVE_OUTPUT_DIRECTORY_` to the same value.
Comment: After a lot of days trying, didn't work.

I have this:
c:\dir\anotherDir\Release (Release Build)

But I want This:
c:\dir\anotherDir\Debug (Release Build)

On the Additional Library Directories
Comment: I've added an example CMakeLists.txt.  I've also just noticed that you've tagged your question VS2005.  If this doesn't work for you, I imagine that the version of VS could be the problem.  This certainly works for VS2010 onwards.
Comment: In the end, what worked for me was putting the full path on the target_link_libraries with debug prefix and optimized prefix to point release config and relwithdebinfo config to release path and debug to debug.
I also took off the link_directories... I don't if I didn't understand but it worked for me! Thanks for the help! I really appreciate!
Comment: So I delete the link_directories and put the full path and lib name on the target_link_libraries...
Comment: @KaiqueGomes: if the issue is resolved, please select an answer. I do not understand why you do not select an answer for your questions...
Answer: In the end, what worked for me was placing the full path on the target_link_libraries with debug prefix and optimized prefix to point release config and relwithdebinfo config to release path and debug to debug. I also took off the link_directories... I don't if I didn't understand but it worked for me!
Comment: Can you please post the part of cmakelist.txt for reference here.
Comment: Sorry, company code and I don't have access anymore.


How to make checkedboxlist multiple columns

Question: I am using VS2008 on my home computer to develop a windows form application.
I need to use a CheckedListBox, here is the current CheckedListBox:

I am wondering how can I make it showing two or more columns instead of one at the time.
It would be really appreciated if you can share some code snippets.
Thank you.
Comment: [MultiColumn Property](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.listbox.multicolumn?view=netframework-4.8)
Comment: Thank you JQSOFT, it is just that simple!!! Please put up your answer here and I will accept it.
Comment: Most welcome. Next time thank you.
Answer: If you want a two column control, either use a DataGridView or a ListView control. By setting a ListView control's View property to View.Details, you can use it as a multicolumn grid.


Cache remains stale for custom blocks after editing

Question: My Drupal 8 website consists of multiple custom blocks created from the drupal backend user interface.
As I went from dev to production settings and activating Internal Dynamic Page Cache (set to 1 minute), the custom block content doesn't change on the actual site after editing (for both anonymous and authenticated users). If I go back to editing mode, the changes are persisted as expected.
The changes are visible when I clear the caches (i.e. drush cache-rebuild). I don't have any issues with my own blocks that implements the Block plugin and has a max-age set. Nodes works works as expected too.
What could be wrong?
Comment: When you configure you block, [is it set to forever?](http://i.stack.imgur.com/gjmJK.jpg)?
Comment: @NoSssweat where can I find this option?
Answer: hope this works ...
<?php
abstract class BlockBase extends PluginBase implements BlockPluginInterface {
  /**
   * Returns generic default configuration for block plugins.
   *
   * @return array
   *   An associative array with the default configuration.
   */
  protected function baseConfigurationDefaults() {
    return array(
      'label' => '',
      'module' => $this->pluginDefinition['module'],
      'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE,
      'cache' => array(
        'max_age' => 0,
      ),
    );
  }
}

refer to this link block cache api is removed
The following block cache constants have been replaced with the combination of the cache.max_age and ::getCacheContexts() return values (or bubbled cache contexts) on blocks:
DRUPAL_NO_CACHE (equivalent: cache.max_age = 0)
DRUPAL_CACHE_CUSTOM (equivalent: cache.max_age = 0 + Cache::keyFromQuery())
DRUPAL_CACHE_PER_ROLE (equivalent: cache.max_age >0 + user.roles)
DRUPAL_CACHE_PER_USER (equivalent: cache.max_age >0 + user)
DRUPAL_CACHE_PER_PAGE (equivalent: cache.max_age >0 + url)
DRUPAL_CACHE_GLOBAL (equivalent: cache.max_age >0, no cache contexts)


'useSplashScreen' is deprecated: Deprecated in Cordova 2.5 getting this warning in Xcode

Question: I have Installed Cordova 2.5 and Was trying Hello World in project in Xcode and got this warning. Does any1 have any idea how to solve this warning..
Thanks
Comment: Stop using `useSplashScreen` and perhaps use an alternative if one is available.  I expect the documentation can provide more information.  Read it.
Comment: Ya in the doc it says that stop using Deprecated methods but I thought some1 might have better solution.
Comment: see http://cookieflow.wordpress.com/2013/03/16/hiding-and-showing-the-ios-status-bar-in-phonegap-2-5-0/#more-77
Answer: You can comment out the line in AppDelegate.m (line 68 according to 2.5.0)
<code>self.viewController.useSplashScreen = YES;
</code>
This should remove the warning on your next build.
Answer: Splash screen control has now been split out into the Splashscreen plugin:
http://docs.phonegap.com/en/2.5.0/cordova_splashscreen_splashscreen.md.html#Splashscreen
(There's a full example of its use on that page)
Comment: If this is deprecated then why is the new version shipping this way? Open terminal and create a new project in xcode, when you try to run it you will get this warning. This is plain vanilla, straight from the phonegap package with no changes. Perplexed.
Comment: @timbad2021 I suspect no-one has updated the template app yet!
Answer: In order to solve this issue, the only thing you have to do is comment the line in the AppDelegate.m, save the file and run the application again.
This was left uncommented for backward compatibilities.
The template comes already with the plugin included, you can check it in the plugins section of the config.xml file.
You can review more information on http://docs.phonegap.com/en/2.5.0/cordova_splashscreen_splashscreen.md.html#Splashscreen as rmc47 pointed out.
Answer: Although you can comment out this line of code in your project's AppDelegate.m file (which I generally don't recommend), you could also just suppress the warning using the following #pragma directives:
<code>#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
    /* ... code generating warning/deprecation message ... */
    return YES;
}
#pragma clang diagnostic pop
</code>


Sliding a div up/ down on click on mobiles and modal view same div on desktop

Question: I have seen a lot of examples for this question and most of them use jQuery for it. But I need a CSS alternative as I will have different placements and effects in different viewpoints.
For ex: When the user visit the page and clicks on the 'SIGN UP' button a div slides up from the bottom with a slight transparency and touch anywhere to slide it back down. Same should happen with the 'SIGN IN' button.
Just like this:

What I have achieved is very minimum as I am not good at CSS.
Fiddle: my work
and I checked example taken for some help.
CSS
html, body
    {
        width:100%;
        height: 100%;
    }
    body
    {
        background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 1)), url(../images/bg.jpg);
        background-attachment: fixed;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
    }
    #google
    {
        background-color: #D34836;
        width:100%;
        height:35px;
        margin-bottom:20px;
        border:none;
        color:#FFFFFF;
        font-family:'Source Sans Pro', sans serif;
        font-size:15px;
        border-radius:5px;
        -moz-border-radius: 5px;
        -webkit-border-radius:5px;
    }

    #container
    {
        margin-left:8%;
        margin-right:8%;
    }
    #greeting
    {
        width:100%;
        margin-top:28%;
        margin-bottom:32%;
    }
    #first_part, #second_part
    {
        text-align:center;
    }
    #first_part
    {
        font-size:38px;
        line-height:0.8;
        margin-bottom:30px;
    }
    #second_part
    {
        font-size:22px;
    }
    #signup, #signin
    {
        font-family:'Source Sans Pro', sans serif;
        font-size:15px;
        background-color:transparent;
        border: solid 1px;
        border-color:#FFFFFF;
        border-radius:5px;
        -moz-border-radius: 5px;
        -webkit-border-radius:5px;
        color:#FFFFFF;
        width:48%;
        height:35px;
    }
    #signin
    {
        margin-left: 3%;
  }
  #signup_container
  {
    color:#000000;
    background:#FFFFFF;
    height:50%;
    display: none;
  }
  #signup:focus + #signin
  {
    display: inline;
  }
  #signup:focus + #signin + #signup_container
  {
    display: block;
  }

Any kind of input will be of great help. If jQuery can be made to use I would still love to know the way and implement it.
UPDATE: I was hoping if breakpoint.js could be used for this purpose?
Comment: Using pure css I wouldn't say is possible as you need some way of triggering a change in classes then using transitions to move. At the very least you should have a collapsed div and open div CSS rules with 'transition' configured on the open div rule to change from one style to the other gracefully.

This toggle would be served as vanilla Javascript too meaning that it wouldn't cause any compatibility issues. (also your links need round brackets on them to work correctly. Check over the mini-markdown rules to see what I mean).
Comment: Changed the links properly
Answer: Your Jsfiddles links are dead/not working but i ll try to answer anyway.
i ll give you a generic example that you could use to do what you want.
.container_to_slide{
  position:absolute;
  transition: top 0.5s ease-in;
  top:-100%;
}

.container_to_slide.slide_up{
  top:0;
}

You can add the class slide_up to your div when you click on 'SIGN_UP' for example and remove the class when you click elsewhere.
(you have to modify top value to make your div hidden when slide_up isn't added and displayed when slide_up is).
You could do something like
sign_up.addEventListener('click',function(){
  document.getElementByClassName('.container_to_slide')[0].classList.add('slide_up');
}

document.addEventListener('click',function(){
 if(//code to detect click/touch outside your div//){
   document.getElementByClassName('.container_to_slide')[0].classList.remove('slide_up');
 }
}

Comment: Using javascript will cause the elements to function in the same way on other viewports but I would like it to animate in a different way. Such as on desktop on clicking SIGNUP will cause the div to have a modal effect whereas on mobiles the div has to slide up instead of modal effect.
Comment: In that respect I'd advise you lookup media queries and use max-width values to change between the different versions of the same named class. [css-tricks](http://css-tricks.com) has a number of articles on how to use them, just do a search on media queries to learn more.
Comment: Btw mediaqueries are accessible from javascript :http://www.sitepoint.com/javascript-media-queries/. You can also detect mobile devices from here so you can adapt your div behaviour depending on your media queries and if you are on a desktop or mobile device.
Comment: Am studying through it. Yet if a fiddle was available it would have been better.
Comment: https://jsfiddle.net/37h0gbtx/5/ this is an example with media queries and everything :) hope it helps
Comment: its kind of not working. Would you like to check my code? and carry on this conversation in chat? So that after it works out I can give you a upvote.


How do I find the number of lines of a file and input the number into the array size in Java?

Question: this is a relatively simple question but I'm stuck for one hour for some reason. What silly mistake am I making??? Please help!
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Program2 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("numbers.txt"));

        int count = 0;
        while (scanner.hasNext()) {
            count ++;
            scanner.nextLine();
        }
        int[] array = new int[count];
        for (int i = 0; i < array.length; i++) {
            array[i] = scanner.nextInt();
        }
        for (int i = array.length - 1; i >= 0; i--) {
            System.out.println(array[i]);
        }
    }
}

Comment: please be more specific about what isn't working, and what you're expecting to happen.
Comment: What errors are you getting? Have you debugged your code? What is your question?
Comment: You've done this already: (int[] array = new int[count];). You need to change scanner.hasNext() to scanner.hasNextLine()
Answer: Ohh... I had to scan the file twice -.- FML...
Answer posted:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class Program2 {
    public static void main(String[] args) throws FileNotFoundException {

        Scanner scanner = new Scanner(new File("numbers.txt"));

        int count = 0;
        while (scanner.hasNext()) {
            count ++;
            scanner.nextLine();
        }

        Scanner scanner1 = new Scanner(new File("numbers.txt"));

        int[] array = new int[count];
        for (int i = 0; i < array.length; i++) {
            array[i] = scanner1.nextInt();
        }
        for (int i = array.length - 1; i >= 0; i--) {
            System.out.println(array[i]);
        }
    }
}

Comment: And this is a limitation of arrays.  An ArrayList would be much better, as you don't need to specify the size when you make one.
Answer: I'm not very familiar using Scanner, i'd rather prefer user BufferReader. Here es my code, let's see if it's useful to solve your problem.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class CoountingLines {

    public static void main(final String[] args) throws FileNotFoundException {

        final BufferedReader br = new BufferedReader(new FileReader(new File("/Volumes/nuquer/work/numbers.txt")));
        String line;

        Integer count = 0;
        final HashMap<Integer, String> map = new HashMap<Integer, String>();
        try {
            while ((line = br.readLine()) != null) {
                map.put(count, line.toString());
                count++;
            }

            final int[] array = new int[count];
            for (int i = 0; i < array.length; i++) {
                array[i] = new Integer(map.get(i));
            }

            for (int i = array.length - 1; i >= 0; i--) {
                System.out.println(array[i]);
            }

        } catch (final IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


I need to show that if $K$ is of characteristic $0$,the algebra $A$ has a primitive generator.

Question: Let $K$ be a field and $A$ a reduced K-algebra of finite dimension over $K$.
I need to show that if $K$ is of characteristic $0$, $A$ has a primitive generator (i.e. $A=K[x], x \in A$)
I've proved that $A$ is isomorphic to a finite product of extensions of finite degree of $K$ (denote them $L_i$).
Then, the hint given is to find a set of primitive generators $ (x_i)$ for these extension fields $L_i$ over $K$ whose minimal polynomials over $K$ are pairwise distinct and then take $x=(x_2, x_2, \dots x_n)$.
But I don't know how to use it. In particular, I don't see why we can always field generators whose minimal polynomials are pairwise distinct. Help is much appreciated.
Answer: If $L_i = K(x_i)$, then $L_i=K(x_i+c)$ for any $c \in K$ (and since $char(K)=0$, we have enough $c$'s to choose from) yields another primitive element with another minimal polynomial.
So you can assume $A = L_1 \times \dotsc \times L_n$ with $L_i = K(x_i)$, the $x_i$ having distinct minimal polynomials $f_i \in K[T]$. In particular they are pairwise co-prime, since they are all irreducible.
Choose an element $a = (a_1, \dotsc, a_n) \in A$ and write $a_i = h_i(x_i)$ with some polynomials $h_i \in K[T]$
What we need to show is the following: There is one single polynomial $H \in K[T]$ with $a_i = H(x_i)$ for all $i$ (Then $a = H(x)$ with your choice of $x$). This is equivalent of solving the system of congruences:
$$H \equiv h_i \mod f_i, ~ i = 1, \dotsc, n$$
Hence the Chinese Remainder Theorem completes the proof.
Comment: Thanks. But what is $f_i$?
Comment: I have called the minimal polynomials $f_i$.


Interpretation of partial dependence plots for multinomial GBM

Question: I've been a big fan of the gbm package for some time, but am having difficulty understanding the output from the partial dependence plots in the case for multinomial classification problems.
Below is the partial dependence plot for 3 of the many variables I'm considering:

My problem is that the probability for 'Good' is always much higher than the others (including on variables not pictured here), but it's not overly prevalent in the data OR in the predictions from the model. Here is some further output to clarify that point:
<code>Confusion Matrix and Statistics

          Reference
Prediction  BAD MIDDLE GOOD
    BAD     875    107  163
    MIDDLE  150   1016  231
    GOOD    396    209 1651

Overall Statistics

               Accuracy : 0.7382
                 95% CI : (0.7255, 0.7506)
    No Information Rate : 0.4262
    P-Value [Acc > NIR] : < 2.2e-16

                  Kappa : 0.5961
 Mcnemar's Test P-Value : < 2.2e-16

Statistics by Class:

                     Class: BAD Class: MIDDLE Class: GOOD
Sensitivity              0.6158        0.7628      0.8073
Specificity              0.9200        0.8901      0.7802
Pos Pred Value           0.7642        0.7273      0.7318
Neg Pred Value           0.8505        0.9071      0.8450
Prevalence               0.2962        0.2776      0.4262
Detection Rate           0.1824        0.2118      0.3441
Detection Prevalence     0.2386        0.2912      0.4702
Balanced Accuracy        0.7679        0.8264      0.7938
</code>
So while the model is able to correctly classify many of the targets as 'Neutral/Middle' (forgive my labelling), the partial dependence plots would suggest this hardly ever happens...
I'm guessing there is something obvious I have missed.. Any insight or thoughts would be hugely appreciated!
Answer: I would like more clarity on your data, but have this to work with.
Assumptions:

the clusters for "good", "neutral", and "bad" are the target disposition for the classifier
the variables "a", "b", and "c" are the independent variables trying to predict the class
Answer:
It looks like this is a multivariate nominal logistic, so there are more that 2 levels of output.  They use a "winner takes all" approach so the values aren't as compatible.  The highest probability value class wins, even if the expression gives the odds as 0.01, 0.001, and 0.0001.  It is normalized by the sum.  I don't think that is being shown well in your figure.
Note: There is a deep connection between a Classification tree and a multi/nominal regression.  They might not be as mutually exclusive as they might seem.  If it is outputting probability of membership, then it isn't simply breaking on a line.  It may be that the probability is a supplied target, but that just means there are two connections, one at a superficial level and one a deep level.
Comment: The model was actually a boosted decision tree, but I believe your answer is still valid and reasonable.


SSH Port forward with secret file(mac)

Question: I have a unique issue where I need Tableau to connect to a Postgres Server under a Bastion Host in AWS. I usually try to
ssh -i key.pem  ec2-user@bastion_host
But I wish to know how I can port forward ssh to 5430 so I can do ssh -R 5430:localhost:5430 bastion host but connect . I am kind of confused about the whole setup of how I can ssh with the secret file and still port forward to my localhost so i can connect tableau to localhost:5430. Would appreciate some help here.
Answer: Here is the command to reset the port to one other than the default of 80/443.
tsm topology set-ports --node-name node --port-name gateway:primary --port-value nn
Article with more detail found here
Comment: Okay, to be fair, that could be also the question. I understand it the way, that the OP is looking only for forwarding the ssh port (already at 5430)
Comment: Where is the relevance to the question?
Comment: If you want tableau server to use a different port like 5430, this is the command to do so. It appears this is what the OP is looking for when I read the `so i can connect tableau to localhost:5430` portion of the question.
Comment: thanks for clarifying @jeb. I do have to admit, I was only looking at it from that part of the question without much knowledge of ssh.

SSH Port forward with secret file(mac)


GCP compute scp error: You do not currently have an active account selected

Question: I am trying to transfer a folder from my local machine to a VM in gcp
I am running
gcloud auth login
gcloud config set account 'my-gmail-account'
sudo gcloud compute scp path/to/folder $VM_ID:$REMOTE_DIR --project=$PROJECT_ID --recurse

It keeps giving me the error below even though I have logged in to the correct account. This problem has never happened when I am running on spare mac computer but it occurs on my ubuntu (I am not even sure if it is an os related issue).
ERROR: (gcloud.compute.scp) You do not currently have an active account selected.

Please run:

  $ gcloud auth login

to obtain new credentials.

If you have already logged in with a different account:

    $ gcloud config set account ACCOUNT

Answer: The config file are stored in a location related to your user (~/.config/gcloud/).
If you change the current user, you change the current user-config location. In your code you configure GCLOUD with your user account and you use it with the ROOT account. It fails, it's normal.
Perform all your command with sudo, or without. But not mix the two.


how to set the height of div tag using css

Question:
Possible Duplicate:
DIV width and height wont resize when setting innerHTML?

I have a div tag and it has text written as inner HTML, like this for example:

Some text. Some text. Some text. Some text. Some text. Some text. Some text. Some text.........

The inner HTML has a long text. Under the div tag I have kept an anchor tag. The problem is, when I shorten the height of div tag, say to 200px then the anchor tag comes over the inner HTML of div tag.
But, I want that when I shorten the height of div tag the inner HTML should also have the same height. I mean the anchor tag will appear just below the div tag and the div tag will have 200px height. I have googled around but didn't got much help. I hope I have made myself clear. If you have any doubts ask me please. I need help.
Comment: If it's solved, accept the answer that gives the solution.
Comment: Try adding a http://jsfiddle.net/ so we can better understand your problem.
Comment: And could you show your actual HTML? Or at least something that accurately represents your actual HTML?
Comment: heres the jsfiddle.net link http://jsfiddle.net/TtG6C/
Comment: heres the answer http://stackoverflow.com/questions/1798926/div-width-and-height-wont-resize-when-setting-innerhtml :p
sorry folks
Comment: Hey Check to this http://jsfiddle.net/rohitazad/TtG6C/8/ working fine...
Answer: you need to set the height in % rather than px; so change your anchor tag height in % means height: 5% this will probably solve your problem.
Answer: set position property of your anchor tag to be relative
a#MyA
{
  top:100px;
  position:relative;
}

Answer: I have got the solution for this problem:
DIV width and height wont resize when setting innerHTML?
You have to add the overflow property for the div tag.
Answer: I am not sure if i understant your problem correctly but at least in your jsfiddle link there was a lot of typos, corrected some and here's the results

Some Text. Some Text. Some Text. Some Text. Some Text. Some Text.Some Text.Some Text. Some Text. Some Text.Some Text.......

Read More

Also added some colors for easier debugging.
Take a look at it.
Check this too, another possibility what you are trying to do...
div#aa {
    height: 100px;
    background-color: #f00;
    overflow: hidden;
}

a {
    background-color: #aaf;
}

Comment: thanks but i have got the answer myself :) i have commented the answer on my question
Comment: @subhojit777 If any of answers would solve your problem you should accept it, stackoverflow is wiki after all and someone else may have same problem. Or maybe edit your first post to clearly point where others can found answer. Comments are not intended for that.


Jquery double click event is not working

Question: My requirement is to just double click a button.
HTML:
 <button id="btn-db" class="dbBtn" ></button>

Solutions tried:
  $("#btn-id").trigger("dblclick");

is not triggering double click event
Note: I've tried the same thing for single click,
  $("#btn-id").trigger("click");

Single click is triggering by invoking above statement in browsers console.
Comment: this may help you : https://stackoverflow.com/questions/9680290/double-click-function-in-jquery-is-not-working
Comment: Did you try  `.dblclick(...)`?
Comment: No. Give a example of to how to use it
Comment: @Chintan let me check
Answer: Try button.on("dblclick", ...). Here is an example.

var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("dblclick", function(){
  banner.addClass("alt")
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

Hello World

  <button>Change color</button>

Comment: Such a giant example for such a simple problem… :p
Answer: This is working:

$("#btn-id").on('dblclick', function() {
  console.clear();
  console.log("You double-clicked!");
});

$("#btn-id").trigger("dblclick");

<button id="btn-id" class="dbBtn">Double click</button>

I just noticed this is a typo error:
<button id="btn-db" class="dbBtn" ></button>: id should be btn-id in your code!
Hope it helps.


Let $A$ and $B$ be $n\times n$ matrices. Suppose all the eigenvalues of $A$ and $B$ are distinct.

Question:
Question: Let $A$ and $B$ be $n\times n$ matrices. Suppose all the eigenvalues of $A$ and $B$ are distinct. Prove or disprove the following statements.

$1$. If  $AB=BA$, then each eigen vector of $A$ is an eigen vector of $B$.

$2$. If $AB-BA=2B$ and $\lambda$ is an eigen value of $A$ then $\lambda-2$ is also an eigen value of $A$.

Consider $2\times 2$ matrices as follows
$$A=\begin{pmatrix}
2 & 0\\
0 & 1\\
\end{pmatrix}$$ and
$$B=\begin{pmatrix}
1 & 0\\
0 & 0\\
\end{pmatrix}$$
then consequently we have $$AB=BA=\begin{pmatrix}
2 & 0\\
0 & 0\\
\end{pmatrix}$$
Subtracting the eigen values down the matrix and checking its eigen vectors satisfied $1$.Tried looking for more, they satisfied it, I doubt it being correct! Similar is the situation with $2$.
Thanks.
Comment: The question asks about all $n\times n$ matrices. For 2. just note that if $Ax=\lambda x$ for some $x\neq 0$, then $$(AB-BA)x = 2Bx \Leftrightarrow A(Bx) = (\lambda +2)Bx\quad \text{(assuming }Bx\neq 0\text{)} $$
Maybe $\lambda -2$ is an eigenvalue, I don't know at the moment.
Comment: What I meant to say with "assuming $Bx\neq 0$" part is that would allow the conclusion that $\lambda+2$ is an eigenvalue of $A$.
Comment: For 1. use the fact that the eigenspaces are one-dimensional.
Comment: I can see that $\lambda +2$ would be an eigenvalue in 2. Don't know about $\lambda -2$.
Comment: Thanks for your efforts @AlvinL. Didn't get your hint for 1. I mean how can I relate that eigenvectors of $A$ and $B$ are same? How $\lambda+2$? Please mention the matrices on which you were trying to get a conclusion :/
Answer: Part.1
$$Av_k=\lambda_k v_k\Rightarrow ABv_k=BAv_k=\lambda_kBv_k\Rightarrow Bv_k\in Ei(A,\lambda_k)$$
Since all eigenvalues of $A$ are distinct, $$\Rightarrow Dim(Ei(A,\lambda_k))=1\Rightarrow Bv_k=c \cdot v_k$$
Since $v_k\neq0\Rightarrow v_k$ is also an eigenvector of $B$.
Part.2
The problem says "all eigenvalues of $A$ and $B$ are distinct", there are maybe some ambiguities. Suppose $A$ has eigenvalues $a_1,...,a_n$, $B$ has eigenvalues $b_1,...,b_n$, Does the problem mean:
$|\{a_1,...,a_n,b_1,...,b_n\}|=2n$
or
$|\{a_1,...,a_n\}|=n,|\{b_1,...,b_n\}|=n,~|\{a_1,...,a_n,b_1,...,b_n\}|\le 2n$
Comment: Here "Distinct EigenValues" is ambigous : It could even mean A & B may ( or may not ) have repeated EigenValues but the Intersection of these two sets of EigenValues = { } ! In other words , A & B have no common EigenValues !


Alternative construction of Direct Limit

Question: The construction of the direct limit that I learned from Atiyah Macdonald is the following: Suppose we have a directed system $(M_i,\mu_{ij})$ of $A$ - modules and $A$ - module homomorphims  over a directed set $I$. Let $D$ be the submodule generated by elements of the form $x_i - \mu_{ij}(x_i)$. Then
$$\varinjlim M_i \stackrel{\text{def}}{\equiv} \bigoplus_{i\in I} M_i/ D.$$
Now I am trying to see how this is equivalent to the wikipedia definition given here. In particular, what I don't understand about the wikipedia definition is that the equivalence relation $\sim$ defined there is between individual elements, e.g. say whether $x_i \sim x_j$. How does one "extend this linearly" to an equivalence relation on $\bigsqcup M_i$ which is the set of all sums $\sum_{i \in I}x_i$ where $x_i \in M_i$ and all but finitely many $x_i$ are zero?
Comment: By "extend linearly", the Wikipedia page means that you add the equations $x_i = x_j$ as *relations* to the infinite direct sum $\bigoplus M_i$.
Comment: @JimBelk What do you mean by equations "$x_i = x_j$"? Do you mean that if say $x_1 \sim x_2$ and $x_3 \sim x_4$ then $x_1 + x_3 \sim x_2 + x_4$? Conversely if $x_1 + x_3 \sim x_2 + x_4$ this means that $x_1 \sim x_2$ and $x_3 \sim x_4$? If you post an answer I will definitely accept it.
Comment: Stated differently, you take the congruence relation generated by the individual pairs $x_i \sim x_j$.  (See http://en.wikipedia.org/wiki/Congruence_relation)
Comment: @JimBelk I know how to go from individual elements being equivalent to sums being equivalent. But what about the other way round? So am I correct in saying that in the direct sum, say $x_1 + x_2 + x_3 \sim x_4 + x_5 + x_6$ is $x_1 \sim x_4$, $x_2 \sim x_5$ and $x_3 \sim x_6$?
Comment: I have posted an answer below that might help to clarify things.
Comment: There is already an accepted answer, but FWIW, Rotman (An Introduction to Homological Algebra, 2nd edition) proves exactly this on p.245, with full detail. [I find myself citing this book here over and over again... I love it!]
Comment: @BrunoStonek I already had a look at Rotman's text and it is quite good. I read that section too. Thanks for the heads up!
Answer: Here's how I would present the construction given in Wikipedia.
Suppose $(M_i,\mu_{ij})$ is a directed system of modules. We begin by taking a disjoint union of the underlying sets of the $M_i$; in order to "keep them disjoint", the usual method is to "paint" each set with its index $i$ to ensure that if $i\neq j$, then the sets are disjoint. That is, we consider the set
$$\mathcal{M} = \bigcup_{i\in I}(M_i\times\{i\}).$$
The elements of $\mathcal{M}$ are pairs of the form $(x,i)$, where $i\in I$ and $x\in M_i$.
Note that $\mathcal{M}$ is not a module, at least not one with any natural structure: the operations we have on hand (the ones for the different $M_i$) are not defined on all of $\mathcal{M}$, they are only defined on proper subsets of $\mathcal{M}$.
We now define an equivalence relation on $\mathcal{M}$ as follows: $(x,i)\sim(y,j)$ if and only if there exists $k\in I$, $i,j\leq k$ such that $\mu_{ik}(x) = \mu_{jk}(y)$ in $M_k$. It is not hard to verify that this is an equivalence relation.
Let $\mathbf{M}$ be the set $\mathcal{M}/\sim$. Denote the equivalence class of $(x,i)$ by $[x,i]$.
We now define a module structure on $\mathbf{M}$: we define a sum on classes by the rule
$$ [x,i] + [y,j] = [\mu_{ik}(x)+\mu_{jk}(y),k]$$
where $k$ is any element of $I$ such that $i,j\leq k$. One needs to prove that this is well defined and does not depend on the choice of the $k$. Suppose first that $k'$ is some other element with $i,j\leq k'$. Let $\ell$ be an index with $k,k'\leq \ell$; then
$$\begin{align*}
\mu_{i\ell}(x) + \mu_{j\ell}(y) &= \mu_{k\ell}(\mu_{ik}(x))+\mu_{k\ell}(\mu_{jk}(y))\\
&= \mu_{k\ell}(\mu_{ik}(x) + \mu_{jk}(y)).
\end{align*}$$
Therefore, $[\mu_{ik}(x)+\mu_{jk}(y),k] = [\mu_{i\ell}(x)+\mu_{j\ell}(y),\ell]$. By a symmetric argument, we also have
$$[\mu_{ik'}x) + \mu_{jk'}(y),k'] = [\mu_{i\ell}(x) + \mu_{j\ell}(y),\ell],$$
so the definition does not depend on the choice of $\ell$.
To show it does not depend on the representative either, suppose $[x,i]=[x',i']$ and $[y,j]=[y',j']$. There exists $m$, $i,i'\leq m$ with $\mu_{im}(x)=\mu_{i'm}(x')$, and there exists $n$, $j,j'\leq n$, with $\mu_{jn}(y)=\mu_{j'n}(y')$. Pick $k$ with $m,n\leq k$. Then
$$\begin{align*}
[x,i]+[y,j] &= [\mu_{ik}(x)+\mu_{jk}(y),k]\\
            &= [\mu_{mk}(\mu_{im}(x)) + \mu_{nk}(\mu_{jn}(y)),k]\\
            &= [\mu_{mk}(\mu_{i'm}(x')) + \mu_{nk}(\mu_{j'n}(y')),k]\\
            &= [\mu_{i'k}(x') + \mu_{j'k}(y'),k]\\
            &= [x',i'] + [y',j'],
\end{align*}$$
so the operation is well-defined.
It is now easy to verify that $+$ is associative and commutative, $[0,i]$ is an identity (for any $i$) and that $[-x,i]$ is an inverse for $[x,i]$, so this operation turns $\mathbf{M}$ into an abelian group.
We then define a scalar multiplication as follows: given $r\in R$ and $[x,i]\in\mathbf{M}$, we let $r[x,i] = [rx,i]$. Again, one needs to show that this is well-defined (easier than the proof above), and verify that it satisfies the relevant axioms (not hard) to show that this endows $\mathbf{M}$ with the structure of a left $R$-module.
Now note that the maps $\mu_i\colon M_i\to \mathbf{M}$ given by $\mu_i(x) = [x,i]$ is a module homomorphism. The module $\mathbf{M}$ together with the maps $\mu_i$ are a direct limit of the system.
(The same construction works for Groups, Rings, etc).
There is no "linear extension" of the equivalence relation. Rather, we define an operation on $\mathcal{M}/\sim$, since $\mathcal{M}$ (being a disjoint union of the underlying set of the original modules) is not a module itself: it does not even have a total operation defined on it, just a bunch of partial operations.
Comment: @BenjaminLim: I find it very frustrating that your responses seem to be basically, "Okay, but let's ignore everything you wrote and answer me this question instead." Especially when "this question" is the repetition of something that I have already pointed out is nonsensical. $\mu_{ik}-\mu_{jk}$ is not an element, it's not even a sensical expression: $\mu_{ik}$ and $\mu_{jk}$ are **functions**, with **different domains**. They are not elements that can be mapped into the direct sum, and they are not functions whose difference can be computed. *The formula is nonsense.* GIGO.
Comment: @BenjaminLim: Then you need to keep the fact that "$a$" **doesn't** mean $a$, it means $(\ldots,a,\ldots)$ in mind all the time. I'm sure Atiyah and MacDonald can keep that fact straight without getting confused. I am fairly sure you cannot, given the evidence at hand. So make it *explicit* by using the canonical embeddings and *writing them out*.
Comment: Say we do $\bigoplus/C$ where $C$ is the submodule generated by the union of kernels of $\mu_{ik} - \mu_{jk}$ for any triple $i,j,k$ such that $i \leq k$ and $j \leq k$. Then I think what we get is not different from what you constructed above. However the problem now is how do we define kernel of $\mu_{ij} - \mu_{ik}$? The domains are not even the same.......
Comment: @BenjaminLim: We do **not** define $C$ to be the submodule generated by "kernels of $\mu_{ik}-\mu_{jk}$". We define $C$ to be the submodule generated by all elements of the form $\mu_i(a)-\mu_j(\mu_{ij}(a))$, where $\mu_k$ is the embedding of $M_k$ in the $k$th component, and we consider all pairs $i\leq j$ and all $a\in M_i$. See [this previous question](http://math.stackexchange.com/q/81447/742). The reason you are confused is because you are mixing the two constructions. The $\mu_{ij}$ are not maps into the direct sum; they are maps between direct **summands.** (cont)
Comment: @BenjaminLim (cont) What you need to do is relate the embeddings of the direct summands into the direct sum with the maps $\mu_{ij}$, and that is what $C$ needs to do: it provides the bridge between the maps $\mu_{ij}$ and the canonical embeddings.
Comment: I see what you mean. Perhaps I just have to go with that construction of the direct limit that you used above.
Comment: @BenajminLim: The **correct** way to do it is *precisely* the "usual submodule": you want to mod out by all pairs $(\ldots,a,\ldots,-b,\ldots)$ where $a\in M_i$, $b\in M_j$, and $\mu_{ik}(a)=\mu_{jk}(b)$. This pair is the difference of two generators of $C$: $$(\ldots,a,\ldots,-b,\ldots) = (\ldots,a,\ldots,-\mu_{ik}(a),\ldots) - (\ldots,-\mu_{jk}(-b),\ldots,b).$$And such a pair includes, as a special case, each generator of $C$ (when $j=k$).
Comment: Thanks Arturo I see what you mean! That makes a lot of sense to me. Just one thing; how do you know that there is a $k$ such that $\mu_{ik}(a) = \mu_{jk}(b)$?
Comment: @BenjaminLim: We want to mod out by all pairs for which *there exists* such a $k$, no? You don't start with a pair and try to find a collision, you start with a collision and find the corresponding pair.
Comment: You are right. Now I think what I want to do next is show that if $C$ is the submodule generated by elements $a - \mu_{ij}(a)$, then this is equal to the submodule generated by elements $ a - b$ such that $\mu_{ik}(a) - \mu_{jk}(b)$. Sorry if I left you frustrated, I have been frustrated the whole day myself trying to get around these things!
Comment: @BenjaminLim: You are still using the notation badly, which invites confusion. $a$ is in $M_i$. $\mu_{ij}$ is in $M_j$. *It makes no sense to write $a-\mu_{ij}(a)$.*. You have to first embed $M_i$ and $M_j$ into the direct sum, so you need to write it as $\mu_i(a) - \mu_j(\mu_{ij}(a))$ (or whatever letter you want to use for the embedding of $M_i$ into $\oplus_k M_k$). The most likely reason you are frustrated "trying to get around these things" is that you keep writing things that are nonsense to begin with. *Be careful!* GIGO is *always* true in mathematics.
Comment: I should have said "submodule of $\bigoplus M_i$. I think showing those two submodules of $\bigoplus M_i$ are equal, I should be done.
Comment: @BenjaminLim: No, the problem is much more than simply not saying "submodule of the direct sum." The very elements you are writing **don't exist**. "$a-\mu_{ij}(a)$" is **nonsense**: you are trying to take the difference of two elements that live in **different** modules. $a$ lives in $M_i$. $\mu_{ij}(a)$ lives in $M_j$. There are no operations between elements of $M_i$ and elements of $M_j$ for $i\neq j$. They are **different** modules. You need to **first** map your elements into the direct sum before they can interact. Until you do that, you just keep putting garbage in, getting garbage out
Comment: Let us make this precise. What we do is first we send $a$ in $M_i$ to its canonical image in the direct sum, which will be $(.....,a,...)$. Similarly for $\mu_{ij}(a)$. Then $a - \mu_{ij}(a)$ will be $(.....,a,....) - (....,\mu_{ij}(a),...)$. By the way in Atiyah Macdonald they mention the submodule of $\bigoplus M_i$ generated by elements of the form $x_i - \mu_{ij}(x_i)$, so they must mean what I said above then.
Comment: Thanks. In future, whenever I write write $x_i$ I will say explicitly it means $(...,x_i,....)$. I guess people write just $x_i$ because it is less cumbersome than to write $(....,x_i,...)$
Comment: @BenjaminLim: Which is *precisely* why I've been suggesting (through example) the use of the canonical embedding functions that map $M_i$ into $\oplus M_j$ instead. Just saying "it means something else" is not going to clear up your confusion, because you are still going to be using the notation that engages in the abuse of notation, and this abuse is helping to confuse you. Give names to the canonical embeddings (I suggest $\mu_i$ to match the names of the structure maps) and use *those*.
Comment: I have an written up an answer below. Please take a look at it.
Comment: There's a typo in the definition of the equivalence relation; $\mu_{ik}(x) = \mu_{jk}(x)$ should be $\mu_{ik}(x) = \mu_{jk}(y)$.
Comment: @HansLundmark: Thank you; fixed.
Answer: All right, there are several things going on here.  First of all the direct limit of a sequence of algebraic objects can be defined in two equivalent ways.  The first way, the direct limit is a quotient of the direct sum of the algebraic objects:
$$
\bigoplus_{i\in I} M_i \bigg/\equiv
$$
where $\equiv$ is a certain congruence relation defined on the direct sum.  In particular, $\equiv$ is the congruence relation generated by pairs of the form $x_i \equiv \mu_{ij}(x_i)$.  (Here, the congruence relation generated by a certain set of pairs means the intersection of all congruence relations that contain the pairs).  This quotient can also be described as the quotient by the submodule $D$ which you have defined, but I have described it as a congruence relation to mimic Wikipedia's definition.
Alternatively, the set of elements of the direct limit can be described as a quotient of the disjoint union
$$
\bigsqcup_{i\in I} M_i \bigg/\sim
$$
where $\sim$ is the equivalence relation generated by all pairs of the form $x_i\sim\mu_{ij}(x_i)$.  (Again, the equivalence relation generated by a certain set of pairs means the transitive, reflexive, symmetric closure of the relation defined by the pairs.)  The Wikipedia article really does mean disjoint union here -- not direct sum.  Naively, this just defines a set of equivalence classes, but there is a natural module structure on this set inherited from the module structure on the $M_i$'s (though this requires some proof).
The first definition is more algebraic, but the second definition makes it clearer that every element of the direct limit actually comes from one of the $M_i$'s.
To show these are equivalent, you just want to construct an isomorphism directly on the level of elements.  This is basically the same as starting from the Atiyah-McDonald defintion and proving the following theorem:
Theorem. Let $L = \bigoplus_{i\in I} M_i\Big/D$ be the direct limit of the $M_i$'s.  For each $i\in I$, let $L_i$ denote the canonoical image of $M_i$ in $L$.  Then $L = \bigcup_{i\in I} L_i$.
Edit: Just in case it helps, here are a few examples of direct limits of $\mathbb{Z}$-modules (abelian groups) that are fairly illustrative.  The first is the limit of the sequence
$$
\textstyle\mathbb{Z} \;\longrightarrow\; \frac{1}{2}\mathbb{Z} \;\longrightarrow\; \frac{1}{4}\mathbb{Z} \;\longrightarrow\; \frac{1}{8}\mathbb{Z} \;\longrightarrow\; \cdots
$$
where all of the maps are inclusion maps, and $q\mathbb{Z}$ denotes the integer multiples of $q$.  The direct limit of this sequence is the group $\mathbb{Z}\bigl[\frac{1}{2}\bigr]$ of dyadic fractions.  The second example is the limit of the sequence
$$
\textstyle\mathbb{Q}\big/\mathbb{Z} \;\longrightarrow\; \mathbb{Q}\big/\frac{1}{2}\mathbb{Z} \;\longrightarrow\; \mathbb{Q}\big/\frac{1}{4}\mathbb{Z} \;\longrightarrow\; \mathbb{Q}\big/\frac{1}{8}\mathbb{Z} \;\longrightarrow\; \cdots
$$
where each of the maps is the natural quotient map.  The direct limit of this sequence is the quotient $\mathbb{Q}\big/\mathbb{Z}\bigl[\frac{1}{2}\bigr]$.
These examples are illustrative, because the first shows just the inclusion aspect of direct limits, while the second shows just the quotient aspect.  A more general direct limit will have both aspects, since a typical homomorphism is neither injective nor surjective.
Comment: @BenjaminLim: Maybe [this related answer](http://math.stackexchange.com/a/81484/742) can help you see how it is done. $a_i\sim b_j$ and $c_k\sim d_{\ell}$, there is $n\geq i,j$ with $\mu_{in}(a_i)=\mu_{jn}(b_j)$; there is $m\geq k,\ell$ with $\mu_{km}(c_k)=\mu_{\ellm}(d_{\ell})$. Let $t\geq n,m$. Then $\mu_{it}(a_i)+\mu_{kt}(c_k) = \mu_{nt}(\mu_{in}(a_i))+\mu_{mt}(\mu_{km}(c_k)) = \mu_{nt}(\mu_{jn}(b_j))+\mu_{mt}(\mu_{\ell m}(d_{\ell})) = \mu_{jt}(b_j)+\mu_{\ell t}(d_k)$.
Comment: Thanks for your answer. Now suppose we forget the wikipedia definition for now, say I have an equivalence relation $\sim$ that says that $x_i \sim x_j$ iff there is $k\geq i,j$ such that $\mu_{ik}(x_i) = \mu_{jk}(x_j)$. I want to extend this to an equivalence relation on $\bigoplus M_i$. Now I looked up congruence relations, but they only tell you if say $a \sim b$, $c \sim d$ then $a + c \sim b + d$. What I am looking for is the reverse: How do we tell when say $a + c \sim b + d$?
Comment: @BenjaminLim In general, there is no algorithm to tell whether a given pair is in the congruence relation generated by a given set of pairs.  Indeed, a presentation of a group is essentially just a congruence relation generated by certain pairs on a free group, and the word problem for groups is unsolvable.
Comment: @BenjaminLim However, the present case isn't quite as difficult.  For a direct limit, you just need to keep mapping the sum forward under the $\mu_{ij}$'s.  Two sums will be equal if and only if their images are eventually equal in the sequence of $M_i's$.
Comment: @JimBelk Thanks for your all your input.
Comment: @JimBelk Actually $\Bbb{Z}[1/2]$ and the maps out of it have the universal property of the direct limit so have to be isomorphic to the direct limit.
Comment: @BenjaminLim More generally, if $M_1 \leq M_2 \leq M_3 \leq \cdots$ is an ascending chain of submodules of a module $A$, then the direct limit of the sequence of $M_i$'s is simply the union of the $M_i$'s.
Answer: I would guess that the "disjoint union" used in the wiki article really means coproduct in the category in question (in fact, I know it does) and it just so happens that the coproduct in $R\text{-}\mathbf{Mod}$ is direct sum. The equivalence relation is then just exactly the one you discussed.
Comment: I know, but how do we define whether say $x_1 + x_3 + x_4 \sim x_5 + x_6 + x_7$? The "extending linearly" bit is what is confusing me.
Comment: My guess would be that since you are dealing with directed sets you can just put both sides in some bigger one (find a "max" of $A_1,A_3,A_4$ on your left side and put it in that set)
Comment: What do you mean by this? Can you explain a bit more?
Comment: @BenjaminLim If $x\in M_i$ and $y\in M_j$ then first find $k\geq i,j$ and define $x+y= f_{ik}(x)+f_{jk}(y)$.
Comment: @azarel right I get that, but then how does this relate to showing whether $x + y \sim z +w$ say?
Comment: @BenjaminLim $\sqcup M_i$ is just the disjoint union of $M_i$'s there are no formal sums from different modules.  It is clearly stated in the wikipedia page.
Comment: @azarel Look at alex's answer above about how coproduct in $R - mod$ is the direct sum.
Comment: @BenjaminLim From wikipedia "The underlying set of the direct limit, , of the direct system  is defined as the disjoint union of the 's modulo a certain equivalence relation"
Comment: @azarel If you look at the wiki page on disjoint union, the disjoint union is also the set consisting of elements of the  form $\sum_{i \in I} a_i$ where $a_i \in A_i$. http://en.wikipedia.org/wiki/Disjoint_union
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/3134/discussion-between-azarel-and-benjamin-lim)


Error building a request and initializing client for OkHttp3 on Kotlin

Question: New to OkHttp, however I was able to track the following errors:
        val url = "https://api.letsbuildthatapp.com/youtube/home_feed"
        try {
            val request = Request.Builder().url(url).build()
        } catch(err: Error){
            println("Request Error: $err")
        }

This generates: "Request Error: java.lang.BootstrapMethodError: Exception from call site #5 bootstrap method"
        try {
            OkHttpClient()
        } catch(err: Error){
            println("Client Error: $err")
        }

This returns an error "Client Error: java.lang.NoClassDefFoundError: okhttp3.internal.Util"
Any help with these will be greatly appreciated.  TIA
Answer: It looks like you have an issue with the dependency and/or JVM. The java.lang.BootstrapMethodError may mean there is something work with the Java Runtime Environment. Please consider upgrading Java to the stable version (e.g. 11 or 1.8)
The NoClassDefFound error means you miss some classes from the OkHttp library in your project. There are likely to be several transitive dependencies from the .jar that you have in your project. Probably Gradle or Maven project will help to have all dependencies resolved correctly.


Public Key Authentication not work on Windows 10 Professional

Question: I have been trying to configure OpenSSH for my Windows 10 Professional Edition media server.  I can get normal password login working without issue but I am trying to set up public key authentication.
I have edited my sshd_config file to allow for public key authentication.  The client and the server are running ssh-agent.  I've copied and pasted my SSH public key from the client computer into the file C:\ProgramData\ssh\administrators_authorized_keys since the account is an administrator account.
Permissions on the above file are set the same as the other key files in the directory of being just SYSTEM and Administrators both with full control and no one else is listed.
I added debug logging and when I try to connect using the public key, I get this:
debug1: userauth-request for user uther service ssh-connection method none [preauth]
debug1: attempt 0 failures 0 [preauth]
debug1: user uther matched group list administrators at line 84
debug1: userauth-request for user uther service ssh-connection method publickey [preauth]
debug1: attempt 1 failures 0 [preauth]
debug1: userauth_pubkey: test pkalg ssh-rsa pkblob RSA SHA256:jcQNaVuxvH90SIh4zu8xduBqJaav1WFQJIov3hiFSFM [preauth]
debug1: trying public key file C:\\ProgramData\\ssh\\administrators_authorized_keys
Failed publickey for uther from 10.0.0.24 port 60432 ssh2: RSA SHA256:jcQNaVuxvH90SIh4zu8xduBqJaav1WFQJIov3hiFSFM
debug1: userauth-request for user uther service ssh-connection method keyboard-interactive [preauth]

I'm at a loss of how to resolve this.  I literally cut and paste the text from id_rsa.pub on the client to the server in the administrators authorized keys file using Remote Desktop.  There doesn't seem to be a permissions error, I can't figure out why it won't authenticate.
I would appreciate any help anyone could offer in getting this working.  It isn't critical, SSH isn't exposed to the Internet, but some of the scripts I use would do much better with public key authentication.
I should also note when I set up the server I used my Microsoft account, I have been wondering if that has anything to do with it, so I may try to set up a straight local account and see if that fixes it.
EDIT:  I attempted to create a local user account, but I cannot.  Even when I try to use control userpasswords2 the box comes up but all the options to create an account are disabled.  I'm thinking this must be because I have Windows 10 Professional and not some higher and most expensive edition.
Comment: Check the logs on the server.
Comment: I did, it only said that the authentication failed.
Answer: I finally solved the problem by commenting out the lines:
Match Group administrators
       AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

Then I placed the authorized keys into the normal file ~\.ssh\authorized_keys like any other time I've used ssh.  I saw this didn't work for a lot of people when I did my initial research and had discounted it.
Comment: ...this and I also had to declare `AllowUsers firstname.lastname@example.com` in config
Answer: Use this sequence of commands in PowerShell to correct permission of administrators_authorized_keys
$acl = Get-Acl C:\ProgramData\ssh\administrators_authorized_keys
$acl.SetAccessRuleProtection($true, $false)
$administratorsRule = New-Object system.security.accesscontrol.filesystemaccessrule("Administrators","FullControl","Allow")
$systemRule = New-Object system.security.accesscontrol.filesystemaccessrule("SYSTEM","FullControl","Allow")
$acl.SetAccessRule($administratorsRule)
$acl.SetAccessRule($systemRule)
$acl | Set-Acl

Comment: YESSSS
You made my day
i was wondering how to do this on windows as its mostly permissions issues with ssh connections.
Answer: In addition to the answer by Sergio Cabral, the documentation provides another option to apply the appropriate permissions:
icacls.exe "C:\ProgramData\ssh\administrators_authorized_keys" /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F"

Answer: @Sergio Cabral's answer didn't work for me, but this did:
$systemRule = New-Object system.security.accesscontrol.filesystemaccessrule("SYSTEM","FullControl","Allow")
$administratorsRule = New-Object system.security.accesscontrol.filesystemaccessrule("Administrators","FullControl","Allow")
$acl = Get-Acl C:\ProgramData\ssh\administrators_authorized_keys
$acl.SetAccessRule($systemRule)
$acl.SetAccessRule($administratorsRule)
$acl.SetAccessRuleProtection($true, $false)
$acl | Set-Acl

Answer: $systemRule = New-Object system.security.accesscontrol.filesystemaccessrule("SYSTEM","FullControl","Allow")
$administratorsRule = New-Object system.security.accesscontrol.filesystemaccessrule("Administrators","FullControl","Allow")
$acl = Get-Acl C:\ProgramData\ssh\administrators_authorized_keys
$acl.SetAccessRule($systemRule)
$acl.SetAccessRule($administratorsRule)
$acl.SetAccessRuleProtection($true, $false)
$acl | Set-Acl


jquery hover() is not triggered when hovered first time

Question: Menu is loaded through ajax and hover function is associated to each li using live(). But still it is not triggering for first time. From second time onwards it is triggering properly
Main file

        <title>
            test
        </title>

            <form method="post">
                Load Menu
            </form>

                none

Menu file
<?php
echo "

one

two

 three

four

 five

six

 seven

 eight

 nine

";

?>
Answer: Get rid of the live and append the action on success
jQuery(document).ready(function() {
    jQuery('.loadm').live('click', function(event) {
        $.ajax({
            // remove the line below and restore your url
            data: "html=" + $('#menufromajax').html() + '&delay=1',
            type: "POST",
            url: "/echo/html/",
            success: function(data) {
                $('#menu').html(data);

                $('.addchar:visible').each(function(index) {
                    $(this).hover(function() {
                        $("#result").html("Index is: " + index);
                    });

                });

            },
            error: function() {

            }
        });
    });
});

http://jsfiddle.net/ENEBB/3/
works even with a delay.
But seriously, there is no need for both the $(window).load and jQuery(document).ready, you can just do $(function() or jQuery(document).ready if you are running in noconflict mode.
And don't use '< script >' always define the type by adding type='text/javascript'


How to programmatically add a paragraph item to a user account?

Question: I already added the Check in/out History field to the user account, which has the check-in date and check-out date fields.
How can I programmatically add new items to Check in/out History?
I need to create some history for users.

Check-in date
Check-out date

04/05/21
05/07/21

03/05/20
04/14/20
Comment: Quite broad the question. What have you tried so far? Did you check for "programmatically create paragraph items" or similar? User entity is just another fieldable entity. Same as nodes. Most answers you'll find are for nodes. You just need to replace the node object with an user object then, done. When and where do you want to update the users? API call? Some hook that gets triggered in a particular situation?
Comment: for example I have field_history as paragraph in user account, and there are 2 fields in paragraph field_checkin_date, field_checkout_date, and I want on some action add new paragraph items, what should be my steps?
1. how reach paragraph field for user?
2. how add new paragraph item with 2 sub fields?
3. how append new item to paragraph?
Comment: Thanks to all, this code solve my task:
Comment: $paragraph = Paragraph::create(['type' => 'checkin_history', 'field_checkin' => $checkin_date,  'field_checkout' => format_date(time(), 'html_date')]);
$paragraph->save();

$current = $account->get('field_check_in_out_history')->getValue();
$current[] = array(
   'target_id' => $paragraph->id(),
   'target_revision_id' => $paragraph->getRevisionId(),
);

$account->set('field_check_in_out_history', $current);
$account->save();
Comment: where:
//field_check_in_out_history  -> field in user account
//checkin_history -> paragraph type
// field_checkin and field_checkout paragraph fields
Comment: Please update the question for clarification and to add details, please don't use comments for that. Next reader should get all relevant info at one glance.
Comment: And then please add an answer with your solution, and accept it, to help future readers to get the solution at one glance.
Answer: I have been able to achieve the task using the following code.
<code>$paragraph = Paragraph::create([
  'type' => 'checkin_history',
  'field_checkin' => $checkin_date,
  'field_checkout' => format_date(time(), 'html_date')
]);
$paragraph->save();

$current = $account->get('field_check_in_out_history')->getValue(); $current[] = [
  'target_id' => $paragraph->id(),
  'target_revision_id' => $paragraph->getRevisionId(),
];

$account->set('field_check_in_out_history', $current);
$account->save();
</code>

field_check_in_out_history is the user account field
checkin_history is the paragraph type
field_checkin and field_checkout are paragraph fields


Hibernate Reserved keyword escaping not working

Question: I am getting below error due to the use of MYSQL reserved keywords in hibernate models.
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'when, who, why) values ('ICL670A - Project Deliverable - HAQ 1 - FDA-IR', null, ' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:970) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1109) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at

I have below property set in my application.properties file, it used to work before, but now it's not working and I am unable to figure out why.
spring.jpa.properties.hibernate.globally_quoted_identifiers=true

Now I have to escape the columns manually in my model definition for it to work.
@Column(name = "`who`")
private String who;

@Column(name = "`when`")
private Date when;

@Column(name = "`why`")
private String why;

How can I further debug for the same? How can I ensure that this property is being picked up?
Answer: We are using multiple DB connections in our spring boot project. So all the hibernate properties need to be configured in the DataSourceConfigurationFile
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean idotdbEntityManager() {
    final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(idotdbDataSource());
    em.setPackagesToScan("com.novartis.idot.model");

    final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    final HashMap<String, Object> properties = new HashMap<>();
    properties.put("hibernate.physical_naming_strategy", SpringPhysicalNamingStrategy.class.getName());
    properties.put("hibernate.implicit_naming_strategy", SpringImplicitNamingStrategy.class.getName());
    properties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.hibernate.ddl-auto"));
    properties.put("hibernate.dialect", env.getProperty("spring.hibernate.dialect"));
    properties.put("hibernate.globally_quoted_identifiers", env.getProperty("spring.jpa.properties.hibernate.globally_quoted_identifiers"));
    properties.put("hibernate.id.new_generator_mappings",  env.getProperty("spring.jpa.properties.hibernate.id.new_generator_mappings"));
    em.setJpaPropertyMap(properties);
    return em;
}

@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSourceProperties idotdbDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource idotdbDataSource() {
    return idotdbDataSourceProperties().initializeDataSourceBuilder().build();
}

@Primary
@Bean
public PlatformTransactionManager idotdbTransactionManager() {
    final JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(idotdbEntityManager().getObject());
    return transactionManager;
}


How to produce markup from a custom views field (FieldPluginBase based) render method in D8?

Question: I've created a custom views field following the excelent Creating a custom Views field in Drupal 8 guide. The render method returns the desired output, except that it's being sanitized somewhere down the line and thus the html markup comes out as plain text on the page.
I'd rather put the html markup into the theme, but there doesn't seem to be such thing as
views-view-field-<fieldname>.html.twig
in Drupal8 ?
Comment: yes, such a template name suggestion for field names does exist: `views-view-field--field-name.html.twig`, problem is only, that twig debug is not able to display it
Comment: Can you show us your render() method?
Answer: I can output HTML using my render method. Take a look:
  /**
   * {@inheritdoc}
   */
  public function render(ResultRow $values) {

    $field_abnormal_category = $this->view->field['field_abnormal_category']->original_value->__toString();

    if($field_abnormal_category == 'No') {
      $field_category_image = $this->view->field['field_category_image']->original_value->__toString();
    }
    else {
      $field_category_image = '';
    }

    return [
    '#type' => 'inline_template',
    '#template' => $field_category_image
    ];

  }

Comment: Thanks. It works on Drupal 9 too.


Commerce one-off products in admin interface

Question: Is there a way I can create the capability for an admin to add a one-off product when creating an order through the admin interface? (For example, it could have a SKU of "CUSTOM" but we'd need the ability to enter a custom description that would show up in the line item in the receipt).
These are for customizations that are not available to the general public/only available if an admin enters them and would only be useful one time, so creating a full-fledged product for each one is not feasible.
I have done some testing with Commerce Customizable Products but it seems to allow customizable fields on the front end, but not in the admin "Add Order" screen where I need it.
Answer: The line item title in 1.x is derived from the line item type's title callback. Your simplest option is going to be to define a new line item type, as you've surmised, and have its title callback pull the value from a field you add to the line item type and expose to administrators to edit. Alternately you could edit the various Views to render this field directly ... but then you'd still need some way to allow creating ad hoc line items on the back end.
Sorry, I wish it were easier.
Comment: Thanks Ryan! I've had some success (perhaps enough to get me where I need to be on this particular project/issue) with this module:
https://www.drupal.org/project/commerce_basic_line_item
Comment: Awesome, didn't know that existed! : )


If $F \subseteq \mathbb{R}$ is closed, countable infinity. Prove that $F$ has a countless infinite number of isolated points.

Question: To prove it use the following lemma : If $F$ is closed and $x \in F$ then $x$ is a isolated point of $F$ if and only if $F-\{x\}$ is closed.
In a book, a solution is as follows :
Let's suppose that $\{ a_1,a_2, \cdots ,a_n \}$ is the set of all isolated points of F. Then by the lemma : $F-\{a_1,a_2, \cdots ,a_n \}$ is closed.
Then this set which is closed and infinite countable does not have isolated points, a contradiction since everything closed countable has some isolated point.
My question comes in this last part, the statement that the set $G=F-\{a_1,a_2, \cdots ,a_n \}$ does not have any isolated point does not seem to be true.
Why? , because although it is true that the set $G$ can not contain an isolated point of $F$, that does not mean that the same set by itself has an isolated point.
I would like to know if my doubt is true or not.
My prove is identical until that last part. I affirm that there is an isolated point of $G$ let's call it $a$. So exists $\delta_1>0$ such that $(a-\delta_1,a+\delta_1) \cap G =\{a\}$. Let´s put $\delta_2 = min_{1\leq i \leq n}\{ \vert a-a_i \vert \}$. Then for $\epsilon = min\{\delta_1,\delta_2\}$ we have to $(a-\epsilon,a+\epsilon)\cap F =\{a\}$ so we would get an isolated point of $F$ different from all the others $a_i$.
Comment: Yes, you are correct that the argument you added at the end is needed. In fact, if $F$ is closed and countable, removing from $F$ its isolated points gives us a new closed set which, if nonempty, has again isolated points but *none* of them are isolated in $F$. The difference with the situation in your argument is of course that the number of isolated points we removed is infinite and thus the number corresponding to your $\delta_2$ could now be zero.
Comment: I am very confused by this question. Do we have the same definition of *'isolated point'*?
Comment: Let $F \subseteq \mathbb{R}$, a point $x \in F$ is isolated if exists $\delta>0$ such that $(a-\delta,a+\delta)\cap F = \{a\}$
Comment: Thanks for answering!
Answer: Your findings agree with the proof; you have proved that if $G$ has an isolated point then $F$ has an isolated point different from all the $a_i$. But by assumption (toward a contradiction), the $a_i$ are all the isolated points of $F$. Hence $G$ does not have an isolated point.


installation bochs Compile Error x.cc:37:22: fatal error: X11/Xlib.h: No such file or directory

Question: make[1]: Entering directory `/home/zfl/bochs-2.6.9/gui'
g++ -c  -I.. -I./.. -I../iodev -I./../iodev -I../instrument/stubs -I./../instrument/stubs -g -O2 -D_FILE_OFFSET_BITS=64 -D_LARGE_FILES -pthread     x.cc -o x.o
x.cc:37:22: fatal error: X11/Xlib.h: No such file or directory
 #include <X11/Xlib.h>
                      ^
compilation terminated.
make[1]: *** [x.o] Error 1
make[1]: Leaving directory `/home/zfl/bochs-2.6.9/gui'
make: *** [gui/libgui.a] Error 2

Comment: Can you please provide more information about what you are trying to do and what you did before getting the message above?  Did you download the software?  Were you trying to install with apt-get?
Answer: Looks like you are missing the libx11 package.
Try
sudo apt-get install libx11-dev

and recompile after that.
EDIT:
Steps to recompile. Run the following commands.

make dist-clean
./configure
make


Show $|f(z)| \leq \frac{2A|z|}{1 - |z|}$

Question: I have the following question:

Let $f$ be a holomorphic function on $\mathbb{D}$. Assume $f(0) = 0$ and $\Re f ≤ A$ on $\mathbb{D}$ for
some constant $A > 0$. Show that
$|f(z)| ≤ \frac{2A|z|}
{1 − |z|}$
for all $z ∈ \mathbb{D}$.

The $f(0)$ hypothesis and the fact that $f$ is defined on $\mathbb{D}$ makes me think that this could involve some type of Schwartz Lemma. But, the there is no reason to think that the function is bounded by $1$. I also do not know how to dissect the $\Re f \leq A$ part.
Any help would be greatly appreciated.
Comment: The question you asked is slightly different from that one in the title. One of then should be correct. Please make necessary corrections.
Comment: See also https://math.stackexchange.com/q/960550/42969
Answer: Wlog we can assume that $f$ extends to the boundary analytically (as otherwise we use $f_r(z)=f(rz)$ and take $r \to 1$) and we use what Wikipedia calls the Schwarz Integral formula (or what is called in some books the Poisson-Cauchy representation - the Cauchy completion of the Poisson formula):
$f(z)=\frac{1}{2\pi}\int_0^{2\pi}{\Re f(e^{it})\frac{e^{it}+z}{e^{it}-z}}dt$ so
$f(z)=f(z)-f(0)=\frac{1}{2\pi}\int_0^{2\pi}{\Re f(e^{it})(\frac{e^{it}+z}{e^{it}-z}}-1)dt=\frac{1}{2\pi}\int_0^{2\pi}{\Re f(e^{it})\frac{2z}{e^{it}-z}}dt$
Taking absolute values:
$|f(z)| \le \frac{1}{2\pi}\int_0^{2\pi}{A\frac{2|z|}{|e^{it}-z|}}dt$
But $|e^{it}-z| \ge 1-|z|$ so we get the required result and we are done:
$|f(z)| \le \frac{1}{2\pi}\int_0^{2\pi}{A\frac{2|z|}{1-|z|}}dt=A\frac{2|z|}{1-|z|}$
A second solution can be given noting that $\Re (-f/A) \ge -1, f(0)=0$ means that $f$ is subordinated to $g(z)=\frac{2z}{1-z}$ (which sends the unit disc precisely to the domain $ \Re w >-1$ as wlog we can assume $Re f <A$ as otherwise $f=0$ by maximum modulus and $f(0)=0$)
This means that there is $\phi(0)=0, \phi : D \to D$ holomorphic so $-f(z)/A=g(\phi(z))=\frac{2\phi(z)}{1-\phi(z)}$.
But $|\phi(z)| \le |z|$ by Schwarz so taking absolute values we recover the required result since $|1-\phi(z)| \ge 1 -|\phi(z)| \ge 1-|z|$


How to show $ a,b,c \in \mathbb R , z \in \mathbb C , az^2 + bz + c = 0 \iff a\bar{z}^2 + b\bar{z} + c = 0$?

Question: I am completely stumped by with this problem.

If a, b and c are real numbers and z is a complex number of the form $x + yi$, prove that $$az^2 + bz + c = 0 \iff a(z^*)^2 + b(z^*) + c = 0$$

I tried substituting $z = x + yi$ and for $z^*= x - yi$, but that gives a bigger equation with multiple variables. How should I proceed with this? Thanks for your help.
Answer: Try taking the complex conjugate of each side of the equation, and remembering that
$$(w+z)^* = w^* + z^*$$
$$(wz)^* = w^*z^*$$
Comment: I've edited my answer to be more clear. The expression $az^2 + bz + c$ is a complex number, as is $0$. So you can take their complex conjugates. You're doing the same thing to both sides of the equation, so you get another valid equation. You know that $0^*=0$, so $(az^2+bz+c)^*=0$. Now you just need to expand out that bracket using the rules in my answer.
Comment: Much clearer now. Thank you. I was able to work it out with these 2 identities and @lhf reply.
Comment: Can you please clarify what you mean my complex conjugate of the entire equation? Complex conjugate of a complex number, x+yi as I understand it is x-yi. How does this translate to an equation?
Comment: If $a=0$ we have nothing to prove. Otherwise $z_1+z_2=-\dfrac{b}{a}\in\Bbb{R}$ and $z_1z_2=\dfrac{c}{a}\in \Bbb{R}.$ Only complex conjugates have this property.
Answer: Here is a solution along the lines you took:
$a(z^*)^2 + b(z^*) + c = a(x-yi)^2 + b(x-yi) + c$
$\quad=a(x^2-2xyi-y^2) + b(x-yi) + c $
$\quad= (a(x^2-y^2)+bx+c) - (2axy+by)i$
$\quad=(az^2 + bz + c)^*$
Since $w=0$ iff $w^*=0$, you get your result.
Comment: Thanks, you made the factoring look simple.
Answer: Note: This answer is based on the relation between the roots of a quadratic equation with real coefficients, in the case when both are complex numbers.
I used below $z_1,z_2$, instead of $z,z^{\ast}$.

If one of the roots of a quadratic equation is the complex number $z_1=x_1+iy_1$ the other root $z_2=x_2+iy_2$ is the conjugate of $z_1$, i.e $z_2=x_1-iy_1=z_1^{\ast}$, as it can be seen, among other ways, by the resolvent formula
$$az^2 + bz + c = 0 \iff z=\frac{-b\pm\sqrt{b^2-4ac}}{2a}\qquad(a \ne 0).$$
Thus, if
$$z_1=\frac{-b+\sqrt{b^2-4ac}}{2a}=x_1+iy_1,$$
then
$$z_2=\frac{-b-\sqrt{b^2-4ac}}{2a}=x_1-iy_1=z_1^{\ast}$$
and vice-versa.
Since $z_1,z_2$ are roots, both satisfy the quadratic equation, by definition.

Added in view of the comments below.

If $z_2=z_1$, then $z_2=x_2=x_1$ and $y_1=y_2=0$.
If $a=0$, then the equation reduces to $bz_1+c=0$, which has a single root $z_1=x_1$, and $y_1=0$.
Comment: I am not sure how this translates to my question. Can you please clarify? Thanks.
Comment: @Américo That's true when $z^* \ne z$. Don't forget the other case.
Comment: If $az_1^2 + bz_1 + c = 0$, then $az_2^2 + bz_2 + c = 0$, where $z_2=z_1^{\ast}$ and vice-versa. I used the variables $z_1,z_2$, instead of $z,z^{\ast}$.
Comment: @Américo The other root need not be $z^*$ when $z^* = z$. Also, don't forget the case $a = 0$.
Comment: @Bill: If $z^{\ast}=z$, then the quadratic equation has a double real root, which means that $y=0$, isn't it?
Comment: @Bill: If $a=0$, then the equation is $bz+c=0$, which has a single real root, and again $y=0$.
Comment: @Ame Yes, but one needs to explicitly mention that (easy) case, unless "complex" above means non-real complex. Also one needs to explicitly treat the degenerate case $a = 0$. One can avoid this case analysis by noting that conjugation is an automorphism.
Comment: @Bill: Thanks! I added these considerations to my answer. I hope it is now complete.
Comment: @Ame if $z^* = z$ then the equivalence is clear, no need to mention anything about double roots. I just wanted to point out that one does need to mention these (easy) cases for this type of argument to be complete.
Comment: @Bill: I simplified the answer once more, in view of your comment.
Comment: Thanks guys. I feel I understood most of what you guys are saying. But need some time to digest it better. :)
Comment: @mathguy80: my answer is based on the relation between the roots of a quadratic equation with real coefficients, in the case when both are complex numbers.
Comment: Converted to CW because the reasoning was not clearly worded, though the idea were correct, I think.


Discrete Fourier transform implementation giving results that are order of magnitude off

Question: I tried implementing a Discrete Fourier transform in Matlab, but I found my results an order of magnitude off. I used next definition of DFT:
$$  F(u) = \frac{1}{2N} \sum^{N-1}_{x=-N}  f(x) e^{- \pi i x u/N} $$
I obtained separately the values for real and imaginary coefficients from this expressions and implemented the algorithm in Matlab. I set N=500, so I made an array of x values of size 500, and array of the result values for real and imaginary of size 500. Here is my Matlab code of my DFT function:
function [ rFT, iFT ] = DFT( N, rf, imf )

rFT = zeros(length(rf),1);
iFT = zeros(length(imf),1);

a = fix(length(rf)/2) + 1;
for u=(-N):(N-1)
    sumR = 0;
    sumI = 0;
    for x=(-N):(N-1)
        sumR = sumR + rf(x+a) * cos(- pi*(x)*u/N) - imf(x+a)*sin(- pi*(x)*u/N); %adjust for the fact that something starts counting at 0, not -250
        sumI = sumI + rf(x+a) * sin(- pi*(x)*u/N) - imf(x+a)*cos(- pi*(x)*u/N);

    end
    rFT(u+a) = sumR;
    iFT(u+a) = sumI;
end
rFT = rFT/(2*N);
iFT = iFT/(2*N);
end

Now, if I try to input a box function for example of width 10 and height 1 centered on origin, I find that the result looks like a sinc function, which is what I expected but the maximum value of the function is of order $10^{-2}$ (value at $u=0$), while I find just by taking the integral myself that the max should be 10. And similarly, if I take a transform of a convolution of the box with itself (I calculated the convolution on paper) and compare it to the square of the transform of the box, I find they look similar in shape, but again off by a very big scalar constant. Is my understanding of theory wrong, or is there something off with my implementation?
Comment: Compare your formula to the ones here https://en.wikipedia.org/wiki/Discrete_Fourier_transform that will be a good exercise in skimming and picking out relevant information too.
Comment: Why are you looping in Matlab?
Comment: Apart from looping is very slow in matlab, the fourier transform can be normalized in different ways. This affects how the inverse transform will be.
Comment: So I guess the reason I am getting inconsistent answers is because of normalisation?
Comment: If everything looks right but there is a constant factor wrong on each sample I would say normalization is the most probable issue. Note that this is not necessarily "wrong", it just changes how you would need to implement the inverse transform.
Comment: I just want to make sure that my implementation and approach is self-consistent. And comparing the transform of convolution and square of transform they look the same, both look like a $sinc^2$ and I guess if they are just normalised differently it is not a problem.
Answer: It seems to me that your implementation is correct but that you use a non-unitary transform: that is you need different normalization factors for forward and backward transform. You can for example turn your DFT into a unitary DFT by replacing
rFT = rFT/(2*N);
iFT = iFT/(2*N);

with
rFT = rFT/(2*N).^0.5;
iFT = iFT/(2*N).^0.5;

However in the Matlab programming language using loops is very slow compared to doing matrix and vector operations. By comparison running DFT on a 127 sample long $\sin^2(x)$ function ( in seconds, and actually I run it in Octave, but it is designed to be compatible ):
t_vec =  0.0024350
t_for =  1.1651
t_for/t_vec
ans =  478.49

A factor of almost 500 times! So if you expect to use matlab or other vectorized languages in the future for more involving and computationally intensive things I would encourage you to learn thinking and writing code which takes advantage of that.


Do Bayes factors require multiple comparison correction?

Question: As the title: Do Bayes factors require mutliple comparion correction?
For more context, I am calculating very many likelihood ratio tests and I am thinking about how to handle multiple comparison correction. I thought Bayes factors might present a solution - if I am presenting the results in the Bayes factor evidence scale then I think correction should not be required?
Computing full Bayes factors for every test with MCMC would be difficult (but not impossible - although I am not sure how to chose priors really), but following Wasserman (2000), it seems that BIC can be used to approximate the Bayes factor. So it seems to get around my multiple comparisons difficulties I can simply add the $\frac{d_f}{2}\log n$ term to my log-likelihood ratio, exponentiate it and call it a Bayes factor which I can present without correction.
It seems too good to be true, so what am I missing?
My view is that it pushes the inference step to the reader instead presenting the Bayes factor evidence (which is of course exactly what I want to do, philosophically I don't see the need for assigning every point in an image a precise p-value) - but is this likely to be acceptable to reviewers? (The application is in neuroimaging)
Answer: What you are missing is that it very rarely makes sense to use a prior for which  all of parameters are independent. That might make sense if the parameters were as varied and logically disconnected as, say, the set {some physical constant, some baseball player's batting average, some yeast gene's expression level}.
Most analyses look at sets of parameters that are best modeled as exchangeable, like, say, the set of all current players' batting averages or the set of all yeast genes' expression levels. For estimation, this leads to approaches like this; for testing, it leads to approaches like this.
Answer: Not necessarily for Bayes factors. But Bayes factors require conversion to posterior probabilities for proper inference, and posterior probabilities most definitely can require a Bonferroni-style multiplicity adjustment of sorts. Here is the explanation:
If the hypotheses are independent a priori, then probability that all nulls are simultaneously true decreases to zero very rapidly as the number of hypotheses tested increases. But there may be scientific doubt as to whether any effect exists: For example, in a neuroimaging study there can be doubt as to whether the association studied has any neuronal basis whatsoever. (Nevertheless, the most extreme statistics are likely to suggest an association, simply because when you look at a large number of statistics, the extreme values will likely be quite atypical.)
In cases such as this where there is scientific doubt about whether there is any association whatsoever, you must set your prior probability on the global null hypothesis to some non-infinitesimal value in order to correctly model such doubt. In doing so, your prior probabilities on the component nulls are necessarily increased from commonly-used levels (such as 0.5), depending on the number of hypotheses tested, and depending on your assessment of their degree of prior dependence. Such a change in the prior probabilities on the component nulls causes a change (or adjustment) in the posterior probabilities on the component nulls. This adjustment is similar to the usual Bonferroni adjustment when the components are assumed independent a priori, and is less extreme than the Bonferroni adjustment when the components are assumed dependent.
This issue is discussed in the following literature. The last reference discusses how to do the analysis when you assume prior dependence.
Jeffreys, H. Theory of Probability. Oxford press.
Westfall, P.H., Johnson, W.O. and Utts, J.M.(1997). A Bayesian Perspective on the Bonferroni Adjustment, Biometrika 84, 419–427.
Gönen, M., Westfall, P.H. and Johnson, W.O. (2003).  Bayesian multiple testing for two-sample multivariate endpoints, Biometrics 59, 76–82.
Answer: In the context of frequentist inference, the posterior odds, or posterior probability of the null (a.k.a. local fdr), is nothing more than a test statistic.
It can definitely lead you to many erroneous inferences due to chance alone.
If you want some frequentist guarantee on the amount of errors you might be making, the posterior odds should be plugged into some multiplicity control scheme.
Comment: Thanks. I understand for the frequentist interpretation correction is necessary. But do Bayes factors with a bayesian interpretation require any correction?
Comment: I would say no. But have a look at this:http://normaldeviate.wordpress.com/2012/11/09/anti-xkcd/


Configuring connectors for multiple topics on Kafka Connect Distributed Mode

Question: We have producers that are sending the following to Kafka:

topic=syslog, ~25,000 events per day
topic=nginx, ~5,000 events per day
topic=zeek.xxx.log, ~100,000 events per day (total). In this last case there are 20 distinct zeek topics, such as zeek.conn.log and zeek.http.log

kafka-connect-elasticsearch instances function as consumers to ship data from Kafka to Elasticsearch. The hello-world Sink configuration for kafka-connect-elasticsearch might look like this:
# elasticsearch.properties
name=elasticsearch-sink
connector.class=io.confluent.connect.elasticsearch.ElasticsearchSinkConnector
tasks.max=24
topics=syslog,nginx,zeek.broker.log,zeek.capture_loss.log,zeek.conn.log,zeek.dhcp.log,zeek.dns.log,zeek.files.log,zeek.http.log,zeek.known_services.log,zeek.loaded_scripts.log,zeek.notice.log,zeek.ntp.log,zeek.packet_filtering.log,zeek.software.log,zeek.ssh.log,zeek.ssl.log,zeek.status.log,zeek.stderr.log,zeek.stdout.log,zeek.weird.log,zeek.x509.log
topic.creation.enable=true
key.ignore=true
schema.ignore=true
...

And can be invoked with bin/connect-standalone.sh. I realized that running or attempting to run tasks.max=24 when work is performed in a single process is not ideal. I know that using distributed mode would be a better alternative, but am unclear on the performance-optimal way to submit connectors to distributed mode. Namely,

In distributed mode, would I still want to submit just a single elasticsearch.properties through a single API call? Or would it be best to break up multiple .properties configs + connectors (e.g. one for syslog, one for nginx, one for zeek.**) and submit them separately?
I understand that tasks be equal to the number of topics x number of partitions, but what dictates the number of workers?
Is there anywhere in the documentation that walks through best practices for a situation such as this where there is a noticeable imbalance of throughput for different topics?
Answer:
In distributed mode, would I still want to submit just a single elasticsearch.properties through a single API call?

It'd be a JSON file, but yes.

what dictates the number of workers?

Up to you. JVM usage is one factor that you can monitor and scale on
Not really any documentation that I am aware of
Comment: I suppose I'm confused by what exactly a worker is then. I get that a task is effectively a thread, but would submitting one JSON properties file equal one worker?
Comment: Edit of above comment: my understanding is I would run something akin to `bin/connect-distributed.sh worker.properties` on multiple nodes while specifying the same `group.id`. I'm assuming each of those is a worker process, and then would make a _single_ REST API request with the connector properties. Is that correct?
Comment: That's correct. You could also use Kubernetes, for example to launch multiple pods of some Connect image to run a cluster, then expose a load balancer for the API


How to construct a non-trivial example that shows $A^{-1}A = I_X $ and $AA^{-1} = I_Y$, where $I_X \neq I_Y$

Question: Let $A: X \to Y$, and $A^{-1}:Y\to X$ be maps where $A^{-1}$ is the inverse of $A$
Then $A^{-1}A =  I_X$ and $AA^{-1} = I_Y$
I can't think of good examples to demonstrate this result, because for $A$ a matrix (finite dimensional operator), there is no difference between $I_X$ and $I_X$, they are just the identity matrix of same dimension
How to construct an $A$ where $I_X \neq I_Y$?
Answer: Just take a bijective mapping between two different vector spaces of the same dimension. For instance, $X=\mathbb R^{m,n}$, $Y=\mathbb R^{n,m}$, $n\ne m$, and the mapping $A:X\to Y$ defined by
$$
A(M)=M^T.
$$


how is the affect of ordering the features in perceptron?

Question: I Have 2 linearly separable classes and I have performed a simple perceptron for finding the classifier's threshold.
Since in simple perceptron I used all missclassified points in every iteration of algorithm I was wondering if :

does the order of accounting points affect the out put threshold line?
does the order of accounting points affect the number of iterations needed to achieve the line?
Comment: What is your perceptron learning rule?
Comment: @user31264:
w(n+1) = w + delta *sum(missclassified points * class label)
Answer: Yes to both questions. You should experiment with a small example if you want to see this happening. Here is an example of a perceptron in R:
fit <- function(dat, y, w){

# dat a n x 2 matrix of data points
# y an n-vector of 0/1 classifications
# w starting weight vector

counter <- 0 # count number of iterations
error <- 100
n <- nrow(dat)

while (error > 0){
  error <- 0
  for (i in 1:n){
    fitted <- sum(w*dat[i,]) > 0
    if (fitted != y[i]){
      error <- error + 1
    }
    w <- w + (y[i] - fitted)*dat[i,]
  }
  counter <- counter + 1
}
print(w) # final value of w
print(counter) # number of iterations through data set until convergence
}

You can try creating a small data set to classify:
dat <- matrix(c(1,1,2,2,2,1,1,0), nc=2)
y <- c(1, 1, 0, 0) # true classes
w <- c(0, 0) # weights

Classify it:
> fit(dat, y, w)
[1] -2  3
[1] 5
> z <- c(3, 2, 1, 4) # re-order data
> fit(dat[z, ], y[z], w)
[1] -1  2
[1] 4

You can see that it reaches a different solution and takes a different number of iterations to do so.
Comment: Thank you for your answer.The algorithm that you have used is revised version of perceptron in reward and punishment manner (theodoridis page 99). The algorithm which I am using considers following learning rule in every iteration:
w(n+1) = w + delta *sum(missclassified points * class label)
where I have used constant delta =1