Error reading table in Python/Pandas

Question: I am using Python/Pandas and when I try to:

df = pd.read_table("/test/" + file, sep='\t')

I get the error:

'Error tokenizing data. C error: Expected 24 fields in line 6927, saw 26'

How do I overcome this?
Comment: Also try: `df = pd.read_csv(filename, sep=r'\t')`. You're actually placing a tab there, not the character sequence `"\" + "t"`
Answer: try this :-)
<code>data = pd.read_csv('file1.csv', error_bad_lines=False)
</code>

Error reading table in Python/Pandas


Need to CFRunLoopRun() but want it unblocking

Question: I have the following piece of code in a cocoa Application for OSX:
void *callbackInfo = NULL; // could put stream-specific data here.
            FSEventStreamRef stream;
            CFAbsoluteTime latency = 1.0; /* Latency in seconds */

            /* Create the stream, passing in a callback */
            stream = FSEventStreamCreate(NULL,
                                         &mycallback,
                                         callbackInfo,
                                         pathsToWatch,
                                         kFSEventStreamEventIdSinceNow, /* Or a previous event ID */
                                         latency,
                                         kFSEventStreamCreateFlagFileEvents//kFSEventStreamCreateFlagNone /* Flags explained in reference */
                                         );

            /* Create the stream before calling this. */
            FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(),kCFRunLoopDefaultMode);
            FSEventStreamStart(stream);

            CFRunLoopRun();

        }

This code gets notified about files system changes and reacts accordingly (the callback function is not in the snippet).
My problem now is that the CFRunLoopRun() is blocking. I.e. the further execution of the code stops. However, I'm looking for a possibility that I can start the observation of file system changes but also stop it again (e.g. from another object).
One option that I thought of would be to only start the loop for a second and check for a global variable afterwards. However, I usually don't like global variables....
Does anybody here have a nice and handy idea, how this could be solved? Would it be a good idea to buy the overhead and put the execution into a separate thread?
Thanks in advance!
Norbert
Comment: Why don't you just leave out the call to `CFRunLoopRun()` and just allow execution return to the app's main event loop? The main event loop is built on the run loop, so allowing that to run **is** allowing the run loop to run. You will get file system events as well as user events like mouse and keyboard, etc. If you eventually want to stop observing file system events, just call `FSEventStreamStop()`.
Comment: With other words: the run loop already runs and handles the events from the FS event stream? So the only thing I have to ensure is that the current thread that the object lives in does not end!? That sounds so simple that I did not even think about it ;-)
Comment: After many tries and debugging sessions I'm almost to give up on this :-( what I did not mention in my original post is that this all happens in a command line app. And there it seems that the runloop has to be called explicitly. Whatever I do: the FSEvents are not handled if I don't call CFRunLoopRun() but when I call it, it blocks the rest of the code being executed.
Comment: FSEvents is a notification API. How do you expect to receive those notifications? What should the thread your code is running on be doing in the meantime? How would the callback be called on it if it's busy doing other stuff? Do you want to poll (which is against the purpose of a notification API)? You could schedule a timer on the run loop and, when it fires, stop the run loop. You can use a dispatch queue instead of a run loop (`FSEventStreamSetDispatchQueue()`), in which case your callback will be called on another thread. You need to explain more clearly how you want this to work.
Comment: I obviously underestimated the complexity here :-(
What I want to achieve/do in my command line tool is round about this:
1) Create a custom object. This object brings an FSEventStream that is linked to the standard runloop
2) start an observer function of this object. This will start the event stream
3) Repeat steps 1 and 2 multiple times'
4) listen to the events and handle them
5) The user shall be able to interact with the app (by pressing certain buttons that may cancel the app or influence the behavior of the callback routine for the events
Comment: Sorry, that was imprecise in the english language. When saying button I meant a certain key on the keyboard.
Answer: CFRunLoopRun() runs the current run loop forever, until somebody registered in the runloop calls CFRunLoopStop().  This is not what you want to do unless you're doing something very fancy.
If you want to the FSEventStream callback to run, you just register it with the runloop and leave it, you don't have to do anything explicitly to the runloop after that, registering the even stream as a source is all you have to do.
If you want to stop observing the stream you call FSEventStreamStop() on it.
Answer: A Cocoa application has an implicit run loop, so just delete CFRunLoopRun();
Consider to use a dispatch queue via Grand Central Dispatch (GCD) rather than schedule the stream on a run loop


transforming data from cartesian plane to isometric plane

Question: Here is a brief description of what I'm trying to accomplish. I created a 2d top down game that operated on a Cartesian plane and used some custom polygons to determine collisions and perform actions within the game engine.
I have converted the engine into a tiled isometric game and have got the majority of it working. I can translate the mouse click to the tile selected and can go back and forth between Cartesian coordinates and isometric tile coordinates. However, transforming some of my polygons is proving difficult. I need them to not only display correctly along the isometric plane but also to retrieve the adjusted coordinates in order to perform collision detection tests. I also need to accurately determine the "simulated" distance between a pair of points on the isometric plane.
Here is an examples to help clarify the situation a little bit:

This image is from the 2d top down game, with an isometric background to help clarify the issue. In this image you can see the green bounding box of a character in the game and the blue custom polygons used to simulate a sword swing. However in this image you can see that the bounding box and the sword swing polygons are still represented in the Cartesian plane.

This image is from the isometric game, with the Cartesian axis being represented by the red lines. They meet at point (0,0). There is a blue bounding box for the character that has now been transformed to fit the Isometric plane. To the bottom right you'll see a tile I selected outlined in green. Inside the tile are some points and lines that will be used to demonstrate the problem.
The teal letters represent coordinates and the red numbers represent lines. The distance (on the Cartesian plane) between B and F is 45 and the distance between H and D is 90. However, on the isometric plane the "simulated" distance (within the game) should be the same, in order to give the effect of a 3d environment.
Hopefully, that's enough information to get to the actual problem. What I need help with is deriving a formula for converting an angle and a "simulated" distance (on the isometric plane) to a Cartesian coordinate.
For example if given the coordinate of point A, the angle 0 and the distance of 45 you should get the Cartesian coordinates for the point D. Similarly if given the angle 90 and the distance of 45 you should get the point B. If given the angle 180 and the distance of 45 you should get the point H. If given the angle 270 and the distance of 45 you should get the point F.
Similarly if asked what the distance of point A to all of those points you should get 45 as the distance.
These examples wont necessarily transform the polygons but they will allow me to recreate them and the majority of my other custom polygons. Sorry if this doesn't make sense. If needed I'll try to clarify the problem more, just let me know what needs to be explained further.
Thanks for your time.
EDIT: if there is some type of transformation matrix that would accomplish this and be easier, I'm definitely open to that as well.
EDIT 2: using the answer provided by amd below I was able to get the answers needed. my isometric view was created by rotating an object 45 degrees and then scaling the y axis in half. In order to find the distance between the two points I simply needed to reverse the transformation and then determine the distance. also the formula provided by amd worked to determine a point given a distance and angle, however to fit my example i needed to change the 1/sqrt(3) into 1/2 and add 45 degrees to the angle provided before running it through the formula.
EDIT 3: here is an example of the finished product
Comment: The isometric view looks a bit off to me. Are the segments $IE$ and $CG$ meant to be at "simulated" 45-degree angles? If so, then they should be parallel to $BD$ and $BH$, respectively.
Comment: yeah they were supposed to be at 45 degrees, I did the points and lines around the green border in photoshop and it's not pixel perfect unfortunately. sorry about that.
Answer: Angles and lengths can be introduced into a vector space by giving it an inner product. The familiar Euclidean scalar product $\mathbf u\cdot\mathbf v = \mathbf v^T\mathbf u$ defines lengths and angles via the well-known equations $\mathbf v\cdot\mathbf v=\|\mathbf v\|^2$ and $\mathbf u\cdot\mathbf v=\|\mathbf u\|\|\mathbf v\|\cos\theta$. We can define a different inner product $\langle\cdot,\cdot\rangle_A$ by choosing a positive-definite (symmetric) matrix $A$ and letting $\langle\mathbf u,\mathbf v\rangle_A=\mathbf v^TA\mathbf u$. The previous formulas can then be taken as defining lengths and angles relative to this new scalar product.
We can try to find a scalar product for the isometric view that has the desired properties. First note that we can get the isometric view from the top-down view via the transformation matrix $$
B=\pmatrix{1&0\\0&\frac1{\sqrt3}}.$$ This maps the circle $x^2+y^2=1$ onto the ellipse $x'^2+3y'^2=1$, so unit vectors in the isometric view must satisfy the latter equation. On the other hand, we have $\langle\mathbf u,\mathbf u\rangle_A = a_{11}x'^2+2a_{12}x'y'+a_{22}y'^2$, so we must have $$A=\pmatrix{1&0\\0&3}$$ as the matrix of the inner product.
This gives us the desired lengths in the isometric view, but we should also check that the angles look right. Taking the ellipse in the diagram as the image of the unit circle, $AC$ represents the image of the 45° line, i.e., the line parallel to $\left(\frac1{\sqrt2},\frac1{\sqrt2}\right)^T$. This is transformed into $\left(\frac1{\sqrt2},\frac1{\sqrt6}\right)^T$. Taking the inner product of this with $(1,0)^T$ and $\left(0,\frac1{\sqrt3}\right)^T$ (the images of the standard basis vectors) yields $\frac1{\sqrt2}=\cos\frac\pi 4$, which is what we wanted.
To produce a vector with a particular angle and length relative to this inner product, generate it in the top-down view first and then transform the resulting vector: $$
\pmatrix{1&0\\0&\frac1{\sqrt3}}\pmatrix{r\cos\theta \\ r\sin\theta}=\pmatrix{r\cos\theta \\ \frac r{\sqrt3}\sin\theta}.
$$
The above all assumed that the isometric view was generated by looking down at the $xy$-plane and then tilting it away from the viewer so that $45°$ lines changed to $30°$. If you're using some other isometric transformation, you can follow a similar procedure to compute a compatible inner product.
Here's another way to compute the inner product matrix $A$ given the non-singular transformation $B$. We want $\langle\cdot,\cdot\rangle_A$ applied to the images of a pair of vectors under $B$ to equal their dot product, i.e., $$\begin{align}
\langle B\mathbf u,B\mathbf v\rangle_A &= (B\mathbf v)^TAB\mathbf u \\
&= \mathbf v^T B^T A B \mathbf u \\
&= \mathbf v^T\mathbf u,
\end{align}$$ so $A=(B^T)^{-1}B^{-1}=(BB^T)^{-1}$.


Unable to open .jar files with Java

Question: I'm using Lubuntu and trying to open a file named Minecraft.jar, but all the solutions that work for other people aren't working for me. I have these versions of Java installed:

openjdk version "9-internal"OpenJDK Runtime Environment (build
  9-internal+0-2016-04-14-195246.buildd.src)OpenJDK 64-Bit Server VM
  (build 9-internal+0-2016-04-14-195246.buildd.src, mixed mode)

When I try to right click it and open with OpenJDK Java 8 runtime nothing happens and whenever I try the java -jar command in terminal this is all I get:
mitochondria@Mina:~$ java -jar /home/mitochondria/Desktop/Minecraft.jar

A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0x00007fc01b121009, pid=20039, tid=20040
JRE version: OpenJDK Runtime Environment (9.0) (build
  9-internal+0-2016-04-14-195246.buildd.src)  Java VM: OpenJDK 64-Bit
  Server VM (9-internal+0-2016-04-14-195246.buildd.src, mixed mode,
  tiered, compressed oops, g1 gc, linux-amd64)  Problematic frame:  C
  [libjava.so+0x1d009]  JNU_GetEnv+0x19
Core dump will be written. Default location: Core dumps may be
  processed with "/usr/share/apport/apport %p %s %c %P" (or dumping to
  /home/mitochondria/core.20039)
An error report file with more information is saved as:
  /home/mitochondria/hs_err_pid20039.log
If you would like to submit a bug report, please visit:
http://bugreport.java.com/bugreport/crash.jsp  The crash happened
  outside the Java Virtual Machine in native code.  See problematic
  frame for where to report the bug.
Aborted (core dumped)
Answer: You seem to be using a development version of java : Java 9 has not been released yet.
So, first of all, you should remove this version of java, and install the default one :
sudo apt-get remove openjdk-9-*
sudo apt-get install default-jre

Depending on your version of Ubuntu, it should be a version 7 or 8.
If you're on a development version of Ubuntu, you might need to choose version 8 :
    sudo apt-get install openjdk-8-jre
Then you should be able to run Minecraft.
By the way, the simplest method to install it is to use the PPA instead of trying to run the .jar by hand :
sudo add-apt-repository ppa:minecraft-installer-peeps/minecraft-installer
sudo apt-get update
sudo apt-get install minecraft-installer

Comment: Not only did this solve the issue, but you went above and beyond in showing how to more easily achieve the end result requested.

Excellent first post, IMHO.
Comment: Thank you so much! I have been trying to figure this out for days! The instructions were clear, and effective!
Comment: A native Linux launcher for Minecraft has been released and can be downloaded as Deb file. If you are still using 16.04 you will have to build libicu from source

Unable to open .jar files with Java


onActivityResult not working with RESULT_OK, RESULT_CANCEL, etc when using camera on Android

Question: I've got in my class something like this:
<code>  public class Main extends Activity {

        private static final int CAMERA_PICK = 1;
        private static final int GALLERY_PICK = 2;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            Button photo = (Button) findViewById(R.id.button);

            photo.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    createDialog();
                }
            });

        private void createdialog(Activity activity) {
            final CharSequence[] items = { "Take shot", "Take from gallery" };

            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("Get image");
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
                    if (item == 0) {
                        takePhoto();
                    }
                    if (item == 1) {
                        choosePhoto();
                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }

        protected void choosePhoto() {
            // not necessary;
        }

        protected void takePhoto() {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

            mUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "myPic"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg"));
            cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mUri);

            try {
                cameraIntent.putExtra("return-data", true);
                startActivityForResult(cameraIntent, CAMERA_PICK);

                //Doing something with the picture here;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // TODO
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

             switch (resultCode) {
             case CAMERA_PICK:
                    break;
             case RESULT_OK:
                    Toast.makeText(Main.this, "Photo selected", Toast.LENGTH_SHORT).show();
break;
        }
       }
    }
</code>
As you can see I am trying to use the phone's camera to take a picture and use it later on an image view. The thing is there I can't trigger the method onActivityResult(...)! When I do the startActivityForResult(cameraIntent, CAMERA_PICK); I do not have a way to manipulate the RESULT_OK, RESULT_CANCEL or even the one I defined as CAMERA_PICK. The onActivityResult(...) should work on perfection by I am not understand what I'm doing wrong!
Any help would be aprecciated, Thanks.

I've already found the problem. I was using an activity group and I
  didn't realized that the onActivityResult() triggered was the first
  one of all the activities...
Answer: I've just have the same problem when picking photo from gallery on some of the real device. After a lot of searching I found this. Indicating that the onActivityResult of the Dialog may be tirggered instead of the activity to get returned value. This issue does not happens on all devices.


Data type mismatch in fortran

Question: I've written a rudimentary algorithm in Fortran 95 to calculate the gradient of a function (an example of which is prescribed in the code) using central differences augmented with a procedure known as Richardson extrapolation.
function f(n,x)
! The scalar multivariable function to be differentiated

integer :: n
real(kind = kind(1d0)) :: x(n), f

f = x(1)**5.d0 + cos(x(2)) + log(x(3)) - sqrt(x(4))

end function f
!=====!
!=====!
!=====!

program gradient
!==============================================================================!
! Calculates the gradient of the scalar function f at x=0using a finite        !
! difference approximation, with a low order Richardson extrapolation.         !
!==============================================================================!

parameter (n = 4, M = 25)
real(kind = kind(1d0)) :: x(n), xhup(n), xhdown(n), d(M), r(M), dfdxi, h0, h, gradf(n)

h0 = 1.d0
x  = 3.d0

! Loop through each component of the vector x and calculate the appropriate
! derivative
do i = 1,n
! Reset step size
h = h0

    ! Carry out M successive central difference approximations of the derivative
do j = 1,M
        xhup = x
        xhdown = x
        xhup(i) = xhup(i) + h
        xhdown(i) = xhdown(i) - h
        d(j) = ( f(n,xhup) - f(n,xhdown) ) / (2.d0*h)
    h = h / 2.d0
    end do

    r = 0.d0
    do k = 3,M      r(k) = ( 64.d0*d(k) - 20.d0*d(k-1) + d(k-2) ) / 45.d0
        if ( abs(r(k) - r(k-1)) < 0.0001d0 ) then
        dfdxi = r(k)
            exit
        end if
    end do

    gradf(i) = dfdxi
end do

! Print out the gradient
write(*,*) " "
write(*,*) " Grad(f(x)) = "
write(*,*) " "
do i = 1,n
    write(*,*) gradf(i)
end do

end program gradient

In single precision it runs fine and gives me decent results.  But when I try to change to double precision as shown in the code, I get an error when trying to compile claiming that the assignment statement
d(j) = ( f(n,xhup) - f(n,xhdown) ) / (2.d0*h)

is producing a type mismatch real(4)/real(8).  I have tried several different declarations of double precision, appended every appropriate double precision constant in the code with d0, and I get the same error every time.  I'm a little stumped as to how the function f is possibly producing a single precision number.
Comment: I won't even try to debug a Fortran code which does not state `implicit none` within every scope. I suggest you enhance your code and edit your question once you've done so.
Answer: The problem is that f is not explicitely defined in your main program, therefore it is implicitly assumed to be of single precision, which is the type real(4) for gfortran.
I completely agree to the comment of High Performance Mark, that you really should use implicit none in all your fortran code, to make sure all object are explicitely declared. This way, you would have obtained a more appropriate error message about f not being explicitely defined.
Also, you could consider two more things:

Define your function within a module and import that module in the main program. It is a good practice to define all subroutines/functions within modules only, so that the compiler can make extra checks on number and type of the arguments, when you invoke the function.
You could (again in module) introduce a constant for the precicision and use it everywhere, where the kind of a real must be specified. Taking the example below, by changing only the line
integer, parameter :: dp = kind(1.0d0)

into
integer, parameter :: dp = kind(1.0)

you would change all your real variables from double to single precision. Also note the _dp suffix for the literal constants instead of the d0 suffix, which would automatically adjust their precision as well.
module accuracy
  implicit none

  integer, parameter :: dp = kind(1.0d0)

end module accuracy

module myfunc
  use accuracy
  implicit none

contains

  function f(n,x)
    integer :: n
    real(dp) :: x(n), f
    f = 0.5_dp * x(1)**5 + cos(x(2)) + log(x(3)) - sqrt(x(4))
  end function f

end module myfunc

program gradient
  use myfunc
  implicit none

  real(dp) :: x(n), xhup(n), xhdown(n), d(M), r(M), dfdxi, h0, h, gradf(n)
  :

end program gradient

Comment: Thankyou very much, that cleared up my issue.  And I know it is good practice to use `implicit none` in Fortran, but coming from a Matlab background it's something I've had to get accustomed to and sometimes don't make use of.

Data type mismatch in fortran


Adding Serilog ILogger to a static class

Question: I'd like to add a Serilog Log to a static class in my program like this (DataHelper is the class name):
private readonly ILogger _log = Log.ForContext<DataHelper>();

But this leads to the error message:

static types cannot be used as type arguments

Which makes sense. So how do I inject the logger (which is working fine in non-static classes) to this class?
Update: The answer to you referred question suggests that it is not possible. But according to Serilog's Github, there is a workaround. I just need log to be aware of the class it is logging from. For now, it seems as if it is logging from the main class.
Comment: Possible duplicate of [Dependency injection with a static logger, static helper class](https://stackoverflow.com/questions/1293489/dependency-injection-with-a-static-logger-static-helper-class)
Comment: @nilsK the answer to you referred question suggests that it is not possible. But according to Serilog's Github, there is a way: https://github.com/serilog/serilog/issues/886
Comment: what I would do, if you have a possibility, refactor DataHelper class and make in regular object registered as a singleton. It will simplify usage and testability
Comment: @OlegI Does that mean that every static class I have made, in order to write to log, needs to turn into Singleton?
Comment: @Disasterkid well, it's up for you to make such decisions if there is no easy workaround to fix your problem and writing logs are crucial for you
Answer: You need to use the overload that accepts a Type:
private readonly ILogger _log = Log.ForContext(typeof(DataHelper));

Comment: Do we not need `static` after `private`?
Comment: Depends on usage; I only made the minimal changes here to show the `ForContext()` overload in the setting of your code sample above. If the `_log` field is in a static class, you'll definitely need to add `static`; otherwise, it's probably a matter of taste in this situation. HTH!
Answer: The discussion on this issue discusses this limitation and suggests a resolution. Summary: Use the overload ForContext(Type), which you can pass the type of the static class using typeof(DataHelper).
Comment: This seems to work but what should the value of `"SourceContext"` be? It logs as if we are logging from the Main class.
Comment: Beats me; I've never used Serilog.


"Unexpected end of declaration" Android AIDE

Question: I'm following this spinner_guide to add a spinner to my app. I have added the following to MainActivity.java:
Spinner key_spinner = (Spinner) findViewById(R.id.key_spinner);
ArrayAdapter<CharSequence> key_adapter =ArrayAdapter.createFromResource(this,R.array.spinner_keys,android.R.layout.simple_spinner_item);
key_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
key_spinner.setAdapter(key_adapter);

with spinner_keys a string array defined in strings.xml and key_spinner is a spinner in main.xml. I get an unexpected end of declaration error at the brackets of the last two functions (the brackets are underlined with a red squiggly line in AIDE). I have had this error in another app I am working on but cannot see the cause. I have searched for the error term but have not found it. I suspect it may be due to the argument to the function not being recognised(?), but I don't really know - this (and the other mentioned app) are my first attempt at Android (and Java) programming.
Any suggestions would be appreciated.
Comment: It sounds like you are missing braces in your code. However, it is impossible to tell without the exact code that produces the error.
Answer: Code like this should be in a method body such as onCreate() and not in class body. In a class body the first two lines are valid since they define and initialize member variables, while the latter two lines are not valid in such context.
So, wrap the code in
@Override
public void onCreate(Bundle b) {
    super.onCreate(b);

    setContentView(R.layout.your_layout_name);

    // that code here

 }


Activiti BPMN Editor - Multiple parallel User Tasks

Question: My example below shows a fairly simple process with a twist.
The scenario given in the image below is designed so that an admin user can:

Create a number of users using the Create User form
Add one or all of the created users to a group
Save the information for all created users

This works fine for one user, but I need the ability to create n instances of the Create User form and have each one follow the path for the rest of the process.
I thought I might be able to do this by using Parallel gateways to spawn new instances of the Create User form on the same process. But this doesn't seem to work as expected, It just overwrites the first instance of Create User in the process.

is this design possible? Am I missing something? Im aware that you can make the forms Asynchronous but this also does not appear to work as expected.
Answer: Executions model supports what you want, but variables model is a bit off.
Nevertheless you can separate variables and forms through call activiti subprocesses. Forms data will be separated.


Passing a value into a method that is triggered by an event

Question: I made a simple todo app using React.
An unordered list (
 is used to present all the items in my list. Within that are list items (
), and with a list item is a button with an onClick handle attached to a class method:
<button onClick={this.onHandleClick.bind(this)}>Add</button>

In the method, I need to prevent the default behaviour to prevent the page refreshing when the button is clicked:
onHandleClick(event) {
    event.preventDefault();
    ...
}

My question is, what can I do if I want to pass a value into onHandleClick, given that event is given as the argument?
Comment: `onClick={event => this.method(event, arg1, arg2)}`
Answer: Wrap your event handler in another function and pass item specific parameters this way:
<button onClick={e => this.handleClick(e, itemId)}>Add</button>

handleClick(event, itemId) {
    event.preventDefault();
    console.log(itemId);
}

Answer: I'm not familiar with React, but if the value is static, you could do something like this:
<button onClick={function(){self.onHandleClick(passedInValue);}}>Add</button>

Note that "self" would need to be bound to whatever object contains the 'onHandleClick' method.
Comment: be aware in your example `this` will not be the surrounding class and will not contain the event handler


Using a Mixture of Record-Editing UI Strategies

Question: I'm working on an application that will keep various types of records that vary from adding or editing two entities (name and uploaded document) to a user added either by searching through the database (either using a modal dialog or auto-fill) or manually entering at least 7+ entities. All of the entities won't be displayed to the user in the data grid.
I know there isn't a best way of adding or editing data and varies based on how much information is used to create the one record. I wanted to use two of the methods from this post to create or edit records: What is the best UX to let user perform CRUD operations?
For records with 7+ entities, I wanted to use a modal dialog; while for the records where all the fields were showing, use inline record editing.
Is it a bad practice to use inline editing/sorting on one data grid for one type of record on a separate tab or page, and then to use a modal dialog to either add or edit another type of entity?
Answer: It's not a bad practice in general if you have a reason for it and the visual and interaction design will be good. On the other hand yes, it might be confusing and happens to be confusing in software that was not designed and implemented properly.

Hope it helps, if not, feel free to attach a sketch of what you have. The CRUD and entity things are pretty hard to parse and imagine just from words.
Answer: it's generally a good practice to not treat objects as "records" in a database, as they vary not only in number of properties, attached entities, etc, but also on importance, and their place in the workflow.
An object might have a full-blown single page datasheet of its own in one workflow, and might be automatically created just from a string in the other - for example, a contact. Current UX of Jira is a perfect example of this.
The "I just want to have a list of entities, which pattern should I use for CRUD operations" question is too general from a UX perspective I believe: for the user, it's never a list of records, it's a list of living things inside their mind, something which is connected to their goals.


No Greeter on Ubuntu 18.04

Question: I updated to Ubuntu 18.04 and now my greeter is gone.
After reboot my computer, I am automatically logged into my GUI.
I understand Ubuntu now uses GDM3, how can I enable/configure its greeter?
Comment: Try `sudo systemctl enable gdm.service && sudo systemctl start gdm.service`.
Answer: Two ideas:

AutoLogin is On
Go to Settings -> Details -> User -> Automatic Login
The Upgrade didn't complete properly
Go to the terminal and verify that the ubuntu-desktop package is installed:
sudo apt install ubuntu-desktop

(ubuntu-desktop requires gdm3 which requires gnome-session which manages the login session so, presuming you haven't changed any configs, ensuring ubuntu-desktop is installed should fix a lot of things.)

There are more things that you could have messed up somehow, but these are the easiest to fix.

No Greeter on Ubuntu 18.04


Database connection/update mechanism for continuous data

Question: I am working on system where there are huge (2000-5000 records per minute) amount of incoming events which have to be recorded in the database (SQL server 2000). We are using ODBC connection to connect with the database.
Currently we open a single connection during the app startup and push the data using the connection since we won't be able to get a new connection during every record addition due to the huge amount of data getting pumped in. The challenge we face is this: when there is a network failure or the connection is intermittent, the data doesn't get pushed into the database (of course, we get a CDBException if there is an issue with the network). But it will be too late to restore the connection because more events keeps pouring in. Neither it is possible to check for the validity of the connection each time we insert a record because it is a time-consuming job.
I thought of a method to overcome this issue.

Use a cache/buffer to hold the
  incoming alarms/events and push them
  into the database
  once in 'n' seconds and/or once the
  buffer reaches a certain size.

Will this solution prove helpful? Is there any alternate approach to solve the problem?
Thanks.
Answer: I was about to suggest using a cache or buffer to hold the incoming events and batch insert them but I see you've thought of that already.
You should take a look at MSMQ which could be what you're looking for.
Answer: I'd have the client write to a file with a date and time in the name.  After N records are written, stop writing to that file (start writing to a new file) and have BULK INSERT (Transact-SQL) insert that "completed" file.  You could add a cleanup routine to delete files that were processed into the database.


How to store a python module and data in a directory, and import that module with acess to the data

Question: setup
I have the following structure (printed using tree from project root):
└── stuff
    ├── __init__.py
    ├── mod.py
    └── stuff_data.py

I would like to be able to open an ipython session from the project root, and do the following:
import stuff.mod

But it's not currently working.
 file content
The files have the following content:
stuff_data.py
paper = {"type_0": "lined", "type_1": "plain"}

mod.py
from stuff_data import paper

def f():
    """print something...
    """
    print(paper)

When I try the following (from project root)
import stuff.mod

I get the error
----> 1 from stuff_data import paper
      2
      3
      4 def f():
      5     """print x + 1

ModuleNotFoundError: No module named 'stuff_data'

I'm wondering either - how I should structure things so that I'm able to use
them in the way I've outlined above. Or - what should be done instead.
Answer: Your mod.py file's import should either be a relative import:
from .stuff_data import paper

OR
an absolute import starting from the project's root:
from stuff.stuff_data import paper

Comment: Yeah, if you use an import without the `.` prefix, it always has to be in a module or a package that's importable in your path. The relative vs absolute import is really only a matter of preference. I *personally* prefer absolutely ones almost always just for making it extra clear where the module is coming from. Others prefer relative ones because this allows moving around modules which import each other easier as a group.
Comment: Thank you, this works. Is this because - when I run python (or ipython) from
the project root, all executions are carried out from that location,
therefore it's necessary to put the `stuff.stuff_data` in the import? I would
be interested if there are any cases where one might prefer to use a relative
import over an absolute, and visa versa? In short - how might one choose between using
a relative import or absolute?


Roblox Suddenly Lagging

Question: So I know there are similar questions on Google, but they had something to do with their Nvidia driver, which I don't have or any way to get it (I'm just a kid, I don't have enough knowledge to go through my PC stats and get an Nvidia driver or whatnot).
I did try the reducing lag methods (such as going into Roblox studio and turning off frame manager and changing the render distance to a lower resolution), but I still get stuttering frames, just barely-noticeable but gameplay-changing amounts of lag and just overall server lagging (pressing a key and the function of the key happening about a second later, people teleporting and such).
This isn't my PC problem - my 2 PCs had no problem running Roblox about 2 days ago, then one day I turned on my wireless PC and it just seems to have lag. I thought this may be just it being wireless and tried my wired one, but that had the exact same problem. I also tried disabling my antivirus on my big PC, which did seem to get rid of a tiny bit of lag but still lagging the same way nonetheless. Others seem to not have this problem, re-installing or restarting the PC doesn't work, and Roblox didn't update until today (which still lags). This is extremely frustrating, any help will be appreciated.
Comment: Did you try to visit other simple games, such as Escape Prison Obby? Whenever I play complex games like Jailbreak I often lag.
Comment: Well I only tried Void Script Builder and Reason 2 Die, and even in completely empty VIP servers in VSB it still had the same lag.
Comment: And that still doesnt explain why I suddnly started lagging in games that ran perfectly fine before on both pc's.
Comment: I tried the game, it doesnt have people teleporting, but my chat still takes about 1 second to get sent.
Comment: Also, I can no longer hold the backspace button to delete all my messages like in here, if that mattered(I have to spam-tap backspace to delete my chat, unlike just holding them)
Comment: AND NOW CLICK FUNCTIONS DO NOT WORK PROPERLY. SOMEONE HELP!
Comment: maybe your internet connection is not good?
Comment: Another suggestion: play roblox on an ipad (with keyboard if you do not get used to joysticks), it does not lag that much.
Answer: You are talking about the Nvidia driver. Do u mean you just need to update it? If so, its extremely easy to update a graphics card driver. Assuming you are running windows, just go to Device Manager, open display adapters, and select your graphics card. Then, click the upgrade driver software button on the top of the window. (The one with the green arrow pointing upwards). That's it.

Roblox Suddenly Lagging


SQlite3 syntax error UPDATE statement on flask - python

Question: i've developed a APIful webapp using sqlite3 and flask framework with python, i have an external client that sends POST request, and it works correctly.
On my Windows environment the update query works correctly, when i try to execute all on my CentOS environment my query it return a syntax error, the following code is:
    @app.route('/apis/rcvInfo', methods=['POST'])
    def form_to_json():
        if request.method == "POST":
            table=request.form['table']
            status=str(request.form['status'])

            ####query operations
            nEntries = (sendQuery("SELECT COUNT (*) AS RowCnt  FROM "+table))[0]
            if (nEntries > 0 ):
                sendQuery("UPDATE "+table+" SET status = "+status+", lastcheck=CURRENT_TIMESTAMP ORDER BY lastcheck DESC LIMIT 1")
            else:
                sendQuery("INSERT INTO "+table+" (status) VALUES ("+status+")")

            db.get_db().commit()

            return json.dumps({'success':True}), 200, {'ContentType':'application/json'} ```

def sendQuery(query):
    cursor = db.get_db().cursor()
    print (query)
    cursor.execute(query)
    records = cursor.fetchone()

    return records

On my Windows environment the UPDATE statement work correctly, updating the first row.
But on my CentOS env i have the following error message:
sqlite3.OperationalError: near "ORDER": syntax error
The params (table, status) are correct.
Comment: Does UPDATE really have an ORDER BY clause in SQLite?
Comment: Can't see how this error is OS-specific. Generally in SQL, `ORDER BY` is not used in `UPDATE` actions.
Comment: From: https://sqlite.org/lang_update.html#optional_limit_and_order_by_clauses: *If SQLite is built with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT compile-time option then the syntax of the UPDATE statement is extended with optional ORDER BY and LIMIT* So no, ORDER BY is not supported in UPDATE in common releases of SQLite.
Comment: @jarlh why in my windows environment it works?
Answer: As mentioned in 2.3. Optional LIMIT and ORDER BY Clauses:

If SQLite is built with the SQLITE_ENABLE_UPDATE_DELETE_LIMIT
compile-time option then the syntax of the UPDATE statement is
extended with optional ORDER BY and LIMIT clauses...

So in a common release of SQLite you can't use ORDER BY and LIMIT with an UPDATE statement.
In your case as a workaround, if the column lastcheck contains unique values you can do this:
UPDATE tablename
SET status = ?,
    lastcheck = CURRENT_TIMESTAMP
WHERE lastcheck = (SELECT MAX(lastcheck) FROM tablename)

or:
UPDATE tablename
SET status = ?,
    lastcheck = CURRENT_TIMESTAMP
WHERE lastcheck = (SELECT lastcheck FROM tablename ORDER BY lastcheck DESC LIMIT 1)

If the column lastcheck does not contain unique values you could use the column rowid in the ORDER BY clause of the subquery to break any ties:
UPDATE tablename
SET status = ?,
    lastcheck = CURRENT_TIMESTAMP
WHERE lastcheck = (SELECT lastcheck FROM tablename ORDER BY lastcheck DESC, rowid DESC LIMIT 1)


What is the best way for algorithm about insertion

Question: I have to choose the best choice of insertion algorithm
1.before inserting the data  ,we have to search the proper place
by the binary search.After getting that place ,we insert it by kicking every right-hand index(after that wanted place) to the next
right cell.Then, we can insert my data into that proper place.
2.putting the data into the last place of that array.And sort it by Merge Sort.
I have guessed that first choice takes time O(logn) (binary search), and O(n) search the proper place. Can I conclude that it all takes time totally O(logn)+O(n)?
and the second one is O(nlogn) (merge sort), and O(1) (put the data at the last place). Again, can I conclude that it all takes time totally O(nlogn)+O(1)?

If the given size of array is
a.) 30
b.) 2,000,000
which algorithms are suit to each size?
Comment: When adding big-O notation elements, you can simply throw away the smaller one. *O(logn)+O(n)* is the same as *O(n)*, *O(nlogn)+O(1)* is the same as *O(nlogn)*. Once *n* becomes large enough, the smaller terms simply become insignificant in comparison.
Answer: if you have sorted list already, inserting new elements to list one by one makes more sense to me.
if you have an array. It makes sens to go another approach.


Duplicate entries in webix datatable when changing state of ui-router in angularJs

Question: I am having problems with webix datatable.
I am boulding an application with AngularJs and ui-router with webix integration.
When i refresh my site, everything is O.K. But when i redirect to another view the datatable load duplicate entries.
I am using webix and firebase extensions.
I think this is somehow related to angular so i please for an answer.
Thanks!
Answer: Most probably you have some problem with data IDs. Webix widgets may render data twice if .load was called twice and each time data with different ( or missed IDs ) was loaded.
If you have a .load somewhere in your code, try to prepend it with .clearAll call
<code>grid.clearAll();//delete an existing data
grid.load("some");//load new data
</code>


x-editable : turn off inline editing for non admin users

Question: I am using X-Editable plugin for inline editing with angular.js
In-line editing is working perfect. But, I want to disable this feature for non-admin users.
HTML:

   {{ user.name || 'empty' }}

JS:
var app = angular.module("app", ["xeditable"]);
app.run(function(editableOptions) {
  editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

app.controller('OnaftersaveCtrl', function($scope, $http) {
$scope.user = {
  id: 1,
  name: '<?=$test?>'
};

$scope.updateUser = function() {
    $http({
        method: 'post',
        url: '/test',
        data: $scope.user,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
      }).
      success(function(response) {
          alert(response);
      }).
      error(function(response) {
          alert("not ok");
      });
      return false;
    };

});
I tried to putting html code in the id.
$('#myselector').editable('option', 'disabled', true);

But, It's not rendering the initial value. (here it's test variable which is coming from php).
Answer: I need to have the same functionality, I found a few issues on https://github.com/vitalets/angular-xeditable/pull/206, but non of them wore fixed. I had to finish fast my task so I choose to replace the element with anotherone that dosent have the editable atributs.

And in my controller I have:

$scope.accounts.editOptions.isEditable = false;
$scope.accounts.editOptions.toggleEditability = function() {
    $scope.accounts.editOptions.isEditable = !$scope.accounts.editOptions.isEditable;
};


$K[X]_X$ is not integral over $K[X]$

Question: The localization $K[X]_{X}$ is a ring extension of $K[X].$ I want to show that $K[X]_X$ is not integral over $K[X]$ using lying above.
I tried to find a maximal ideal in $K[X]_X$ whose contraction in $K[X]$ is not maximal ideal, or maybe we can produce two prime ideals above one containing another whose contraction is the same prime ideal. I need some help to construct such prime ideals. Thanks.
Comment: Rings of fractions are almost never integral over the original ring.
Comment: Do you mean if $S$ contains a non unit then $S^{-1}A$ is not integral over $A$
Comment: When $A$ is an integral domain, yes.
Comment: See my answer for details on the fundamental property mentioned by @user26857
Answer: Your second approach cannot work because this does not imply that the lying over property fails. For example, the extension $\Bbb{Z}\subset\Bbb{Z}[i]$ is integral and hence has the lying over property. But the two prime ideals $(2+i),(2-i)\subset\Bbb{Z}[i]$ satisfy
$$(2+i)\cap\Bbb{Z}=(2-i)\cap\Bbb{Z}=5\Bbb{Z},$$
so their contraction is the same prime ideal.
Instead, consider the prime ideal $(X)\subset K[X]$. If there is a prime ideal $\mathfrak{q}\subset K[X]_X$ such that $\mathfrak{q}\cap K[X]=(X)$ then in particular $X\in\mathfrak{q}$. But $X$ is a unit in $K[X]_X$ and so $\mathfrak{q}=K[X]_X$, a contradiction. So there is no prime ideal lying over $(X)$.
For some more perspective; in general when localizing a (commutative unital) ring $R$ with respect to a multiplicative subset $S$, the set of prime ideals of $R_S$ corresponds bijectively to the set of prime ideals of $R$ that are disjoint from $S$. The bijection is given by taking contractions/extensions w.r.t. the localization map $R\ \longrightarrow\ R_S$.
In this particular case, the set of prime ideals of $K[X]_X$ corresponds bijectively to the set of prime ideals of $K[X]$ that do not contain any power of $X$. These are all prime ideals except $(X)$, and every prime ideal of $K[X]$ except $(X)$ is the contraction of a prime ideal of $K[X]_X$.

[Original answer, where I mistook $K[X]_X$ for $K[X]_{(X)}$.]
As you say, the ring $K[X]_X$ is local, so there is only one maximal ideal, which is the ideal generated by $X$. Its contraction in $K[X]$ is the ideal generated by $X$ there, which is also maximal, so this approach won't work.
The only other prime ideal of $K[X]_X$ is the zero ideal, which contracts to the zero ideal in $K[X]$, which is also prime. So this approach won't work either.
However, this does show that the extension does not have the lying over property; the ring $K[X]_X$ has only two prime ideals whereas $K[X]$ has infinitely many. So there must be some prime ideal of $K[X]$ that is not the contraction of a prime ideal of $K[X]_X$.
Comment: $K[X]_X$ is localization wrt the multiplicative closed set $\{1,X,X^2,\ldots\}$
Comment: Ah, I read it as the localization w.r.t. to (the complement of) the prime ideal $(X)$. See my new answer.
Answer: Haven't seen a proof like this yet so let me write down:
Suppose otherwise $K[x]_x$ is integral over $K[x]$. Since $1/x\in K[x]_x$, it is the solution of a monic polynomial over $K[x]$, that is:
$$\left(\frac{1}{x}\right)^n+f_{n-1} \left(\frac{1}{x}\right)^{n-1}+\cdots+f_0\equiv 0$$
where $f_i\in K[x], i=0, \cdots, n-1$ are the coefficients. Clearing denominators (multiplying both sides with $x^n$) to obtain a polynomial relation in $K[x]$:
$$1+f_{n-1} x+\cdots+f_0 x^n\equiv 0.$$
However this is impossible since the left side has a non-zero constant term: letting $x=0$ gets an equation $1=0$.
Comment: This is just a rearrangement of the proof in my answer ($2$ years prior). I scale by $\,x^{n-1}\,$ to get $\,x^{-1}=g(x)\in K[x]\,$ vs. you scale by $\,x^n\,$ to get $\,1 = xg(x),\,$ i.e. your proof is mine scaled by $\,x.\,$ Both show $x$ is a unit in $K[x]$. I did it that way  because it  clarifies the generalizations I mention.
Answer: Here is a conceptual view:  a crucial ($\rm\color{#c00}{characteristic})$ property of integral ring extensions is that they don't alter unit properties in the base ring, i.e. a nonunit $\,r\in R\,$ remains a nonunit in any integral extension ring $S.\,$ [For example, this may allow us to deduce that Diophantine equations in $\Bbb Z$ are unsolvable by deducing a parity contradiction $\,2\,|\,1\,$ in any number ring with parity, or a proof that $(9+4\sqrt{5})^n + (9-4\sqrt{5})^n$ is even]. Thus the  nonunit $X\in R[X]$ must remain a nonunit in any integral extension (so the OP extension is not integral since it inverts $X$)
A proof is easy: below specialize $\,u \in R\,$ to get $\,\bbox[3px,border:1px solid #c00]{u^{-1}\text{ is integral over }R\! \iff\! u^{-1}\in\ R\,}$
Lemma $ $ Suppose  $\,R\subset S\,$ is an integral extensions of commutative rings and $\,u\,$ is a unit in $S$. Then $u^{-1}$ is integral over $R\iff u^{-1}\in R[u]$
$\begin{align}{\bf Proof}\ \ \ u^{-1}\ \text{is integral over } R&\iff u^{-n} =  r_{1} u^{-(n-1)}+\cdots +\, r_n,\:\! \ \ \ \ {\rm for\ some}\ \ r_i\in R\\
 &\!\!\overset{\times\ u^{\large n-1}\!\!}\iff u^{-1} =\,  r_{1}\ +\ \cdots\,\ +\,\ r_n\, u^{n-1},\ \ {\rm for\ some}\ \ r_i\in R \end{align}$
Generalization $ $ More generally it is easy to prove that $R[u]\cap R[u^{-1}]\,$ is integral over $R$.
Viewed in terms of ideals the key property is: $ $ principal ideals $\:\!(r)\:\!$ survive in integral extensions, i.e. $\, rR\neq 1\,\Rightarrow\, rS\neq 1.\,$ Integral extensions can be nicely $\rm\color{#c00}{characterized}$ by various universal forms of such ideal survivability, e.g. see the paper of Coykendall and Dobbs cited here.

$K[X]_X$ is not integral over $K[X]$


Zend DB with Postgres problems with nextval()

Question: Ok this is a 2 part question, first primary concern is the nextval() bit. I have a table where one of the columns is an auto incrementing column. Being fairly new to postgres and Zend DB I am running into trouble. Inserting a new row on to a table.
This is what i have thus far (and in the CLI this works). But not in the Zend DB stuff..
class Comments extends Zend_Db_Table_Abstract
{

    protected $_name = 'comments';

    public function setComment($comment_id = null, $id = null, $comment = null)
    {
        if(($comment_id == null)||(empty($comment_id))||(trim($comment_id) == '')){return false;}
        if(($id == null)||(empty($id))||(trim($id) == '')){return false;}
        if(($comment == null)||(empty($comment))||(trim($comment) == '')){return false;}

        echo 'check one';

        $db = Zend_Db_Table::getDefaultAdapter();
        if($comment_id == "none")
        {
            $created = time()*1000;
            $data = array(
                        "comment_id" => nextval('comments_comment_id_seq'),
                        "comment" => $comment,
                        "comment_level" => 1,
                        "is_active" => true,
                        "status" => 0,
                        "id" => $id,
                        "user_id" => $_SESSION['role']['user_id'],
                        "ts_create" => $created,
                        "ts_mod" => $created
                    );
            $table->insert($data);
            return true;
        }

    }
}

The Error I am getting is:

Fatal error:  Call to undefined function nextval() in
  /home/src/branches/portal/application/model/Comments.php
  on line 45

So Not really sure how to adjust for that. I am more familiar with mySQL where I could just drop NULL and it would auto increment. So all in all the big problem is the nextval, does Zend DB have anything in the framework that I can fix this issue with?
Next part, since this is a two part question. By using $table->insert($data); is that going to automatically use the $_name variable? I read through the Zend doc on the subject but its confusing me a bit currently as how to define the right table in the case of an insert.
Comment: There is no php function called `nextval`
Comment: yes I know theres no php function nextval. but with postgres there is.
Comment: so call postgres function, not php's one ;-)
Answer: Use this:
"comment_id" => new Zend_Db_Expr("nextval('comments_comment_id_seq')"),

Comment: overall I just had my first successful insert, now on to the update part. Anyway I thank you for your help.
Comment: ok, so the error I was getting is now gone, I appreciate that. I dunno where you found that but, awesome call. Now I my second part of the question where i was wondering about the insert part seems to be true where thats failing. Any idea on that?
Comment: @chris: what if you try first and see?
Comment: I did, Im getting an error for undefined I am guessing $table is the undefined bit, as I said, the insert/update stuff has me a bit confused with the Zend DB stuff. This is maybe the first time Im seriously taking a crack at using ORM layer for SQL related things. So Im a bit off my game til I understand it better
Comment: @chris: and what is the **actual** error? The guesses is a cool thing, but programmers work with facts
Comment: Yea, I just figured it out, copying from examples and working from them, my variable is `$db` not `$table` and then it looks like I can actually do something like `$db->insert($this->_name, $data)` when I was digging through the examples on the Zend site, it only expressed the $data variable being passed in the insert function.


Cannot use some methods in F# from C# class

Question: I am having hard time figuring out why I cannot see/use some methods from C# type in F# function.

<code>public class KafkaBus : IKafkaBus
{
    // this works and can be used
    public IObservable<Shared.Model.Message<T>> CreateConsumer<T>(string topic, Func<byte[], T> deserialize = null)

    // those cannot be found
    public Task<Confluent.Kafka.CommittedOffsets> CommitAsync<T>(Message<T> message)
    public Task<Confluent.Kafka.CommittedOffsets> CommitAsync(string topic, int partition, long offSet)
}
</code>
If I check object browser in F# solution under references, I see those methods listed:

I am using VS 2017 15.3, .NET Framework 4.6.1, library is referenced via nuget.
Comment: If you type the `CommitAsync` code in, ignoring the fact that it doesn't appear in intellisense, and then build, does it compile? If not, what's the error?
Comment: Your code sample shows a `Bus` class but your last screenshot is for the `KafkaBus` class. Is that a mistake?
Comment: Sorry for making this even harder. It was a mistake. Now class naming aligned.
Comment: You should also look out for the fact that intellisense won't update between C#/F# projects until you build them.
Comment: Yes, rebuilding is like ceremony already :)

Here is the error:
Error FS0039 The field, constructor or member 'CommitAsync' is not defined. Gateway Service.fs 31 Active
Comment: Do you see the methods if you cast to the interface, ```(kafkaBus :> IKafkaBus).```
Comment: Tried that with no luck :/
Comment: Grasping at straws here: What type is `kafkaBus` in your F# code?  If it's an `IKafkaBus` and `CommitAsync` is only defined in the `KafkaBus` class, that could explain the missing members...
Comment: Hello Wilson, nice shot but unfortunately it is KafkaBus. Anyway, IKafkaBus expose same contract so it should not be different either using one or another.
Comment: Made sure that all reference paths are exactly as you expect?  I've often been building Debug mode and referencing a Release path...
Comment: Cannot really reproduce the problem in VS2015/.net 4.6.1. Could you be a bit more specific: which version of VS? Which .net version are your projects targeting? How do you reference which libraries (nuget / vs referncing projects vs referencing DLL-s directly)? Does your F# project reference Confluent.Kafka as well?
Comment: Hi, updated, it does reference Confluent.Kafka as well.
Answer: So in the end reopening project, rebuilding or simply restarting a machine helps the cause... Seems like a bug in Visual Studio. Got help on MSDN forums


New 40A EVSE Wiring Install

Question: I want to install a 40A electric vehicle charger (probably a ClipperCreek HCS-50) in my unfinished attached garage in the Puget Sound area of Washington State. I intend to have this inspected and permitted, but it's been a good learning experience in a variety of ways already.
I haven't installed a branch circuit before, but this seems about as dirt-simple as it could get: the location I'd like to put the EVSE is about 20 feet away from my service panel, which has open slots on it and sufficient extra capacity in the 200A mains breaker.
To do the install, I've purchased 25 feet of 6/3 NM-B (ampacity 55A) and a 240V 50A breaker that matches my panel brand. I will run the 6/3 along the same path of already drilled holes in the exposed studs to the point where I'll put a NEMA 6-50 receptacle.

I'm not clear on whether it's necessary to have a bushing on the entrance to the box where the receptacle will go, but intend to add one to err on the side of caution.
I believe the routing through the studs means that I shouldn't need any further protection from physical damage. I think the hole bored through the stud counts as supports, but the cable will still need to be secured within 12" of each end. I'm not sure how proscriptive this is, but I'd like to use screw-in cable guides similar to this:

The path of the cable is near EPS insulation, but there's only one cable there now, so 310.15(B)(3)(a)'s adjustments shouldn't apply.
It's indoors, it's a dry location, so normal NM-B is sufficient.

Are there any major obstacles I haven't accounted for, or any likely gotchas that I'll hit during an inspection?
This is similar to the question Questions regarding my plan for new 50A circuit (with pictures), but I believe it's sufficiently different to merit its own question.
Comment: If you're under NEC2017, you may consider making the breaker a GFCI or hard-wiring instead of using the receptacle. NEC 625.54 says you need GFCI protection if using a receptacle.
Comment: You do need a bushing, the studs are all the support you need but the hole must be 1-1/4" away from the face of the stud if closer than 1-1/4" a nail plate will be required. I would verify that the hole is back and if closer than 1-1/4" put the plates up. In my jurisdiction the open wiring required cover below 8'. 1/2" plywood or Sheetrock is acceptable. + for Phillip on the GFCI requirement if a receptacle.
Comment: Note for the rest of the folks here: if you're looking in your Codebooks and can't find 625.54, that's because it isn't there -- the NFPA left it out by accident and had to fix that with [TIA 70-17-2](https://www.nfpa.org/assets/files/AboutTheCodes/70/TIA_70_17_2.pdf)
Comment: By unfinished, do you mean no sheetrock at all?  Just bare studs?
Comment: Yep, just bare studs between the panel and where the receptacle will go.
Comment: They have insulated staples for attaching the NM-B to wood studs and there are standard connectors to attach the NM-B to the metal box.
Comment: I was thinking about hardwiring it, but I was hoping to not pull the trigger on the EVSE until after the inspection, and am unsure how the inspector would feel about me just terminating the circuit into a junction box with some wire nuts. Edit: having GFCI on that honestly doesn't seem terrible, either...
Answer: If it's cord-and-plug, you need a GFCI breaker...
If you are cord-and-plug connecting your EV charger, then you'll need a 50A GFCI breaker instead of the regular breaker as per 2017 NEC 625.54 (as specified in TIA-70-17-2):

625.54 Ground-Fault Circuit-Interrupter Protection for Personnel. All single-phase receptacles
  installed for the connection of electric vehicle charging that are rated 150 volts to ground or less, and
  50 amperes or less shall have ground-fault circuit-interrupter protection for personnel.

...but, leaving the wires nutted off in the box is OK for a hardwired setup
If you intend to hardwire it, though, you can simply terminate the circuit into a junction box with some wire nuts (and a cover if you intend to install it after the final electrical inspection).
As to the rest of the bits...
Getting the cable into the box requires a cable clamp, made of either plastic or metal; this goes into a knockout in the box and holds the cable jacket firmly in place. However, some plastic boxes have integral cable clamps instead of knockouts; with those, you do not need to install a separate clamp.
Attaching the cable to the studs near the endpoints is done using a NM cable staple or strap; these have a somewhat rectangular profile to them to match that of the NM cable itself.  (The clip you depict in your photo looks to be intended for low voltage wiring such as coaxial and communications cables; a NM cable will simply be too big to fit into it.)
Comment: Thanks! The cable clips I have are physically large enough for the #6 cable, but I wasn't sure if low-voltage / data straps would be count, given the "approved and identified" language.

New 40A EVSE Wiring Install


Volume control command

Question: Is there a way to control volume of a remote system via ssh? we have a media center server and we want to remotely control the volume.
Answer: Thought it's not a command per-se, alsamixer is great for this kind of thing. It's part of the alsa-utils package
Comment: super awesome, thanks. that's what we've been looking for.
Answer: You can also write a bash script using pacmd utility of PulseAudio sound system.
I have found an example script for you: pulsevol.sh

Volume control command


Dynamic canvas chart with jquery slider

Question: I am using a canvas library for creating a dynamic chart to see the overflowing data using jquery UI-scroll, But the scrollbar always coming on the left-hand side If a user wants to see initial plotted data they need to scroll it to the left-hand side. But I need a scrollbar always in the right.
<code>var scrollbar = $(".scroll-bar").slider({
  max:6,
  min:0,
  slide: function( event, ui ) {

  }
});
</code>
Please find my code:
https://jsfiddle.net/canvasjs/082at1u5/
Answer: CanvasJS has recently released StockChart which comes with inbuilt slider. Please check this resource (https://canvasjs.com/docs/stockcharts/stockchart-options/navigator/slider/) for more information.
Also, please check this example for a dynamic chart with slider - https://canvasjs.com/javascript-stockcharts/dynamic-stockchart-navigator/

Dynamic canvas chart with jquery slider


My Terabyte hard drive only has 931mb free?

Question: I just used boot and nuke to wipe my hard drive and reinstall my OS systems. When selecting the hard drive I noticed that there were only 931gb free in my hard drive.
Is this normal? It sees like a strange number as I though terabyte drives held 1024gb.
Is some of the hard drive hidden? Are there any programs that can check?
Thanks in advanced for any help with this!
df -h returns the following:
Filesystem           Size  Used Avail Use% Mounted on
udev                 3.9G     0  3.9G   0% /dev
tmpfs                786M   18M  768M   3% /run
/dev/sda5            437G  5.7G  409G   2% /
tmpfs                3.9G   31M  3.9G   1% /dev/shm
tmpfs                5.0M  4.0K  5.0M   1% /run/lock
tmpfs                3.9G     0  3.9G   0% /sys/fs/cgroup
tmpfs                786M   20K  786M   1% /run/user/124
/home/*/.Private     437G  5.7G  409G   2% /home/*
tmpfs                786M  2.0M  784M   1% /run/user/1000

lsblk returns the following:
NAME           MAJ:MIN RM   SIZE RO TYPE  MOUNTPOINT
sda              8:0    0 931.5G  0 disk
├─sda1           8:1    0   500M  0 part
├─sda2           8:2    0 478.8G  0 part
├─sda3           8:3    0   496M  0 part
├─sda4           8:4    0     1K  0 part
├─sda5           8:5    0 443.9G  0 part  /
└─sda6           8:6    0   7.9G  0 part
└─cryptswap1   253:0    0   7.9G  0 crypt [SWAP]
sr0             11:0    1  1024M  0 rom

EDIT: I am literally installing the dual boot system as we speak. Windows first, here is a breakdown of what Windows 10 sees:

So total size is 931.51GB. That is a very strange number.
Comment: What are the outputs of `df -h` and `lsblk`? [edit] your question to include that information. And by the way a TerraByte is supposedly 1024 GigaByte.
Comment: @Berrik on the other hand ravery is right, due to the switch from powers of two to use scientific thousand we now have GiB and GB, one of which is using 1000 where as the other uses 1024 and so on, due to that many programs still show power of two you are left with an amount less than the manufacturer of the drive announces on its label.
Comment: 1 TB = 1,000 GB =  1,000,000 MB =  1,000,000,000 KB = 1,000,000,000,000 bytes = 976,562,500 KiB = 953,674.31640625 MiB = 931.322574615478515625 GiB
Comment: @Berrik read my comment.
Comment: @Berrik No. An MiB is 1024 KiB. ~931.51 GiB the size of a 1 TB disk. A 1 TiB is 1,099,511,627,776 bytes.
Comment: Just installing OS's as we speak. Will update it once I'm on Ubuntu 17.10 (haha thanks for correcting mb to gb, I totally overlooked that).
Comment: @Videonauth - for years drive manufactures have used 1000 instead of 1024, that is why we now have GB and GiB designations. Additionally some space is used for the file system (partiton and file tables) so 931 GB free sounds about right for a terabyte drive.
Comment: @ravery I do know that, if you check the [edit history](https://askubuntu.com/revisions/980055/1) on the question you might see why I wrote what I wrote.
Comment: Or just read my comment for some clarity @ravery. The issue was that this should be a clean disk, so even before installation I would have expected there to be a larger capacity then 931gb it's not even a round number...
Comment: All good supporting information guys, but it doesn't explain the strange disk size... 931.51GB is a strange number that doesn't fit with the GiB/GB sizes (which is why I am asking the question in the first place).
Comment: @jdwolf I mainly use Ubuntu but dual boot the system just in case something goes wrong. I see so a MiB is 931.32. It's still a bit strange, I'm getting 931.51 on the hard drive
Answer: it's because Gigabyte (GB) can have different meanings in different contexts. When referring to computer memory, gigabyte is always a "power of two" = 1,073,741,824 bytes, but when measuring hard drive capacity it is often defined as 1,000,000,000 bytes. Generally, operating systems calculate disk and file sizes using binary numbers, so a new 500 GB drive you've just purchased would be reported by the OS as "465.66 GB" (meaning 465.66 GiB, GiB = Gigibyte). so 1 TB hard disk means 1,000,000,000,000 bytes and if you divide it by 1024^3 to convert it to Gigabytes, you see the result is: 931.322574615 GB
Comment: Well drive manufacturers use the scientific notation Gigabyte (GB) while most programs as well show falsely GigaByte (GB) instead of powers of two GibiByte (GiB). @Berrik see [here](https://www.google.de/search?q=GigaByte+GibiByte).
Comment: 1,000,000,000,000 bytes = 1 TB
1,000,000,000,000 / 1024 / 1024 / 1024 = 931.322574615478515625 GiB
Comment: Alright time ot actually answer this
Comment: Just one minor Correction GB has no different meaning nowhere it is either GiB or GB.
Comment: Right I understand that 1TB means 1,000,000,000,000 bytes and that hard drives vary in size i.e. 1TB is usually 1024GB but I don't understand how you got to "931.322574615 GB". 1024^3 is 1,073,741,824... I think I misunderstood a step...
Comment: @Videonauth yeah but all operating systems use GB instead of GiB.
Comment: Right... well the drive is .19GB over what it should be, again suggesting to me that something isn't adding up. Would there be any reason for such a small variant or am I just being too ocd about it?
Comment: @Berrik Who said your drive was exactly 1,000,000,000 bytes? ;3
Answer: The discrepancy with the displayed number is do to the fact that hard drive manufactures are aiming for a number closer to
1,000,000,000,000 bytes which is 1 TB.
while windows and Linux present you with a unit of 1024 not 1000 although on Windows this is GB and on Linux this is the more accurate GiB.
1 TiB would have to be 1,099,511,627,776 bytes.
If we go the nearest GiB with only 1,000,000,000 bytes this is the math:
1,000,000,000,000 bytes / 1024 = 976,562,500 KiB
976,562,500 KiB / 1024 ~= 953,674 MiB
953,674 MiB / 1024 ~= 931 GiB

However don't make the assumption that hard drive manufactures make disk platters that exactly add up to 1,000,000,000,000 bytes they do not. Still the same unit conversion discrepancies apply.
Comment: 931.51GB / 2 = 465.755 * 8 = 3726.04Gb <- note lower case b.
Comment: Woo. An answer I can understand! For bonus points what's half of 931.51GB in bits?
Comment: Thanks again everyone. This cleared up the question I had. Once I install Ubuntu 17.10 I'll update the question with the relevant Ubuntu perspective!


Supposedly simple integral

Question: While working on a differential equation I stumbled on this integral:
$$\int_0^x\frac{e^{-t^2}}{a^2+t^2}dt,$$
where $a\in \mathbb{R_{>0}}$.
At first glance it looks so simple that it's ridiculous that I can't find closed form expression for it.
Can someone help me with this beast?
$Edit:$From the comments, it doesn't seem to exist a closed form. I tried a series expansion by writing the integrand as $e^{-t^2}g(t)$ and take the Taylor expansion of the function $g(t)$. It's a good approximation and it's possible to integrate the expression found but it's only valid for small values of $x$ since the series diverge.
Comment: @par I wasn't implying that it does. I was just answering the first two comments.
Comment: I'm not sure it has a closed expression. Try to exchange the integrals, hopefully the other direction gets you some $t$ as multiplier.
Comment: Or, perhaps, do you want its limit as $x\to\infty$?
Comment: @Berci Well, there's no other integration to be made. I have a ODE whose solution is $f(x)=\int_0^x \frac{e^{-t^2}}{a^2+t^2}dt+...$. So I can't take the limit.

I'm sorry if I misled you with the way I wrote the question.
Comment: I would guess that this does not have an expression in terms of elementary functions.
Comment: @PML: Just because it is an ODE does not mean its solution can be expressed in terms of elementary functions.
Comment: [This](http://math.stackexchange.com/questions/155/how-can-you-prove-that-a-function-has-no-closed-form-integral) question may be relevant. Trying to solve the differential equation mentioned in the accepted answer leads to an integral similar to this one, so I'm not sure how useful it is.
Comment: @JavierBadia Very nice reference. Well my equation is second order but indeed it can be put in the same form as that equation. The difference is in the non-homogeneous part (their $f$ function). That theorem is very useful but it says nothing about special functions. For example the integral of $e^{x^2}$ is itself a function.
Comment: I just ran it through Mathematica (which has quite advance formulas and algorithms for integration)... and nothing. In all likelihood, there is no closed form.
Comment: Why this question not tagged [tag:definite-integral]?
Comment: @paul2357paul I forgot to add it. I just edited  the question.
Answer: $\int_0^x\dfrac{e^{-t^2}}{a^2+t^2}dt=\int_0^x\dfrac{1}{a^2+t^2}\sum\limits_{n=0}^\infty\dfrac{(-t^2)^n}{n!}dt=\int_0^x\sum\limits_{n=0}^\infty\dfrac{(-1)^nt^{2n}}{n!(a^2+t^2)}dt$
Consider $\int\dfrac{t^{2n}}{a^2+t^2}dt$ ,
Let $t=a\tan\theta$ ,
Then $dt=a\sec^2\theta~d\theta$
$\therefore\int\dfrac{t^{2n}}{a^2+t^2}dt$
$=\int\dfrac{(a\tan\theta)^{2n}}{a^2+(a\tan\theta)^2}a\sec^2\theta~d\theta$
$=\int a^{2n-1}\tan^{2n}\theta~d\theta$
$=\sum\limits_{k=0}^{n-1}\dfrac{(-1)^ka^{2n-1}\tan^{2n-2k-1}\theta}{2n-2k-1}+(-1)^na^{2n-1}\theta+C$
$=\sum\limits_{k=0}^{n-1}\dfrac{(-1)^ka^{2k}t^{2n-2k-1}}{2n-2k-1}+(-1)^na^{2n-1}\tan^{-1}\dfrac{t}{a}+C$
Hence $\int_0^x\sum\limits_{n=0}^\infty\dfrac{(-1)^nt^{2n}}{n!(a^2+t^2)}dt$
$=\left[\sum\limits_{n=1}^\infty\sum\limits_{k=0}^{n-1}\dfrac{(-1)^{n+k}a^{2k}t^{2n-2k-1}}{n!(2n-2k-1)}+\sum\limits_{n=0}^\infty\dfrac{a^{2n-1}}{n!}\tan^{-1}\dfrac{t}{a}\right]_0^x$
$=\sum\limits_{n=1}^\infty\sum\limits_{k=0}^{n-1}\dfrac{(-1)^{n+k}a^{2k}x^{2n-2k-1}}{n!(2n-2k-1)}+\dfrac{e^{a^2}}{a}\tan^{-1}\dfrac{x}{a}$
Comment: This is outstanding!Thank you very much, really. I hope you get many upvotes for the work you've put into this answer. Thank you once again.
Answer: I'll tackle the case of the large values of $x$. Let's express the integral as follows:
$$\int_0^x\frac{e^{-t^2}}{a^2+t^2}dt=\int_0^{\infty}\frac{e^{-t^2}}{a^2+t^2}dt-\int_x^{\infty}\frac{e^{-t^2}}{a^2+t^2}dt=$$
$$=I(a)-\int_x^{\infty}\frac{e^{-t^2}}{a^2+t^2}dt$$
The next step is evaluate the last integral by parts:
$$-\int_x^{\infty}\frac{e^{-t^2}}{a^2+t^2}dt=\frac{1}{2}\int_x^{\infty}\frac{d(e^{-t^2})}{t(a^2+t^2)}dt=$$
$$=-\frac{e^{-x^2}}{2x(a^2+x^2)}+\frac{1}{2}\int_x^{\infty}\frac{(3t^2+a^2)e^{-t^2}}{t^2(a^2+t^2)^2}dt$$
In the last expression, the first term dominates for large $x$ and we have approximately:
$$\int_0^x\frac{e^{-t^2}}{a^2+t^2}dt\approx I(a)-\frac{e^{-x^2}}{2x(a^2+x^2)}$$
We'll get a better result if we continue the integration by parts in the penultimate expression.
Now, consider
$$I(a)=\int_0^{\infty}\frac{e^{-t^2}}{a^2+t^2}dt$$
Let's introduce the parameter $b$ so that
$$J(b)=\int_0^{\infty}\frac{e^{-bt^2}}{a^2+t^2}dt$$
and $I(a)=J(1)$
By differentiating with respect to $b$ we will see that $J$ satisfies the following differential equation:
$$\frac{dJ}{db}-a^2J+\frac{\sqrt{\pi}}{2\sqrt{b}}=0$$
Taking into account that
$$J(0)=\int_0^{\infty}\frac{dt}{a^2+t^2}=\frac{\pi}{2a}$$ we get a solution of this diff-eq:
$$J(b)=\sqrt{\pi}\frac{e^{a^2b}}{a}\int_{a\sqrt{b}}^{\infty}e^{-y^2}dy$$
Finally
$$I(a)=J(1)=\sqrt{\pi}\frac{e^{a^2}}{a}\int_{a}^{\infty}e^{-y^2}dy=\frac{\pi}{2}\frac{e^{a^2}}{a}\text{erfc}(a)$$ where $\text{erfc}(x)=\frac{2}{\sqrt{\pi}}\int_{x}^{\infty}e^{-y^2}dy$ is so called "the complementary error function"
Comment: I'm learning a lot with your answers. I thank you very much with the time you took on your answer. Your approach is very interesting and pedagogical. Thank you once again

Supposedly simple integral


AngularJS filter function explanation

Question: Here is a filter I'm adding to AngularJS:
angular.module('myApp', [])
  .filter('clean', function(){
    return function(input){
      return input;
    };
  })

Can someone explain like I'm five, why the extra anonymous function is needed in order for the data to be returned?
Basically why this doesn't work:
angular.module('myApp', [])
      .filter('clean', function(input){
         return input;
      })

I'm trying to understand what's going on here better so any help would be appreciated.
Answer: We'll they could just do it the other way! But that's what frameworks about, standardization.
Look at the service definition it works in the same way.
But if you look closely in the documents it says that .filter function and others like it should get providers not values. This helps in:

Lazy or not instantiation.
DI and all DI benefits, it lets you define dependency on per-filter basis.

Check the full fiddle http://jsfiddle.net/vAHbr/4/
angular.module('myApp', [])
.filter('discountcurrency',
        // The provider, where we can encapsulate our filter
        // creation code, without having to do JavaScript ninja
        // stuff. As well as this is our chance to ask for
        // dependencies.
        function ($filter) {
        var currency = $filter('currency');

        // The actual simple filter function.
        return function (value) {
            return currency(value - 5);
        }
    });

AngularJS filter function explanation


A bunch of relatively small images are reading at 1 MB/s via Samba

Question: I have a bunch of images of total size of 6Gb, but each of which is relatively small. I am trying to copy these images over LAN and the speed of copying is approximately 1 MB/s.
It is slower than Internet nowadays.
My LAN has gigabit speed. Looks like this is happens only with lots of small files. When I am copying one large file, speed is more than 100 MB/s.
Is it possible to make samba faster for a bunch of small files?
Answer: You can't make Samba faster for small files, because Samba is not the issue.
The best way to transfer a large amount of small files is to compress them into an archive first, and then transfer the entire archive.  You may even find the entire process of compress>transfer>extract to be faster than transferring all the files.
The reason is two parts, overhead, and hard drive operations.  There's more overhead on the network when transferring multiple files compared to a single file since each file has many attributes that go along with it.  And, your hard drive works harder to allocate space to write each packet from its buffer.  If you have a mechanical drive, then you also have to factor in seek time added to it, and the hard drive's operation of fitting the data into sectors.  SSD's aren't affected as much.
You'll find the same problem when transferring files from HDD to HDD, or from USB drive to HDD.  It's the overhead of many individual files.
Comment: The OS could get the entire directory structure, but each file is still transferred one at a time.  It's the network overhead that takes all the extra time, before and after each file is transferred.  It's a small amount of time, but it adds up with thousands of files.  With one large file, there's just less overhead because the transmission is mostly just the data stream of the file's content with minimal packet transfer overhead for data integrity.
Comment: OS could prefetch directory information, why not?
Comment: Why can't SAMBA send several files at a time? May be I can parallelize copying somehow? The question costs 100 times gain!
Comment: Also I don't understand general network overhead. In TCP/IP all data is transmitted in packets. 2Gb single file does NOT transmitted in one packet it split. This is definitely Samba problem.
Comment: The same is with harddrive. It stores data in sectors. If directory is in cache, then reading one big file should be the same as multiple of small.


CSS Box border bottom stick to top?

Question: I am writing my own css, but the strange thing is that the my .content border-top and border-bottom are sticking together.
Here is my code for css:

body{
    width: 100%;
    margin: auto;
    }
header{
    position: relative;
    margin: 20px;
    min-width: 1200px;
    min-height: 70px;
    }
p{
    font-family: courier;
    font-size: 130%;
    margin: 10%;
    }
.content{
    margin-top: 100px;
    min-width: 1200px;
    border-top: 3px solid orange;
    border-bottom: 30px solid rgb(239, 98, 98);
}
.content .col-left{
    width: 20%;
    float: left;
    }
.content .col-mid{
    width: 60%;
    float: left;
    }
.content .col-right{
    width: 20%;
    float: left;
    }
.footer{
    margin-top: 20px;
}
<!doctype html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>IEEI</title>

        <link href="css/reset.css" rel="stylesheet">
        <link href="css/customized.css" rel="stylesheet">

                    Instead of referencing the image directly, stick it within a DIV.
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV

test footer

test footer

I am wondering how to move the red border bottom to the right position.
I have tried to put a new content box in the HTML, the position seems to be OK but messes up the output. I am new to the CSS, please help me out.
Comment: Set the `position` of `.content` to `relative` and `float` to `left`. This should work.
Comment: you're welcome! :-)
Answer: Your .content element only contains floated elements, which "don't count" concerning the borders and size of their container element. Add overflow: auto; to .content to make .content wrap its floating contents:

body{
    width: 100%;
    margin: auto;
    }
header{
    position: relative;
    margin: 20px;
    min-width: 1200px;
    min-height: 70px;
    }
p{
    font-family: courier;
    font-size: 130%;
    margin: 10%;
    }
.content{
    margin-top: 100px;
    min-width: 1200px;
    border-top: 3px solid orange;
    border-bottom: 30px solid rgb(239, 98, 98);
    overflow: auto;
}
.content .col-left{
    width: 20%;
    float: left;
    }
.content .col-mid{
    width: 60%;
    float: left;
    }
.content .col-right{
    width: 20%;
    float: left;
    }
.footer{
    margin-top: 20px;
}
<!doctype html>

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <meta name="description" content="">
        <meta name="author" content="">

        <title>IEEI</title>

        <link href="css/reset.css" rel="stylesheet">
        <link href="css/customized.css" rel="stylesheet">

                    Instead of referencing the image directly, stick it within a DIV.
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV
                    Instead of referencing the image directly, stick it within a DIV

test footer

test footer

Answer: Also would be a good idea to provide some height to the element of .content ID.

CSS Box border bottom stick to top?


How do I quicksave when using a controller?

Question: There is a keyboard shortcut to quicksave (F5), but since I switched to playing with an Xbox controller I can't find any option to quicksave anymore.
Is the option to quicksave hidden somewhere, or is there actually no way to quicksave when using the controller?
Answer: As far as i know there isn't a way to quicksave with a controller, on console the manual quicksave is disabled. The only way i can think about is to use a 3rd party tool like xpadder and bind a specific button to f5.


How to manually execute a function inside a jQuery plugin?

Question: I have a plugin that looks like this:
(function($) {
    $.fn.plugin_name = function(options) {

        var $this = $(this);

        var defaults = {
            // some defaults
        };

        options = $.extend({}, defaults, options);

        var work = {
            action_1: function() {
                // do something
            },
            action_2: function(output) {
                alert('hello world');
            }
        }

        that.submit(function(e) {
            e.preventDefault();
            work.action_1();
        });

        return $this;
    }
})(jQuery);

It's being used like any traditional jquery plugin, by being attached to a page element like so:
$('#search-form').plugin_name({
    // overide options
});

My question is, how can I execute the work.action_2() function that's deeply nested inside the plugin? I would like to call it manually from the javascript console in firebug.
Comment: You recommend that you start by following the plugin authoring guidelines (http://docs.jquery.com/Plugins/Authoring)
Comment: By the way, you have no `that` declared in the code, did you mean `this`?
Answer:
My question is, how can I execute the work.action_2() function that's deeply nested inside the plugin?

You can't, it's outside of your scope!
you can't reach private function variables, just like you can't reach my functions...
Comment: I figured this was the issue, only reason why I needed this was because I am making a call to one of the google apis and they accept a callback function as one of the parameters. Google only recognizes this function if it's in the global sphere. If I put that function outside the plugin then I can't use the plugin's options :(
Comment: @JakeRow123. You can define it the the global scope, and call it with the `options` values. Simple isn't it?
Answer: Create it in a separate utility function if its needed independently, better if its in your own global object.
So you can call it like so: $.myGlobalObj.action_2()


How to get the count of deleted entities

Question: I use the following method to delete a set of objects based on a certain where condition, but in reality the number of removed objects could be lesser than the passed collection. How do I get the actual count of deleted entities
http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/orm/hibernate3/HibernateTemplate.html#deleteAll(java.util.Collection)
Comment: Do a COUNT with the same WHERE clause before and after executing the DELETE command?
Comment: @DanTemple would not work with a busy DB server
Comment: @ScaryWombat Yeah, there'll be time delays in the requests, so the data might not be entirely accurate on a high traffic system. Hence I put it as a comment, with a question mark on the end. Depending on the system as a whole, it could be an adequate solution.
Comment: Sorry @DanTemple I did not notice the `?`
Comment: @ScaryWombat No hassle :) I should have made my point a little clearer.
Answer: You can build a query based on primary keys DELETE FROM ... WHERE id IN (1, 2, 3) or something similar and then use executeUpdate() method which returns the number of affected rows.


Select the Controls in a Panel using LINQ

Question: I have added few controls to a table and added that table to a panel. Now, I want to access those controls(like text boxes, dropdowns etc..) in another method.
I am trying as
List<Control> panelControls = (from pControls in _controlsPanel.Controls.OfType
(). OfType<TableRow>().OfType<TableCell>().OfType<Control>()
                                              .Where(ctrl => (ctrl is TextBox || ctrl is DropDownList))
                                           select pControls).ToList();

which is evudently giving me no controls I added to table and eventually to panel.
Should I add each of the control in my table to Panel or is there a better way to retrieve the controls?
Because, I thought, since all the controls are in a table , it seemed redundant to me to add controls again to panel explicitly. However I might be wrong. please clarify.
Comment: . OfType().OfType().OfType() => those are wrong. You have to .Items or .Controls
Answer: You seem to have mixed query and method syntax which is making my head hurt.  For the purposes of my answer I'll stick to method syntax.
In your LINQ, you are starting with a single list (pControls) and applying several OfType and Where clauses, each of which will filter the list.  Thus you are saying "Give me all controls that are tables and are table rows and are textboxes or dropdownlists."  There is no object that is both a table and a table row at the same time, so right there you're going to get an empty list.
instead, you have to walk the hierarchy a bit. You need to generate a list (e.g. of tables), then use items in that list to get another list (controls that belong to those tables).
If you want to get all the controls on a single panel, you just use
var panelControls = pControls.Controls;

If you want to get all the controls from a single table, first get a reference to the table.  For example, if your table is named MyTable:
var table = pControls.Controls.OfType
().Where( c => c.ID == "MyTable").First();

Then use that reference to get the controls:
var controls = table.Controls;

or if you want it all in one statement:
var controls = pControls.Controls
                        .OfType
()
                        .Where( c => c.ID == "MyTable")
                        .First()
                        .Controls;

You can then filter that list just to get textboxes or dropdownlists:
var list = controls.OfType<Control>().Where( c => c is TextBox || c is DropDownList);

Or, if you really want it all in one statement:
var list = pControls.Controls
                    .OfType
()
                    .Where( c => c.ID == "MyTable")
                    .First()
                    .Controls
                    .OfType<Control>()
                    .Where( c => c is TextBox || c is DropDownList);

Comment: Thanks John for the pointers its very close, but what if my table ID is dynamically generated and I don't know it.
Comment: If there is only one table, just eliminate the where clause.  If there are several tables and you want to combine them, you'll have to use a `ForEach` approach and iterate over each table's controls separately.
Comment: I did that but its just giving some error saying that the last `where` doesn't have a definition. Just as an FYI, I am adding textboxes to TableCell and those TableCells to TableRow and TableRows to Table and eventually Table to Panel. `TextBox/DropDowns-->TableCell-->TableRow-->Table-->Panel`
Comment: *Some error*?  Well then I suggest *some solution*.  ;)  Sorry but you should know better.
Comment: Ohh sorry, the error is `Controls Collection does not contain definition for Where and no extension method Where accepting first argument of type ControlCollection`.
Comment: Oops, looks like I ran into [this problem](https://stackoverflow.com/questions/3302435/why-doesnt-the-controls-collection-provide-all-of-the-ienumerable-methods).  Easy to fix by adding `OfType`. Edited.


install MongoDB on ubuntu 22.04

Question: I am  follow this step but not working for ubuntu 22.04.
echo "* Installing Mongod..."
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list

sudo apt-get update -y
sudo apt-get install -y mongodb-org

Comment: What does this mean? "but not working for ubuntu 22.04"
Answer: I installed it in the following way:
Step 1/2: Installation of libssl1.1
download library
wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb

install it
sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.deb

Step 2/2: Installation of mongodb
Following the official mongodb installion page https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -

The operation should respond with an OK.
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

sudo apt update

sudo apt-get install -y mongodb-org

Mongodb is now installed.
To start mongodb: sudo systemctl start mongod.
To verify that MongoDB has started successfully: sudo systemctl status mongod
Comment: Step 1: Error 404, not found
Comment: Hi @Lee Morgan, the package is no longer available on the old link, you can find it on the page http://http.us.debian.org/debian/pool/main/o/openssl. Download it, then install it and continue with step 2.
If you can't find it, then try this link http://http.us.debian.org/debian/pool/main/o/openssl/libssl1.1_1.1.0l-1~deb9u1_amd64.deb.
Answer: Solution: Depends: libssl1.1 (>= 1.1.1) but it is not installable
Steps to install mongodb in ubuntu 22.04

First of all update  system packages

sudo apt update

Download libssl1.1_1.1.1f-1ubuntu2_amd64.deb

wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb

Install the above using the dpkg command

sudo dpkg -i libssl1.1_1.1.1f-1ubuntu2_amd64.deb

Install required packages

sudo apt install wget curl gnupg2 software-properties-common apt-transport-https ca-certificates lsb-release

Add the MongoDB GPG key to apt

wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

Create a file called mongodb-org-5.0.list. To download and install the sources of the target packages

echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

Update  system packages again

sudo apt update

Install MongoDB on your system

sudo apt install mongodb-org -y

Start the MongoDB service

sudo systemctl start mongod

Check MongoDB status

sudo systemctl status mongod

Enable the MongoDB database. This is for running even after rebooting.

sudo systemctl enable mongod

For accessing mongodb shell

mongo
Answer: echo "deb http://security.ubuntu.com/ubuntu focal-security main" | sudo tee /etc/apt/sources.list.d/focal-security.list

sudo apt-get update

sudo apt-get install libssl1.1

sudo rm /etc/apt/sources.list.d/focal-security.list

sudo apt-get install gnupg curl
curl -fsSL https://pgp.mongodb.com/server-4.4.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-4.4.gpg \
 --dearmor

 echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-4.4.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

 sudo apt-get update

 sudo apt-get install -y mongodb-org=4.4.24 mongodb-org-server=4.4.24 mongodb-org-shell=4.4.24 mongodb-org-mongos=4.4.24 mongodb-org-tools=4.4.24

 sudo service mongod start

 sudo service mongod status

Comment: This solution works but libssl1.1 is an old package and may likely had vulnerabilities. The message from the mongoDB team is for you to wait for them to release the updates for ubuntu 22.04.
Here is the official response: https://www.mongodb.com/community/forums/t/installing-mongodb-over-ubuntu-22-04/159931/6#:~:text=Hi%20folks%2C,validate%20new%20packages.
Comment: E: Package 'libssl1.1' has no installation candidate
Answer: Finally! Below Solutions worked for me
It is because of the missing dependencies mongodb not installing on ubuntu 22.04.
The main reason is the missing of libssl1.1 dependency. So we need to install it seperately.
1.sudo apt install dirmngr gnupg apt-transport-https ca-certificates software-properties-common
2.echo "deb http://security.ubuntu.com/ubuntu impish-security main" | sudo tee /etc/apt/sources.list.d/impish-security.list
3.Go to root user sudo -i  then paste this wget http://archive.ubuntu.com/ubuntu/pool/main/o/openssl/libssl1.1_1.1.1f-1ubuntu2_amd64.deb
4.apt update
5.apt install libssl1.1
6.wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -
7.echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
8.apt update
9.apt install -y mongodb-org
The latest version of mongodb will be installed
To start it
1.systemctl enable mongod
2.systemctl start mongod
In case MongoDB doesn't start run the command below to reload.
systemctl daemon-reload
Comment: E: Package 'libssl1.1' has no installation candidate

install MongoDB on ubuntu 22.04