text:
Q: Is using AsyncTask on every activity a good practise? I would like to know if it is a good practice to use AsyncTask on every activity in my app? I need to improve the speed at which my activities load and AsyncTask should do the trick. Are there risks of doing it this way?

A: If you want to identify what is taking time use Traceview to profile the activity. It is generally a bad idea to try to optimize before identifying the culprit causing lag.
With that said you should enable Strict Mode to catch performance bugs early.
Good Luck!

A: As per developer.google says:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

You can perform your all process without asynctask below API level 10.
But You should use it whenever there is probability that
your process will take long time to execute and it is running on your Main UI.
This type of process can be like you are making connection to the server, Using internet, Downloading some image, Running a url. In all above cases you have to use async task so that these processes will not run on MainUI and didnt block your main .
This link will help you in some way. :)

A: It depends on what you really want. You have to remember that you cannot have everything. If you are trying to improve speed, you will have to loose space. AsyncTasks will occupate more space.
Everytime you will have this relation between memory x proccessing

A: By calling AsyncTask, you just end up creating another thread which is maintained by system. So, depends on what you have to load in activity. If your loading is heavy operation, then you should call asysnctask rather than blocking your UI thread. You app will just end up consuming little more memory during runtime..

A: Short answer: if it improves speed as you said it does. Than it is not bad practise.


text:
Q: How do I do live display of a log file from FTP server? I have a device that logs movement with a sensor and (via PHP) sends the log file to the FTP server every 10 seconds. The device essentially POSTs a message to a PHP script which then modifies the file on the FTP server.
I want to monitor the logging without having to reopen the file again and again.
This shouldn't really be too hard to code, just refresh the content of the file every time there's a request to the server. Is there way to update, say, Notepad++ every time the file changes? My Google searches have not been successful.

A: Use WinSCP with Directory Synchronization option. There is synchronize script which will make it automatic. Check the Automate file transfers (or synchronization) to FTP server or SFTP server guide.
Then Notepad++ should notify about changes made in file automaticly. The option you're probably looking is disabling the confirmation which can be found in Settings -> Preferences -> MISC -> Update silently.
There is also DocMonitor plugin for Notepad++.

Document updater updates your opened documents in Notepad++ every 3 seconds

You can find it in Plugins -> Plugin Manager -> Show Plugin Manager as Document Monitor.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is a holomorphic family whose fibers are all smooth locally trivial? Let $\pi : X \to B$ be a proper, surjective holomorphic submersion, where both $X$ and $B$ are compact Kahler manifolds. Assume that all the fibers $X_b = \pi^{-1}(b)$ are smooth. Is the family $\pi : X \to B$ then locally trivial?
The answer is "no" when formulated like this: Let $\pi : X \to B$ be the family where $X_b$ is the blowup of $B$ at the point $b$. If the automorphism group of $B$ does not act transitively on $B$ then the resuling family cannot be locally trivial but all of its fibers are smooth.
This blowup example (and its trivial variants: blowup more points, things of positive dimension if you can get the smoothness hypothesis to work, ...) is however the only counterexample I've been able to come up with, so I wonder if the statement could be true if we make some positivity hypotheses on $K_X$? For example, suppose in addition that $K_X$ is nef. Is the family then locally trivial?

A: Such a map whose fibers are smooth curves would yield a morphism from the base B to the moduli space of curves whose image is a proper smooth subvariety that misses the boundary parametrizing singular curves.  In the other direction, a smooth complete subvariety of the moduli space which misses the boundary should give an example, by restricting the "universal family of curves on moduli" to that subvariety, provided we can finesse the fact that the universal family has problems over the locus of curves with automorphisms, i.e. essentially the singular locus of moduli, (actually the locus of curves with automorphisms may be larger, as in genus 2).
In genus 2 or more there is a Satake compactification of the moduli space of smooth curves having boundary of codimension at least 2 when g ≥ 3; and in genus 4 or more, the locus of curves with automorphisms also has codimension 2 or more.  Thus at least in genus  4 or more, any general one dimensional linear section B of a projective embedding of the Satake compactification of moduli of curves, will give an example.  Probably this can be made to work also in genus 3.  (but not for g=2, because of Dan's observant comment below.)
Remark: The error in my original answer stemmed from my false claim that the boundary of the Satake compactification of M(g) had codimension at least 2, when g ≥ 2.  This false statement appears in a few places in the literature (e.g. my original answer), but I should have known better.  Indeed the boundary of the Satake compactification of A(g) seems to have codimension g, but the locus of Jacobians is not closed yet in A(g).  The result of Mayer and Mumford was that the closure of the locus of Jacobians in A(g) adds in precisely the products of lower dimensional Jacobians.  Thus when g=2, even before adding in the boundary of A(2), the closure of the 3 dimensional M(2) already includes the 2 dimensional locus of products of elliptic curves.  A nice reference is Mumford's Michigan lectures on curves and their Jacobians.
Dan has explained codimensions of the boundary components in A(g) from the Satake compactification process more generally in his remarks below, and also how to resolve the singularities offered by the locus of curves with automorphisms.  Thanks!

A: By Grauert-Fischer Theorem, a smooth family of compact complex manifold is locally trivial if and only if all the fibers are analytically isomorphic.
However, there exist smooth families $\pi \colon X \to B$ such that the fibres are not isomorphic, and so they are not locally trivial.
The easiest examples occur already for $\dim X =2$ and $\dim B =1$: they are the so-called Kodaira fibrations. In such fibrations, all the fibres are smooth curves but their complex structure varies.
If $\pi \colon X \to  B$ is a Kodaira fibration, then $B$ is a curve of genus at least $2$. Furthermore, $X$ is a minimal surface of general type, hence it is algebraic and $K_X$ is ample.
So, even imposing a positivity condition on $K_X$, the answer to your question is no.
A reference is [Barth-Hulek-Peters-Van de Ven, Compact Complex Surfaces], Chapter V.
For the Grauert-Fischer theorem see the same book, Chapter I.


text:
Q: Add inline onfocus and onblur to an input/div programmatically I have a div that doubles as an input textarea users can type in (using Quill JS).

Text Area

I need the div to have an onfocus and onblur to detect when the user has click in (or is outside of) the input textarea. But the way this is added is programmatically so I can't hardcode into the html itself something like:

Text Area

Instead I need to add the onblur/onfocus after creation.
Please note - I really prefer it to be inline like the above, not as an invisible listener. Is their something like .innerHTML but affecting the actual html of the div? Thoughts?

A: Not sure what exactly you need.
Maybe you can use setAttribute to set the listeners explicitly so it will be visible when you inspect the html:

document.querySelector('.myeditor').setAttribute('onclick', 'onEditorClicked()');

function onEditorClicked() {
  alert('clicked');
}

Text Area


text:
Q: Trouble querying DB for room(s) availability at a certain date Hello guys i have a database table that has
Room (Id(PK), roomType, roomProperties, Price, roomNumber)
Occupany(Id(PK), roomId(FK), reservationId(FK), status)
Reservation(Id(Pk), checkInDate, checkOutDate, NumberOfRoomWanted, guestId(FK))
Guest(Id(Pk), firstName, lastName, email)

No i want to query the database to return if a certain room is available within a certain date by the guest.
The way i structured My DB as for the requirements: A guest and Reservation has a One to One relationship. A reservation can have multiple rooms. Since a reservation can have multiple rooms i made a table occupancy to see if a room is occupied. The relationship between occupancy and room is a one to one relationship. And finally since a reservation can have multiple rooms, the relationship is a one to many i.e. a reservation can have multiple occupancys that is rooms.
Now to query if a room or rooms is availabe for a certain date: My query is
String sql = "SELECT * " +
                "FROM Room " +
                "WHERE type LIKE \"" + roomType + "\" AND properties LIKE \"" + roomProp + "\" AND NOT EXISTS(" +
                "SELECT roomId " +
                "FROM Occupancy" +
                "WHERE checkInDate <= \""+checkinD.toString()+"\" and checkOutDate >= \"" + checkoutD.toString() +
                "\" occupancy.roomId=room.roomId and occupany.resId=Reservation.resId " +

                ")";

As i am trying to query this in java but having trouble please could someone help and tell me what i did wrong. Thanks
Error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'occupancy.roomId=room.roomId and occupany.resId=Reservation.resId )' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
    at com.mysql.jdbc.Util.getInstance(Util.java:360)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2530)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1907)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2030)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2066)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1863)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1839)
    at org.hibernate.loader.Loader.doQuery(Loader.java:910)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
    at org.hibernate.loader.Loader.doList(Loader.java:2554)
    at org.hibernate.loader.Loader.doList(Loader.java:2540)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
    at org.hibernate.loader.Loader.list(Loader.java:2365)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:353)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1909)
    at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:311)
    at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:141)
    at edu.sjsu.cmpe275Project.service.occupancyServiceImpl.getResults(occupancyServiceImpl.java:74)
    at edu.sjsu.cmpe275Project.service.occupancyServiceImpl.searchAvlRoom(occupancyServiceImpl.java:82)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy83.searchAvlRoom(Unknown Source)
    at edu.sjsu.cmpe275Project.controller.HomeController.checkAvaliability(HomeController.java:24)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:775)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:299)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:102)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.springframework.boot.actuate.autoconfigure.MetricsFilter.doFilterInternal(MetricsFilter.java:76)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

The Big question:
The problem is since reservation has the dates how do i query reservation date and occupancy table to retrieve the rooms that are available

A: Your sql is wrong. You forgot AND operand after checkout date comparison.
Furthermore, you need to format the java Date to the format that MySQL understands:
"SELECT * " +
                "FROM Room " +
                "WHERE type LIKE \"" + roomType + "\" AND properties LIKE \"" + roomProp + "\" AND NOT EXISTS(" +
                "SELECT roomId " +
                "FROM Occupancy" +
                "WHERE checkInDate <= \""+new SimpleDateFormat("yyyy-MM-dd").format(checkinD)+
                "\" and checkOutDate >= \"" + new SimpleDateFormat("yyyy-MM-dd").format(checkoutD) +
                "\" and occupancy.roomId=room.roomId and occupany.resId=Reservation.resId " +

                ")";


text:
Q: I get stack overflow when instantiate a class inside WPF MainWindow? When i create an instance of a class and call a method from it, I get stack overflow error! Actually i want to prevent writing whole my code inside the MainWindow, so i need to separate them into different classes.
This is my custom class (class2):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    class Class2
    {
        private string[] names = { "USA", "Canada", "China", "Peru", "Germany" }; // really simple array
        MainWindow mn = new MainWindow(); // Main window instance

        public void lbxm() // this method shows array element inside a listBox
        {
            ListBox lbx = new ListBox() { Width = 200 };
            for (int i = 0; i < names.Length; i++)
            {
                lbx.Items.Add(names[i]);
            }

            mn.grd.Children.Add(lbx); // place the listBox in Main grid layout
        }
    }
}

This is MainWindow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent(); // here's the problem, i get stackoverflow exception...
            Class2 cl2 = new Class2(); // instance of class2
            cl2.lbxm();// call the method
        }

    }
}

A: Reduce your code behind to this:
class Class2
{
    public string[] Names { get; } = { "USA", "Canada", "China", "Peru", "Germany" };
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new Class2();
    }
}

public string[] Names is now a property, to which you bind the ItemsSource property of a ListBox in XAML:
<ListBox ItemsSource="{Binding Names}"/>

A: When you create a new instance of Class2, you're also creating a new instance of MainWindow:
class Class2
{
    private string[] names = { "USA", "Canada", "China", "Peru", "Germany" }; // really simple array
    MainWindow mn = new MainWindow(); // Main window instance <- this is the problem
    ...
}

The problem is when Class2 creates a new MainWindow, the new MainWindow then creates a new Class2:
public MainWindow()
{
    InitializeComponent(); // here's the problem, i get stackoverflow exception...
    Class2 cl2 = new Class2(); // instance of class2
    ...
}

This new Class2 then creates ANOTHER MainWindow, and the cycle repeats until stack overflow. Even if this code did not create a loop that caused a stack overflow, this code would still not work the way you want. The MainWindow you're creating in Class2 is not the main window your application created: it's a brand new MainWindow object.
If you need your Class2 to update objects in MainWindow (which may not be the best way to solve this problem depending on your use case), I would pass the control to the class instead of giving the class a reference to its parent. Something like this would work:
//In Class2
public void PopulateListBox(ListBox grd)
{
    for (int i = 0; i < names.Length; i++)
    {
        grd.Items.Add(names[i]);
    }
}

To call the method:
//In MainWindow
Class2 cl2 = new Class2();
cl2.PopulateListBox(grd); // pass the ListBox where you want the items.

As I mentioned, there are likely better ways to solve this problem than passing a control to a class. This couples your classes to your UI, which in general is not desirable. But this basically does what you wanted your original code to do.


text:
Q: trouble creating an test_app on Ruby on rails? Its showing some error like
Please help me resolving this

A: Your problem is there because, bundle cannot continue before that specific dependency of I guess something you have in your gemfile is not installed. The error message is quite specific, so follow the on-screen instruction by doing gem install byebug and then retry bundle install. Bundle is an asynchronous process, hence, some dependencies needs to be installed before others, otherwise it might cause this type of errors. I hope this solves the issue!


text:
Q: What is "column independent code"? User Notes on FORTRAN Programming, chapter 1-2 (Comparison of FORTRAN and C), says:

Fortran 90 supports useful features of C (column independent code,
  pointers, dynamic memory allocation, etc) and C++ (operator
  overloading, primitive objects).

What does the term "column independent code" mean?

A: In Fortran 77 lines were divided into sections by columns and each part of your code had to go into a specific section. Specifically for non-comment lines , the first 5 columns would either contain that line's label or be blank if the line had no label. Column 6 would contain an arbitrary non-space character if the line was a continuation of a previous line or be left blank otherwise. And columns 7 through 72 would contain the actual statement to be executed on that line. Comment lines would contain a "c" in the first column and the rest of the line would not matter.
In Fortran 90 and C (and most other languages) the columns don't matter. You can write any part of your code at any column you please. That's almost certainly what's meant as "column independent code" in the post you cited.
This concept is more commonly known as free-form code.


text:
Q: Difference between Ondblclick And Dblclick I am reading someone Else's javascript code which is listed below
window.onload = function(){
  // Listen to the double click event.
  if ( window.addEventListener ) {
    document.body.addEventListener( 'dblclick', onDoubleClick, false );
  }
  else if ( window.attachEvent ) {
  /* attachEvent is Microsoft and addEventListener is W3C */
    document.body.attachEvent( 'ondblclick', onDoubleClick );
  }
};

A: The name of the event is "dblclick" and the event (handling) property is called "ondblclick". even in IE the event itself is named "dblclick" (ref.)

A: With or without the "on" it is the same event.
Historically, inline event handling via element attributes used the "on" event names:
<div id="div1" ondblclick="someFunction();">

Assigning the event handler within a script block also used the "on" names:
document.getElementById("div1").ondblclick = someFunction;

Microsoft's attachEvent() method (IE8 and lower) used the "on" event names:
document.getElementById("div1").attachEvent("ondblclick", someFunction);

But then the standards-based .addEventListener (IE9 and the other browsers) used the non "on" event names:
document.getElementById("div1").addEventListener("dblclick",onDoubleClick,false);

The code you've quoted first checks whether addEventListener is defined, which it will be for modern browsers including IE9, and if it isn't it then tries for attachEvent, which will be defined in older versions of IE. (Ironic that it goes to the trouble of using the modern methods for the dblclick event but uses the old style for the .onload.)


text:
Q: How to efficiently replace elements of char string with different integer elements? I am looking to replace the elements of character string with integer elements. I want to replace A with 1, B with 2, C with 3 and D with 4.
How can I do it efficiently?
#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string str = "ABCDDCBA";

    std::replace(str.begin(), str.end(), 'A', '1'); // Replacing
    std::replace(str.begin(), str.end(), 'B', '2');
    std::replace(str.begin(), str.end(), 'C', '3');
    std::replace(str.begin(), str.end(), 'D', '4');
    // ...

    std::cout << str << std::endl; // displaying
    return 0;
}

A: Your method is quite efficient for replacing an arbitrary character with another arbitrary character.
However, currently you replace continuous latin alphabet with continuous integer digits, so you can take advantage of the fact that ASCII representations are also contiguous:
for(char& c : str)
     c += '1' - 'A';

Of course, this depends on the native character encoding to represent contiguous latin alphabet with contiguous values, such as ASCII does. It also depends on the digits being represented contiguously, but that is mandated by the standard.
Furhtermore, this method currently has no check for replaced character, and will change all encountered characters. This is not an issue with your input string, but if you intend to only replace some types of characters and leave others untouched, then you'll need to add a condition check.

A: Presumably you mean do the replacement in one traversal? There are flashy C++ Standard Library ways of doing this, or you could even solve it with std::regex. But exploiting the overloaded [] operator on the std::string class will be hard to beat in terms of performance and is clear.
for (std::size_t i = 0; i < str.size(); ++i){
    switch (str[i]){
    case 'A':
        str[i] = '1';
        break;
    case 'B':
        /*etc*/
    }
}

If you are transforming more than a handful of characters (I took your question literally that you only wanted to map A, B, C, and D), then consider defining a const char[] array that describes the transformation; relying on the values of particular characters is not strictly portable C++.

A: Or you can try if input string only contains caps alphabet in ASCII format
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{

std::string str = "ABCDDCBA";
for(int i=0;i<str.size();i++)
{
    str[i]=str[i]-'A'+'0';
}
std::cout << str << std::endl; // displaying
return 0;
}

A: A funny way to do that would be to use the ASCI value of each char:
by exemple: int('A') = 65, int('B') = 66 so you just have to do a boucle with
val = int(c) - 64;
(Works only if you have maj char)

A: One proposal in O(n)
void MyReplaceFunction(char& c)
{
    static const int delta='A'-'1';
    if(c>='A' && c<='Z')
    {
        c-=delta;
    }
}

std::for_each(str.begin(), str.end(), MyReplaceFunction);


text:
Q: What am I supposed to do in processContentChanges:? This is my app's processContentChanges: method, which is triggered by NSPersistentStoreDidImportUbiquitousContentChangesNotification:
- (void)processContentChanges:(NSNotification *)notification {
    [self.managedObjectContext performBlock:^{
        // Merge incoming data updates in the managed object context
        [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];

        // Post notification to trigger UI updates
#warning What do I actually do here?
    }];
}

I'm using NSFetchedResultsControllers throughout my app so that the UI updates automatically when changes are received from another device through iCloud. This all seems to work, but the comment saying // Post notification to trigger UI updates was there in the template method already. Am I actually supposed to do something here, or can I safely leave things the way they are?

A: Well, although I haven't had confirmation of this I don't think there is anything else that needs to be done in this method as long as the following criteria are met:

*

*You implement NSPersistentStoreDidImportUbiquitousContentChangesNotification correctly as per the template so that new content is merged to the managed object context

*Your content is generated using NSFetchedResultsController objects

*Your viewControllers conforms to the the NSFetchedResultsControllerDelegate protocol, and implements controllerWillChangeContent:, controllerDidChangeContent: and controller:didChangeObject:atIndexPath:forChangeType:newIndexPath

*In those methods, update your views accordingly to display new content, remove deleted content, and update changed content.

If you have any objects which utilise CoreData without an NSFetchedResultsController then you might need to update these by manually re-fetching the data when NSPersistentStoreDidImportUbiquitousContentChangesNotification is posted by CoreData.


text:
Q: Windows XP GTK App Glib Import Error I am trying to run my GTK app on Windows XP and I am having troubles with an import. I have installed the following as needed and recommended:
python-2.6.msi
gtk2-runtime.2-16.6.exe
pycairo-1.8.6.exe
pygobject-2.20.0
pygtk-2.16.0.exe
pyserial-2.5.exe

However, I am getting the following error when running my script:
Traceback (most recent call last):
  File "C:\python26\app\src\start.py", line 22, in <module>
    import gtk
  File "C:\Python26\Lib\site-packages\gtk-2.0\gtk\__init__.py", line 30, in <mod
ule>
    import gobject as _gobject
  File "C:\Python26\Lib\site-packages\gtk-2.0\gobject\__init__.py", line 26, in
<module>
    from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \
  File "C:\Python26\Lib\site-packages\gtk-2.0\glib\__init__.py", line 22, in <mo
dule>
    from glib._glib import *
ImportError: DLL load failed: The specified module could not be found.

GTK is installed into C:\gtk\bin and is setup in my System PATH.
Am I missing something obvious here?
Any help would be appreciated.
Thank-you kindly.
Andy

A: I was getting the same issue - I'm not sure why, but I suspect it has something to do with some of the install/lookup paths. I tried adding all sorts of stuff to my path, but nothing seemed to work.
What I did to fix it was to uninstall python et. al. and reinstall using the Python (x,y) package. It's a fairly large download, but it has tons of tools, including several (matplotlib, numpy, scipy, IPython, etc) that I needed/wanted.

A: You could install pygtk bundle found in this page:
http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.22/
where you should find the "all in one" installer suited to your version.
It solved the problem to me without having to install Py(x,y), which seems to be a very usefull scientific environment for windows (I use linux and install all these packages from script).


text:
Q: How to write BigTable table data into a pandas dataframe? I am trying to read a GCP BigTable - table to a pandas dataframe, and currently, the function I am using to fetch rows from BigTable is read_rows(), which returns PartialRowData.
Code:
from google.cloud import bigtable

client = bigtable.Client(admin=True)
instance = client.instance(bigTable_parms['instance_id'])
table = instance.table('s2')

row_data = table.read_rows()  # table.yield_rows()
for i in row_data:
    print(type(i))

Output:

<class 'google.cloud.bigtable.row_data.PartialRowData'>

Query:
How do we read the values from PartialRowData obj?

A: There's an example on how to call read_rows in this documentation:
https://googleapis.dev/python/bigtable/latest/table.html#google.cloud.bigtable.table.Table.read_rows
for row in table.read_rows():
    # replace with your own COLUMN_FAMILY_ID and COLUMN_NAME
    cell = row.cells[COLUMN_FAMILY_ID][COLUMN_NAME][0]
    print(cell.value.decode("utf-8"))


text:
Q: Using snprintf to print an array? Alternatives? Is it at all possible to use snprintf to print an array?  I know that it can take multiple arguments, and it expects at least as many as your formatting string suggests, but if I just give it 1 formatting string and an array of values, will it print the entire array to the buffer?
The reason I ask, is because I am modifying source code, and the current implementation only supported one value being placed in a string, but I am modifying it to support an array of values.  I want to change the original implementation as little as possible.
If this doesn't work, is there another way someone would recommend to do this?  Should I just suck it up and use a for loop (how well would that really work without stringbuffers)?
Essentially: What would be the best way to get all of the values from an array of doubles into the same string for a return?

A: No, there's no formatting specifier for that.
Sure, use a loop. You can use snprintf() to print each double after the one before it, so you never need to copy the strings around:
double a[] = { 1, 2, 3 };
char outbuf[128], *put = outbuf;

for(int = 0; i < sizeof a / sizeof *a; ++i)
{
  put += snprintf(put, sizeof outbuf - (put - outbuf), "%f ", a[i]);
}

The above is untested, but you get the general idea. It separates each number with a single space, and also emits a trailing space which might be annoying.
It does not do a lot to protect itself against buffer overflow, generally for code like this you can know the range of the inputs and make sure the outbuf is big enough. For production code you would need to think about this of course, the point here is to show how to solve the core problem.

A: I decided to go with this:
int ptr = 0;
for( i = 0; i < size; i++)
{
    ptr += snprintf(outbuf + ptr, sizeof(outbuf) - ptr, "%.15f ", values[i]);
}

slightly different, but to the same effect as in @unwind 's solution.  I got this idea from the reference page for snprintf()


text:
Q: Convert RGBA PNG to RGB with PIL I'm using PIL to convert a transparent PNG image uploaded with Django to a JPG file. The output looks broken.
Source file

Code
Image.open(object.logo.path).save('/tmp/output.jpg', 'JPEG')

or
Image.open(object.logo.path).convert('RGB').save('/tmp/output.png')

Result
Both ways, the resulting image looks like this:

Is there a way to fix this? I'd like to have white background where the transparent background used to be.

Solution
Thanks to the great answers, I've come up with the following function collection:
import Image
import numpy as np

def alpha_to_color(image, color=(255, 255, 255)):
    """Set all fully transparent pixels of an RGBA image to the specified color.
    This is a very simple solution that might leave over some ugly edges, due
    to semi-transparent areas. You should use alpha_composite_with color instead.

    Source: http://stackoverflow.com/a/9166671/284318

    Keyword Arguments:
    image -- PIL RGBA Image object
    color -- Tuple r, g, b (default 255, 255, 255)

    """
    x = np.array(image)
    r, g, b, a = np.rollaxis(x, axis=-1)
    r[a == 0] = color[0]
    g[a == 0] = color[1]
    b[a == 0] = color[2]
    x = np.dstack([r, g, b, a])
    return Image.fromarray(x, 'RGBA')

def alpha_composite(front, back):
    """Alpha composite two RGBA images.

    Source: http://stackoverflow.com/a/9166671/284318

    Keyword Arguments:
    front -- PIL RGBA Image object
    back -- PIL RGBA Image object

    """
    front = np.asarray(front)
    back = np.asarray(back)
    result = np.empty(front.shape, dtype='float')
    alpha = np.index_exp[:, :, 3:]
    rgb = np.index_exp[:, :, :3]
    falpha = front[alpha] / 255.0
    balpha = back[alpha] / 255.0
    result[alpha] = falpha + balpha * (1 - falpha)
    old_setting = np.seterr(invalid='ignore')
    result[rgb] = (front[rgb] * falpha + back[rgb] * balpha * (1 - falpha)) / result[alpha]
    np.seterr(**old_setting)
    result[alpha] *= 255
    np.clip(result, 0, 255)
    # astype('uint8') maps np.nan and np.inf to 0
    result = result.astype('uint8')
    result = Image.fromarray(result, 'RGBA')
    return result

def alpha_composite_with_color(image, color=(255, 255, 255)):
    """Alpha composite an RGBA image with a single color image of the
    specified color and the same size as the original image.

    Keyword Arguments:
    image -- PIL RGBA Image object
    color -- Tuple r, g, b (default 255, 255, 255)

    """
    back = Image.new('RGBA', size=image.size, color=color + (255,))
    return alpha_composite(image, back)

def pure_pil_alpha_to_color_v1(image, color=(255, 255, 255)):
    """Alpha composite an RGBA Image with a specified color.

    NOTE: This version is much slower than the
    alpha_composite_with_color solution. Use it only if
    numpy is not available.

    Source: http://stackoverflow.com/a/9168169/284318

    Keyword Arguments:
    image -- PIL RGBA Image object
    color -- Tuple r, g, b (default 255, 255, 255)

    """
    def blend_value(back, front, a):
        return (front * a + back * (255 - a)) / 255

    def blend_rgba(back, front):
        result = [blend_value(back[i], front[i], front[3]) for i in (0, 1, 2)]
        return tuple(result + [255])

    im = image.copy()  # don't edit the reference directly
    p = im.load()  # load pixel array
    for y in range(im.size[1]):
        for x in range(im.size[0]):
            p[x, y] = blend_rgba(color + (255,), p[x, y])

    return im

def pure_pil_alpha_to_color_v2(image, color=(255, 255, 255)):
    """Alpha composite an RGBA Image with a specified color.

    Simpler, faster version than the solutions above.

    Source: http://stackoverflow.com/a/9459208/284318

    Keyword Arguments:
    image -- PIL RGBA Image object
    color -- Tuple r, g, b (default 255, 255, 255)

    """
    image.load()  # needed for split()
    background = Image.new('RGB', image.size, color)
    background.paste(image, mask=image.split()[3])  # 3 is the alpha channel
    return background

Performance
The simple non-compositing alpha_to_color function is the fastest solution, but leaves behind ugly borders because it does not handle semi transparent areas.
Both the pure PIL and the numpy compositing solutions give great results, but alpha_composite_with_color is much faster (8.93 msec) than pure_pil_alpha_to_color (79.6 msec). If numpy is available on your system, that's the way to go. (Update: The new pure PIL version is the fastest of all mentioned solutions.)
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_to_color(i)"
10 loops, best of 3: 4.67 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.alpha_composite_with_color(i)"
10 loops, best of 3: 8.93 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color(i)"
10 loops, best of 3: 79.6 msec per loop
$ python -m timeit "import Image; from apps.front import utils; i = Image.open(u'logo.png'); i2 = utils.pure_pil_alpha_to_color_v2(i)"
10 loops, best of 3: 1.1 msec per loop

A: By using Image.alpha_composite, the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a tuple index out of range error if png has no alpha channel.
from PIL import Image

png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255, 255, 255))

alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)

A: Here's a solution in pure PIL.
def blend_value(under, over, a):
    return (over*a + under*(255-a)) / 255

def blend_rgba(under, over):
    return tuple([blend_value(under[i], over[i], over[3]) for i in (0,1,2)] + [255])

white = (255, 255, 255, 255)

im = Image.open(object.logo.path)
p = im.load()
for y in range(im.size[1]):
    for x in range(im.size[0]):
        p[x,y] = blend_rgba(white, p[x,y])
im.save('/tmp/output.png')

A: Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG support for sorl thumbnails.
from PIL import Image

png = Image.open(object.logo.path)
png.load() # required for png.split()

background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

background.save('foo.jpg', 'JPEG', quality=80)

Result @80%

Result @ 50%

A: The transparent parts mostly have RGBA value (0,0,0,0). Since the JPG has no transparency, the jpeg value is set to (0,0,0), which is black.
Around the circular icon, there are pixels with nonzero RGB values where A = 0. So they look transparent in the PNG, but funny-colored in the JPG.
You can set all pixels where A == 0 to have R = G = B = 255 using numpy like this:
import Image
import numpy as np

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
x = np.array(img)
r, g, b, a = np.rollaxis(x, axis = -1)
r[a == 0] = 255
g[a == 0] = 255
b[a == 0] = 255
x = np.dstack([r, g, b, a])
img = Image.fromarray(x, 'RGBA')
img.save('/tmp/out.jpg')

Note that the logo also has some semi-transparent pixels used to smooth the edges around the words and icon. Saving to jpeg ignores the semi-transparency, making the resultant jpeg look quite jagged.
A better quality result could be made using imagemagick's convert command:
convert logo.png -background white -flatten /tmp/out.jpg

To make a nicer quality blend using numpy, you could use alpha compositing:
import Image
import numpy as np

def alpha_composite(src, dst):
    '''
    Return the alpha composite of src and dst.

    Parameters:
    src -- PIL RGBA Image object
    dst -- PIL RGBA Image object

    The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
    '''
    # http://stackoverflow.com/a/3375291/190597
    # http://stackoverflow.com/a/9166671/190597
    src = np.asarray(src)
    dst = np.asarray(dst)
    out = np.empty(src.shape, dtype = 'float')
    alpha = np.index_exp[:, :, 3:]
    rgb = np.index_exp[:, :, :3]
    src_a = src[alpha]/255.0
    dst_a = dst[alpha]/255.0
    out[alpha] = src_a+dst_a*(1-src_a)
    old_setting = np.seterr(invalid = 'ignore')
    out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
    np.seterr(**old_setting)
    out[alpha] *= 255
    np.clip(out,0,255)
    # astype('uint8') maps np.nan (and np.inf) to 0
    out = out.astype('uint8')
    out = Image.fromarray(out, 'RGBA')
    return out

FNAME = 'logo.png'
img = Image.open(FNAME).convert('RGBA')
white = Image.new('RGBA', size = img.size, color = (255, 255, 255, 255))
img = alpha_composite(img, white)
img.save('/tmp/out.jpg')

A: It's not broken. It's doing exactly what you told it to; those pixels are black with full transparency. You will need to iterate across all pixels and convert ones with full transparency to white.

A: import numpy as np
import PIL

def convert_image(image_file):
    image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
    original_width, original_height = image.size

    np_image = np.array(image)
    new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
    # create 3D array

    for each_channel in range(3):
        new_image[:,:,each_channel] = np_image[:,:,each_channel]
        # only copy first 3 channels.

    # flushing
    np_image = []
    return new_image

A: from PIL import Image

def fig2img ( fig ):
    """
    @brief Convert a Matplotlib figure to a PIL Image in RGBA format and return it
    @param fig a matplotlib figure
    @return a Python Imaging Library ( PIL ) image
    """
    # put the figure pixmap into a numpy array
    buf = fig2data ( fig )
    w, h, d = buf.shape
    return Image.frombytes( "RGBA", ( w ,h ), buf.tostring( ) )

def fig2data ( fig ):
    """
    @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
    @param fig a matplotlib figure
    @return a numpy 3D array of RGBA values
    """
    # draw the renderer
    fig.canvas.draw ( )

    # Get the RGBA buffer from the figure
    w,h = fig.canvas.get_width_height()
    buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )
    buf.shape = ( w, h, 4 )

    # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode
    buf = np.roll ( buf, 3, axis = 2 )
    return buf

def rgba2rgb(img, c=(0, 0, 0), path='foo.jpg', is_already_saved=False, if_load=True):
    if not is_already_saved:
        background = Image.new("RGB", img.size, c)
        background.paste(img, mask=img.split()[3]) # 3 is the alpha channel

        background.save(path, 'JPEG', quality=100)
        is_already_saved = True
    if if_load:
        if is_already_saved:
            im = Image.open(path)
            return np.array(im)
        else:
            raise ValueError('No image to load.')


text:
Q: Conjecture concerning the function $f(x)=\gcd\left(\left\lfloor\int_{0}^{n}\frac{t^{2}}{t+1}dt\right\rfloor,\lfloor x\rfloor\right)$ It's follow up of a previous question :
Let define :
$$f(x)=\gcd\left(\left\lfloor\int_{0}^{n}\frac{t^{2}}{t+1}dt\right\rfloor,\lfloor x\rfloor\right)$$
Leading by some graphical argument it appears that :
$\exists n$ such that :
$$f(x)=p_k^C$$ or $$f(x)=1$$
Where $1\leq C\leq 2$ an integer and $p_k$ is the $k$th prime number .
Reformulating the problem we have :
$$f(x)=\gcd\left(\left\lfloor\frac{n^{2}}{2}-n+\ln\left(n+1\right)\right\rfloor,\lfloor x\rfloor\right)$$
Is the number of $n$ as above unbounded ?


text:
Q: Outlook share same manager I know that I've seen somewhere in Outlook that I've been able to view a list of other people that share the same manager as a given person.  It's useful for locating a peer of someone who's on vacation, etc.
I'm not able to find it currently.  I did a internet search and both Bing and Google seemed to think I was asking how to share my calendar.  Does anyone know how to do this?
Thanks,

A: *

*In an e-mail, right click on the user's name and select Open Contact Card

*Select Organization

*An Org Tree should be displayed all the way up to the top

A: Under calendar view, there are calendar groups in the left pane. There are typically arranged as

*

*My Calendar

*Shared Calendars

*Other Calendars

If your company already has them setup, you may see some additional calendars available. In my case, our company has one called Team: {supervisor name}. Under those we can see all our work associates.
You can also create these calendar groups. There is more information about it in the above link.


text:
Q: How can I customize the TabBar indicator width and height? I'm using a TabBar widget and I'd like to customize the height and width of the indicator. I can't see any other property besides color I can modify.

A: In the same way as this answer https://stackoverflow.com/a/44273493/5938089, The best is to use containers, but I will only use one.
For a change, I will use a bottom bar
bottomNavigationBar: new Material(
    color: Colors.teal,
    child: new Container(
      height: 60.0,
      child: new TabBar(
        controller: controller,
        tabs: <Widget>[
            new Tab(icon: new Icon(Icons.access_alarm)),
            new Tab(icon: new Icon(Icons.account_balance)),
        ]
      ),
    )
  ),

Screen Shot

A: You can use indicatorSize: TabBarIndicatorSize.label on the TabBar to make the indicator the same size as the label.
Or you could set the indicator directly, this is a Decoration which you can customize:
AppBar(
    bottom: TabBar(
        indicator: UnderlineTabIndicator(
          borderSide: BorderSide(width: 5.0),
          insets: EdgeInsets.symmetric(horizontal:16.0)
        ),
        tabs: [
          Tab(text: 'tab 1'),
          Tab(text: 'tab 2'),
          Tab(text: 'tab 3'),
        ],
     ),
);

For more customisation options check this post

A: Give your TabBar a property of isScrollable: true if you don't want the tabs to expand to fill the screen horizontally the way they do by default.
You can use a Container wrapped in a PreferredSize to size the TabBar. (The PreferredSize is only necessary if you want it to live in the bottom slot of an AppBar.) This has the effect of making the indicators appear narrower because the TabBar doesn't fill the screen. However, the indicator has a hard coded height. If you don't like it, you'll have to import your own copy of tabs.dart and customize the constants in that file.
Note that you can also use a Container to set the height of the individual Tabs, although that doesn't seem like what you're trying to do.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
      length: 2,
      child: new Scaffold(
        appBar: new AppBar(
          title: new Text('Tabs Demo'),
          bottom: new PreferredSize(
            preferredSize: new Size(200.0, 200.0),
            child: new Container(
              width: 200.0,
              child: new TabBar(
                tabs: [
                  new Container(
                    height: 200.0,
                    child: new Tab(text: 'hello'),
                  ),
                  new Container(
                    height: 200.0,
                    child: new Tab(text: 'world'),
                  ),
                ],
              ),
            ),
          ),
        ),
        // body: ...
      ),
    );
  }

}

A: You can adjust the spacing between the tabs -> labelPadding: EdgeInsets.symmetric (horizontal: 5),

A: You can use property TabBar(indicatorWeight:detail Height).

A: Check out Tab Indicator Styler package for more advanced styling.

A: appBar: new AppBar(
        title: Text("TabBar demo"),
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(kToolbarHeight),
          child: Align(
            alignment: Alignment.centerLeft,
            child: new TabBar(
              controller: _tabController,
              indicator: UnderlineTabIndicator(
                borderSide: BorderSide(width: 3.0, color: Colors.red),
                insets: EdgeInsets.symmetric(horizontal: 20.0, vertical: 10),
              ),
              indicatorSize: TabBarIndicatorSize.label,
              isScrollable: true,
              onTap: (index) {
                print(index);
                _currentIndex = index;
                setState(() {});
              },
              tabs: [
                new Container(
                  height: 50.0,
                  width: 80,
                  // color: Colors.red,
                  child: new Tab(text: '1'),
                ),
                new Container(
                  height: 50.0,
                  width: 80,
                  // color: Colors.red,
                  child: new Tab(text: '222'),
                ),
                new Container(
                  height: 50.0,
                  width: 80,
                  // color: Colors.red,
                  child: new Tab(text: '333333'),
                ),
              ],
            ),
          ),
        ),
      ),
      // body: ...
    );

A: Try to do this in the TabBar
                  indicatorWeight: 0,
                  indicator: UnderlineTabIndicator(
                    borderSide: BorderSide(
                      width: 0.1,
                      color: AppColor.themeColor,
                    ),

A: You can design the underline indicator with border-radius, and the length of the indicator according to the text container length.
child: TabBar(
    indicatoenter code herer: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        color: widgetBlueColor,
    ),
    indicatorPadding: const EdgeInsets.only(top: 33, bottom: 2),
    labelColor: widgetBlueColor,
    unselectedLabelColor: Colors.black87,
    labelPadding: const EdgeInsets.only(bottom: 16),
    indicatorSize: TabBarIndicatorSize.label,
    labelStyle: const TextStyle(fontWeight: FontWeight.w500),
    tabs: const [
        Tab(
            child: SizedBox(
                width: 60,
                child: Text(
                    "DETAILS",
                    textAlign: TextAlign.center,
                ),
            ),
        ),
        Tab(
            child: SizedBox(
                width: 85,
                child: Text(
                    "DOCUMENTS",
                    textAlign: TextAlign.center,
                ),
            )
        )
    ]
)

A: if you decrease default tab bar size use SizeBox().
                             SizedBox(
                                  height: 40,
                                  child: TabBar(
                                      isScrollable: true,
                                      indicatorSize: TabBarIndicatorSize.tab,
                                      labelColor: Colors.black,
                                      unselectedLabelColor: Colors.grey,
                                      labelStyle: TextStyle(
                                          fontSize: 15,
                                          fontWeight: FontWeight.w500),
                                      unselectedLabelStyle: TextStyle(
                                          fontSize: 14,
                                          fontWeight: FontWeight.w400),

                                      padding:
                                          EdgeInsets.symmetric(horizontal: 12),
                                      indicator: BoxDecoration(
                                          borderRadius: BorderRadius.circular(16),
                                          color: AppTheme().orange),
                                      tabs: getTab(),
                                      controller: _tabController),
                                ),


text:
Q: View optimization As you see below I have a select from a view and my problem is that it takes too long to execute the whole view - around 4min.
The problem is at the FULL OUTER JOIN because it takes about 55% of time!
I can't find/see a viable solution. If you have any idea, it will be much appreciated!
SELECT CAST('1' + CAST(c.ContractNumber AS VARCHAR) + RIGHT('0000'+CAST(ISNULL(p.billTRANNO, p.TRANNO) AS VARCHAR),5) AS BIGINT) AS PaymentID,
    CAST('1' + CAST(c.ContractNumber AS VARCHAR) AS BIGINT) AS ContractID,
    CAST(ISNULL(p.billTRDT,p.corrPTRNEFF ) AS DATE) AS PaymentBillingDate,
    CAST(l.INSTTO AS DATE) AS PaymentDueDate,
    CAST ((CASE WHEN p.BATCTRCDE IN ('B216', 'T642', 'T679', 'B9H2', 'T693', 'T680') THEN p.TRANSACTION_DATE END) AS DATE) AS PaymentDate,
    CAST((CASE WHEN p.BATCTRCDE = 'B216' AND c.StatCode+c.PStatCode IN ('IFWP','IFDW') THEN l.INSTAMT01
              WHEN p.BATCTRCDE IN ('T642', 'T679', 'B9H2', 'T693', 'T680') THEN rtrn.ORIGAMT END) AS DECIMAL (15,2)) AS PaymentAmount,
    c.Currency,
    CAST((CASE WHEN p.BATCTRCDE IN ('T679', 'B9H2', 'T693', 'T680', 'T642') THEN 'P'
                WHEN l.PAYFLAG IS NOT NULL THEN l.PAYFLAG WHEN billTRANNO IS NOT NULL THEN 'O' ELSE 'P' END) AS CHAR(2)) AS PaymentStateCode,
    CAST((CASE WHEN p.BATCTRCDE IN ('T679', 'B9H2', 'T693', 'T680') THEN 'TU'
                WHEN p.BATCTRCDE = 'T642' AND c.ProductCode IN ('1S0', 'XS0', 'INV', 'IND', '1S1', 'XS1', 'PS1', 'PS2', 'SE0', '1S2') THEN 'SP'
                WHEN p.BATCTRCDE = 'T642' AND c.ProductCode NOT IN ('1S0', 'XS0', 'INV', 'IND', '1S1', 'XS1', 'PS1', 'PS2', 'SE0', '1S2') THEN 'IS'
                WHEN p.BATCTRCDE = 'B216' OR p.billTRANNO IS NOT NULL THEN 'RP' END) AS CHAR(2)) AS PaymentTypeCode,
    1 as BusinessLineCode
FROM tmpContract_BaseData c
    INNER JOIN (SELECT ISNULL(p.ContractNumber, bill.ContractNumber) ContractNumber, p.TRANNO, p.PTRNEFF, p.BATCTRCDE, p.TRANSACTION_DATE,
                        bill.TRANNO billTRANNO, bill.PTRNEFF billPTRNEFF, bill.TRANSACTION_DATE billTRDT, corr.PTRNEFF corrPTRNEFF
                FROM (SELECT ContractNumber, TRANNO, PTRNEFF, BATCTRCDE, TRANSACTION_DATE
                        FROM dbo.PTRN
                        WHERE BATCTRCDE IN ('T679', 'T642', 'B216', 'B9H2','T693','T680') and VALIDFLAG='1') p
                    FULL OUTER JOIN (SELECT ContractNumber, PTRNEFF, TRANSACTION_DATE, BATCTRCDE, TRANNO
                                    FROM dbo.PTRN
                                    WHERE BATCTRCDE in ('B503') AND VALIDFLAG='1') bill
                        ON bill.ContractNumber=p.ContractNumber AND bill.PTRNEFF=p.PTRNEFF AND p.BATCTRCDE = 'B216' AND bill.TRANNO<p.TRANNO
    LEFT JOIN (SELECT ContractNumber, PTRNEFF, TRANSACTION_DATE, BATCTRCDE, TRANNO
                    ,RANK() over (partition by ContractNumber, PTRNEFF, TRANSACTION_DATE, BATCTRCDE order by TRANNO) as NrCrt
                FROM dbo.PTRN
                WHERE BATCTRCDE in ('Z791') AND VALIDFLAG='1') corr
                    ON corr.ContractNumber=p.ContractNumber AND corr.PTRNEFF=p.PTRNEFF AND p.BATCTRCDE = 'B216' AND corr.TRANNO>p.TRANNO and NrCrt = 1
                ) p on p.ContractNumber = c.ContractNumber
    LEFT JOIN dbo.LINS l ON l.ContractNumber=c.ContractNumber AND dbo.ParseDateNullInvalid(l.INSTFROM,10)=ISNULL(p.billPTRNEFF, p.corrPTRNEFF)
    LEFT JOIN (SELECT ContractNumber, TRANNO, SUM(ORIGAMT) AS ORIGAMT FROM dbo.RTRN WHERE SACSCODE='LP' AND SACSTYP='S'
GROUP BY ContractNumber, TRANNO) rtrn ON rtrn.ContractNumber=p.ContractNumber AND rtrn.TRANNO=p.TRANNO
WHERE c.BusinessLineCode='1'


text:
Q: Delta Epsilon Question Help? I know that the delta epsilon can produce different correct answers depending on how you approach the question i have:
$\epsilon > 0$ be given
Show $|\sqrt{x^{2}+1}|$ is continuous at x=1.
So i Have:
$$ |\sqrt{x^{2}+1}-\sqrt{2}| \rightarrow \bigg|\sqrt{x^{2}+1}-\sqrt{2}*\frac{\sqrt{x^{2}+1}+\sqrt{2}}{\sqrt{x^{2}+1}+\sqrt{2}}\bigg| \rightarrow |x-1|\bigg|\frac{x+1}{\sqrt{x^{2}+1}+\sqrt{2}}\bigg|$$
Also as $|x-1|<\delta$ and so $x \in (0,2)$
Subbing in my values i get the min as $\frac{1}{1+\sqrt{2} \epsilon}$.
So therefore my value answer is $0 < \delta < min\bigg[1,\frac{1}{1+\sqrt{2} \epsilon }\bigg]$ would this be right as my minimum for delta as my lecturer in his notes times by 2 and has $2|x-1| < 2\delta < \epsilon$ so gets a min$\bigg[1,\frac{2}{\epsilon} \bigg]$.
So is my answer correct or do i need to work further to get to the answer in my lecture notes?
Any help would be appreciated thanks.

A: This is so fuzzy (and looks wrong), it is what you do in a draft. Here is how it is usually done (and the spirit behind it):
Let us consider $\epsilon > 0$.
Let us note $\delta = \min(\frac{1}{3}, \frac{\epsilon}{18\pi})$ (I decide to call this number $\delta$, because I like it, and I think it deserves a proper name)
Let us consider $x \in [1-\delta, 1+\delta]$ (I take any number in that set, I want to play a little with it)
Let us calculate $|\sqrt{x^2+1}-\sqrt{2}|$ (It's rainy outside and I don't have anything better to do, so let's do that. It is better than playing video games anyway)
$|\sqrt{x^2+1}-\sqrt{2}|\leq |\sqrt{x^2+1}-\sqrt{2}||\sqrt{x^2+1}+\sqrt{2}|$ (as $|\sqrt{x^2+1}+\sqrt{2}| \geq 1$ )
$ = x^2+1-2 \leq (1+\delta)^2-1 = 2\delta + \delta^2 \leq \frac{\epsilon}{18\pi}(2 + \delta) $ (since $\delta \leq \frac{\epsilon}{18\pi}$)
$\leq \frac{\epsilon}{6\pi} < \epsilon$ (since $\delta \leq 1$)
So $x \rightarrow \sqrt{x^2+1}$ is continuous in $1$ (Holy Saint Homer on a rainbow! This stuff I was calculating is smaller than $\epsilon $ all along! This means that my function is continuous! I really didn't expect that... )
Rq : You can take any $\delta$ up to $\min(1,\frac{\epsilon}{3})$ and do the same calculus.


text:
Q: Modifing a list created in constructor | Java I'm doing an exercise from a course. The exercise tells me:
-create a 'Calculator' class
-Each new object of this class should have String list, where will be an operation's history stored (list created in the constructor). The constructor cannot have any parameters.
And of course basic operations in calculator.
So I've started to create this, and that's what I've got now:
class Calculator {

    public Calculator () {
        List<String> history = new LinkedList<String>();
    }

    public double add(double num1, double num2) {
        history.add("added " + num1 + " to " + num2);     //here's the problem
        return num1 + num2;
    }
}

But when I try to add the new string to the history list, I can't do that, because it doesn't exist in that place of the program.
Wouldn't it be better to create a List not in the constructor, but directly in the class?
Even if it would, I should do this exercise the way they tell me to do, so could you help me and show how to add something to the List which is created in the constructor?

A: The error is due to the fact that add() is trying to fetch history which happens to be a local variable inside constructor and as local vars have no scope outside its method, add() will not be able to reach that.
So in order to fix this, modify like the field history at class level so that all of it's method can reach out to it. It can be initialized inside the constructor and can very well be used inside the class. Based on the visibility it can be public | private | protected. Your code might look like,
class Calculator {

    private List<String> history;

    public Calculator () {
        history = new LinkedList<String>();
    }

    public double add(double num1, double num2) {
        history.add("added " + num1 + " to " + num2);
        return num1 + num2;
    }
}

A: Using oop concepts like inheritance the code could be rewrite like:
import java.util.LinkedList;
public class Calculator extends LinkedList<String>
{

    public static void main(String[] args)
    {
        Calculator c = new Calculator();
        System.out.println(c.add(1,2));
        System.out.println(c.getFirst());
    }

     public Calculator () {

     }

     public double add(double num1, double num2) {
            this.add("added " + num1 + " to " + num2);     //here's the problem
            return num1 + num2;
     }
}

Output:
3.0
added 1.0 to 2.0


text:
Q: How to pass navigation prop to child component in react navigation v5 How to pass navigation prop to child component in react native, I am using react navigation v5, as I want to use navigation.navigate('settings') in the child component.

A: You can use useNavigation in your child component.
Example (adapted from the docs):
import React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';

function MyBackButton() {
  const navigation = useNavigation();

  return (
    <Button
      title="Go to Settings"
      onPress={() => {
        navigation.navigate('settings');
      }}
    />
  );
}


text:
Q: Can other Chrome extensions read the log messages written by my extension? I've written an extension for Google Chrome which writes something to the console of its background page via console.log. Can any other extension access the data I've written there, or is it safe from them?
I'm guessing the answer is "no other extension can access this, only your extension (and the user)"; but I was not able to find an authoritative source.

A: With default flags, the browser will deny (silent) access to chrome-extension:// pages to other extensions/apps with public API.
There are flags that can override this (e.g. silent-debugger-extension-api flag with chrome.debugger API), but it will require actions from the user (or a local attack that can change the Chrome launcher parameters).
Also, there are private APIs that allow things like Chrome Apps & Extensions Developer Tool to function, but as a private API only apps whitelisted by Google have access.
Lastly, extensions that extend DevTools can potentially divert the console output as long as DevTools is open by replacing the console object with a malicious copy. It's very unlikely, and I have not tested that, but it's theoretically possible.


text:
Q: Express server doesn't start When I run my node server, nothing happens and it doesn't show any errors:

Node Server
const express = require('express')
const app = express()
const path = require('path')
// const router = require('./router')

app.use(express.static(path.join(__dirname, '../../dist/')))

// app.use('/api', router)

app.get('*', (request, response) => {
  response.sendFile(path.join(__dirname, '../../dist/index.html'))
})

This is my folder hierarchy:

A: You have initialised the express server but you need to bind the connection to a port and then listen for requests.
Add the following to the entry point of your Node server:
var PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on PORT ${PORT}`));


text:
Q: Get index of a specific item from list containing possible duplicates okay, I have a list of class objects like so:
    List<fruit> lst = new List<fruit>();
    lst.Add(orange);
    lst.Add(apple);
    lst.Add(grape);
    lst.Add(grape);
    lst.Add(orange);
    lst.Add(pear);
    lst.Add(apple);
I want to be able to ask the list something like
GetIndex("orange", 2) and have it return (in this case) the index # for the second instance of object in question (position 4).
This list will be dynamically filled, and it may not even have an orange to begin with.  If it does, I want the instance number of the second parameter.  So I can get the second orange, or get fifth mango, etc.
list.IndexOf(orange) returns the first instance of any duplicates, so I need something else.
Any ideas?
PS: I failed to mention that the first param will be a string!

A: public static int GetIndex<T>(this IEnumerable<T> lst, T obj, int index)
{
    return lst.Select((o, i) => new { o, i })
              .Where(x => x.o.Equals(obj))
              .ElementAt(index - 1)
              .i;
}

Although it's kind of strange that index starts at 1, but the result starts at 0.

A:         int index = lst.IndexOf(orange);
        if (index >= 0)
        {
            index = lst.IndexOf(orange, index + 1);
        }

or to make it generic you can use some LINQ:
    static int GetIndex(IEnumerable<Fruit> li, Fruit ob, int k)
    {
        var tmp = li.Select((it, i) => new Tuple<int, Fruit>(i, it)).Where(tup => tup.Item2 == ob).Skip(k - 1).FirstOrDefault();
        if (tmp == null)
            return -1;
        else
            return tmp.Item1;
    }

Then call GetIndex(lst, orange, 2)

A: Here's a generic extension search I just wrote up:
public static class ListExtension
{
    public static int GetIndex<T>(this List<T> entity, T what, int find)
    {
        int found = 0;
        int index = -1;

        while ((index = entity.IndexOf(what, (index + 1))) != -1)
        {
            found++;

            if (found == find)
                break;
        }

        return (index);
    }
}

All you have to do is call it like so:
int index = lst.GetIndex(apple, 2);

If the item you are looking for isn't found, it returns -1.

A: var result = list.Select((x, i) => new { x, i })
                  .Where(t => t.x == fruit)
                  .Skip(k - 1)
                  .Select(t => t.i)
                  .First();

A: You can extend classes with your own method for that class, sadly this is not possible for generic classes, so instead you give the type with the method.
public static class ListExtension
{
    public static int GetIndex<T>(this List<T> list, T value, int skipMatches = 1)
    {
        for (int i = 0; i < list.Count; i++)
            if (list[i].Equals(value))
            {
                skipMatches--;
                if (skipMatches == 0)
                    return i;
            }
        return -1;
    }
}

List<int> list = new List<int>();
list.Add(3);
list.Add(4);
list.Add(5);
list.Add(4);
int secondFour = (int)list.GetIndex(4, 2);

A: An extension of dtb's answer to account for when you don't find the value you're looking for:
public int GetIndex<T>(IEnumerable<T> list, T item, int itemNum) {
    // result is a nullable int containing the index
    var result = list.Select((x, i) => new { x, i })
                     .Where(t => item.Equals(t.x))
                     .Skip(itemNum - 1)
                     .Select(t => (int?)t.i)
                     .FirstOrDefault();
    // return -1 when item was not found
    return (result.HasValue ? result.Value : -1);
}


text:
Q: CSS box position floating Good afternoon !
I have a question concerning 3 independent boxes, all of them should contain text.

*

*1 top left

*1 top right

*In the middle a text field, could also be a    box (how can I do
that?)

*1 box down center

I know it is about styling, but please can you help me ? At the moment I have the following in my css: I deleted color, text and so on..  Is it also possible to find a way that for smaller screens the boxes are reducing their size.?  Hope you understand what I mean.
#box1 {
    width: 300px;
    padding: 25px;
    margin: 100px;
    float: left;
}

#box2 {
    width: 300px;
    padding: 25px;
    margin: 100px ;
    float: right;

}

#box3 {
    width: 400px;
    padding: 10px;
    margin: auto;

I have an example here, http://jsfiddle.net/3cUF5/5/.
The problem is, i need the green box in the middle und the 3 blue boxes should be not limited on 800px. Hope you can help. Or is there a JQuery Plugin for that? Tips and hints are welcome

A: Solution
You could use pure CSS to solve your problem. With CSS Flexbox you can center your content easily. You can change the width to 800px if you want your container not to be 100%
CSS
.boxes {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    justify-content: center;
    width: 100%;
}

.box {
    background-color: blue;
    height: 100px;
    margin: 30px;
    width: 100px;
}

.boxM {
    background-color: green;
    height: 100px;
    width: 100px;
}

HTML

Box1

Box2

Box3

Box2

Fiddle
http://jsfiddle.net/3cUF5/11/

A: You can do this (remove the floats and set them to display:inline-block):
CSS
#boxes {
  width: 800px;
  text-align: center;
}

#boxes .box {
  display: inline-block;
  width: 100px;
  height: 100px;
  margin: 30px;
  background-color: blue;
}

#boxes .boxM {
  display: inline-block;
  width: 100px;
  height: 100px;
  margin: 0 auto;
  background-color: green;
}

DEMO HERE

A: If each divs has static width, just set margin-left: 190px to boxM class.
Also, you'll have to delete float: left property in #boxes and add clear after first boxes div.
So the result of html file will be like this

Box1

Box2

Box3

Box2

and your css:
#boxes {
    width: 800px;
}

#boxes .box {
    width: 100px;
    height: 100px;
    margin: 30px;
    float: left;
    background-color: blue;
}

#boxes .boxM {
    width: 100px;
    height: 100px;
    margin-left: 190px;
    background-color: green;
}

A: Is that what you need ?
DEMO

#boxes {
  width: 800px;
  text-align: center;
}
#boxes .box {
  width: 100px;
  height: 100px;
  margin: 30px;
  display: inline-block;
  background-color: blue;
}
#boxes .boxM {
  width: 100px;
  height: 100px;
  background-color: green;
  margin: auto;
  display: block;
}

Box1

Box2

Box3

Box2

A: Not too tricky with absolute positioning. Will work with any size of container.

#boxes {
    width: 800px;
    position: relative;
}

#boxes .box {
    width: 100px;
    height: 100px;
    background-color: blue;
    position: absolute;
}
#boxes .box1 {
    left: 0;
}
#boxes .box2 {
    left: 50%;
    margin-left: -50px; /* half width */
}
#boxes .box3 {
    right: 0;
}
#boxes .boxM {
    width: 100px;
    height: 100px;
    margin: 0 auto;
    background-color: green;
    position: absolute;
    top: 120px;
    left: 50%;
    margin-left: -50px; /* half width */
}

Box1

Box2

Box3

Box2

Also you shouldn't use an ID in your HTML more than once.


text:
Q: Return URL is broken (escaping more characters than needed)
Possible Duplicate:
404 Error on page redirection after creating an account - slashes in URL escaped

Steps to reproduce

*

*Logoff

*Go to jQuery selection. Find element after another

*Login. Url is:
https://stackoverflow.com/users/login?returnurl=%2fquestions%2f5991513%2fjquery-selection-find-element-after-another

*Page is redirected to:
http://stackoverflow.com%2fquestions%2f5991513%2fjquery-selection-find-element-after-another/
Firefox 5, Windows 7


text:
Q: +conditional density of sum of random variables Let $X$ and $Y$ be two independent random variables distributed uniformly on $[0,1].$ How can I compute the following density:
$$f(X+Y|\max\{X,Y\}<a)\ \text{for}\ a\in [0,1]?$$
More generally, what is the formula for the pdf of the sum of two (independent) r.v. conditional on only knowing that the highest of the two can't exceed a given threshold?

A: EDITED HINT
In order to calcultae the density, you sometimes calculate the distribution function and then derive it, if it is possible. In our case we have a conditional density to be calculated. So we calculate the conditional cdf first. By definition,
$$F_{X+Y|\max(X,Y)<a}(u)=P(X+Y<u|\max(X,Y)<a)=\frac{P(X+Y<u \cap \max(X,Y)<a)}{P(\max(X,Y)<a)}.$$
Then
$$P(\max(X,Y)<a)=P(\max(X,Y)=X\cap X<a)+P(\max(X,Y)=Y \cap Y<a)=$$
$$=P(X\le Y\cap X<a)+P(Y\le X \cap Y<a).$$
Now, can you identify the the areas below? (Not the red, not the blue, Which ones?)
Then you can go ahead with the nominator being more complicated. But in that case you have the colored figures. Watch "a".


text:
Q: Sources of magnetic fields and violation of conservation of energy We know that current is a source of magnetic fields, for example when there is a current flowing through an infinitely long wire, this current creates a magnetic field, now I know that this magnetic field has energy that is capable of doing work!
So, I now came to the conclusion that this violates the principle of conservation of energy but I know it has to be true that energy is conserved, so what is wrong with my logic?

A:
when there is a current flowing through an infinite long wire there, this current creates a magnetic field through it, now I know that this magnetic field is capable of doing work

There is no need for an infinitely long wire. A finite loop also stores energy in the magnetic field.

what is wrong with my logic?

You are neglecting the energy required to run the current through the wire. The energy in the magnetic field comes from the energy supplied by the current. Even if the wire has no resistance energy will still be required to increase the current.


text:
Q: Get lastest record from section using mvc5 I want to show in my home page: All section (all link category and one lastest news record in this section).
Please help me to complete my code.
Thank you so much.
My DbContext class:
public partial class xxDbContext : DbContext
    {
        public xxDbContext()
            : base("name=xxDbConnection") { }
        public virtual DbSet<Category> Categories { get; set; }
        public virtual DbSet
 Sections { get; set; }
        public virtual DbSet<News> News { get; set; }
    }
    public partial class Section
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public virtual List<Category> Categories { get; set; }
    }
    public partial class Category
    {
        public int Id { get; set; }
        public int SectionId { get; set; }
        public string Name { get; set; }

        public virtual Section Section { get; set; }
    }
    public partial class News
    {
        public int Id { get; set; }
        public int CateId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
    }

My controllers
public ActionResult NewsInSec()
        {
            var model = db.Sections.Where(m => m.Publish).ToList();
            return PartialView("NewsInSec", model);
        }

My view
@model IEnumerable<xx.Models.Section>

    @foreach (var sect in Model)
    {

@sect.Name

            @foreach (var cate in sect.Categories)
            {

@cate.Name

            }

        **foreach (var item in sect.Categories.SelectMany(c => c.News).Where(c => c.Publish).OrderByDescending(c => c.CreateDate).Take(4).ToList())
    {

            @* News title*@

@item.Title

            @*Content of lastest news*@

@item.NewsContent

@item.Title

    }**
    }

Finally, i want to show section, cate, news as my attached photo.

Please help me to see and fix my code above one more time? Thanks and thanks so much.

A: You can add navigation property in Category for easy access to News.
public partial class Category
{
    public int Id { get; set; }
    public int SectionId { get; set; }
    ...

    public virtual List<News> News { get; set; }
}

And select last news for section:
@foreach (var cate in sect.SelectMany(s=>s.Categories.SelectMany(c=>c.News))
.OrderByDescending(n=>n.ID).Take(5))
 {

            // Title of lastest news

            // Content of lastest news

}

Note: more correct way find last news in your Controller and include result in ViewModel, Like that:
public class SomeViewModel
{
  public IEnumerable
 Sections {get;set;}
  public IEnumerable<News> LastNews{get;set;}
}

Fill this model in controller and pass in view.


text:
Q: Django update a row Hi I am trying to update a row in django but I am getting the error
update_form() takes exactly 2 arguments (1 given)

Here is my code:
view.py:
def update_form(request, id):
    if request.method == 'POST':
        a=newleave.objects.get(id=id)
        form = leave_application(request.POST, instance=a)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('successful.html')
    else:
        a=newleave.objects.get(id=id)
        form = leave_application(instance=a)
    return render_to_response('update_form.html'{'form':form},
context_instance=RequestContext(request))

form.py:
class leave_application(forms.ModelForm):
    class Meta:
        model = newleave
        fields =('First_Name', 'Last_Name', 'department', 'position', 'leave_type',             'Specify_details', 'start_Date', 'end_date', 'total_working_days', 'username')

update_form.html:
<form action ="/update_form/" method="post">{%csrf_token%}

{{form.as_table}}

<input type="submit" name="submit" value="Save Record" >

Can someone tell me what I am doing wrong?

A: The problem is probably in your urls.py.
The update_form view takes an argument id, so you should include it in the url pattern.
url(r'^update_form/(?P<id>\d+)/$', update_form, name='update_form')

For example, to edit the object with id=1, you would go to /update_form/1/
You would have to include the id in the template context
return render_to_response('update_form.html'{'form':form, 'id': id},
                          context_instance=RequestContext(request))

And include it it the form action:
<form action ="/update_form/{{ id }}/" method="post">{%csrf_token%}

Using the url tag would be slightly better:
<form action ="{% url 'update_form' %}" method="post">{%csrf_token%}

A: You should pass the id of the row to the update_form view:
<form action="{% url 'update_form' id %}" method="post">

And in urls.py:
url(r'^update_form/(?P<id>\d+)/$', update_form, name='update_form'),


text:
Q: how to find minimum difference between average of array and elements in that array in PHP First of all I need to find average of array, and then I need to find minimum difference between average of array and elements in that array and to display on which place is that element. This is the array:
myArray(4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19);

A: Crude but working:
<?php
$myArray = [4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19];

// the average: sum/count
$average = round(array_sum($myArray) / count($myArray));

foreach ($myArray as $value) {
  $diffs[] = abs($average - $value);
}

asort($diffs);
print_r($diffs);
$d = reset($diffs);
$p = array_search($d, $diffs);

echo sprintf("Average: %s, min diff: %s, diff pos: %s\n", $average, $d, $p);

A: You can try this:
    <?php

$myArray = array(4,-18,78,136,-52,14,19,-35,162,71,19,-5,-134,77,-78,-35,19);
$averageArray = "";

//Average of the array
if(count($myArray) > 0) {
    $averageArray = array_sum($myArray)  / count($myArray);
}
$diff = array();

//Diff of average value and each value in a array named diff
if(isset($myArray)) {
    foreach($myArray as $value) {
        $diff[] = abs($averageArray - $value);
    }
}
$key = array_search(min($diff),$diff);
echo "average = " . $averageArray .' - min value :'.min($diff).' - index:'.$key .' value: '.$myArray[$key]."\n";

A: The first step is to conceptualise an algorithm. What comes to mind is: find the average, find the absolute difference from each element to the average, and then find the minimum. The average can be calculated from the sum and the length.
$avg = array_sum($array) / count($array);
$diff = function ($x) use ($avg) { return abs($x - $avg); };
$answer = min(array_map($diff, $array));

To also get the element that is closest to the average, instead of mapping to just the difference we can keep the original element along for the ride. Then when we find the minimum we only compare the difference.
function minBy(callable $f, array $xs) {
  $min = $xs[0];
  foreach ($xs as $x) {
    if ($f($x, $min) < 0) $min = $x;
  }
  return $min;
}

$avg = array_sum($array) / count($array);
$diff = function ($x) use ($avg) { return array($x, abs($x - $avg)); };
$byDiff = function ($x,$y) { return $x[1] - $y[1]; };
$answer = minBy($byDiff, array_map($diff, $array));

To find the index of the element in the array (note that this may not be unique), you can use array_search.


text:
Q: How to return from a method after another method call has completed? I am building an android app in Flutter where I want to scan for WiFi networks and return the result of the scan when it completes.
The current method which I call via a MethodChannel between my Dart code and the java code is the following:
public List<ScanResult> getScanWifiResult(){

if (WifiManager != null && WifiManager.getScanResults() != null && WifiManager.getScanResults().size() > 0) {
    return WifiManager.getScanResults();
}
    return null;
}

The method returns List<ScanResult> which is what I want. Now, I need this method to return when WifiManager.startScan() has completed.
I have seen people using a BroadcastReceiver but I do not know how I can get my method to return only when this BroadcastReceiver has completed. Here is my start for the BroadcastReceiver setup.
public List<ScanResult> getScanWifiResult(){
    registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
    wifiManager.startScan();

    //Here I need to return wifiManager.getScanResults(); once the BroadcastReceiver is finished.
    //return wifiManager.getScanResults();
  }

BroadcastReceiver wifiReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
    results = wifiManager.getScanResults();
    unregisterReceiver(this);
};
}

How can I return from the method when the BroadcastReceiver has completed?
I have access to the permissions needed to use WifiManager.getScanResults. I can run both WifiManager.getScanResults and WifiManager.startScan without permission issues.
Update!
I cannot simple wait until there is data returned from wifiManager.getScanResult since I will hold that data of the most recent scan performed. Further, the scan which I start might return null which is also okay. I just want the result on the same scan that I start.

A: you can try this way in anywhere in your code for scanresult you must ask gps location permission in your manifest
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

After adding permission in your manifest
List<ScanResult> foundedNetwork;
foundedNetwork = wifiManager.getScanResults();
foundedNetwork.SSID;
foundedNetwork.BSSID;
foundedNetwork.level;


text:
Q: If this gets out... / If it gets out
If this gets out, they will be fined.
If it gets out, they will be fined.

What's the difference between them? I suppose that "this" could be "this information", but "it" - "this document". Right?

A: "It" is singular, and always refers to something previously mentioned. So, consider what comes before this statement. Is there a singular thing - a fact, or a story, or an event - that you are referring to?
"This" is also singular, but it can be used to collect things that are not already collected - for example, you could highlight a number of different items and say "all this".
So, if you have previously spoken about various different details that have not been referred to by a single collective term, then "this" might be more appropriate.
Examples:

This story is shocking. If it gets out, there'll be trouble.

In this example, 'it' refers back to the 'story', which is singular, even though it may contain many different details.

I've heard what has been happening. If this gets out, there'll be trouble.

Here, there is only reference to 'what has been happening', which could be lots of different things over a period of time. Because there is no collective term, 'this' seems appropriate.


text:
Q: String of words - DP I have a string of words and I must determine the longest substring so that the latest 2 letters of a word must be the first 2 letters of a word after it.
For example, for the words:
star, artifact, book, ctenophore, list, reply
Edit: So the longest substring would be star, artifact, ctenophore, reply
I'm looking for an idea to solve this problem in O(n). No code, I appreciate any sugestions on how to solve it.

A: First, read in all words into a structure. (You don't really need to, but it's easier to work that way. You could also read them in as you go.)
Idea is to have a lookup table (such as a Dictionary in .NET), which will contain key value pairs such that each two last letters of a word will have an entry in this lookup table, and their corresponding value will always be the longest 'substring' found so far.
Time complexity is O(n) - you only go through the list once.
Logic:
maxWord <- ""
word <- read next word
initial <- get first two letters of word
end <- get last two letters of word

if lookup contains key initial //that is the longest string so far... add to it
    newWord <- lookup [initial] value + ", " + word
    if lookup doesn't contain key end //nothing ends with these two letters so far
        lookup add (end, newWord) pair
    else if lookup [end] value length < newWord length //if this will be the longest string ending in these two letters, we replace the previous one
        lookup [end] <- newWord
    if maxWord length < newWord length //put this code here so you don't have to run through the lookup table again and find it when you finish
        maxWord <- newWord
else //lookup doesn't contain initial, we use only the word, and similar to above, check if it's the longest that ends with these two letters
    if lookup doesn't contain key end
        lookup add (end, word) pair
    else if lookup [end] value length < word length
        lookup [end] <- word
    if maxWord length < word length
        maxWord <- word

The maxWord variable will contain the longest string.
Here is the actual working code in C#, if you want it: http://pastebin.com/7wzdW9Es

A: The closest thing to O(n) I have is this :
You should mark every word with an Id. Let's take your example :
star => 1st substring possible. Since you're looking for the longest substring, if a substring stars with ar, it's not the longest, because you can add star in the front.
let's set the star ID to 1, and its string comparison is ar
artifact => the two first character matches the first possible substring. let's set the artifact ID to 1 as well, and change the string comparison to ct
book => the two first character don't match anything in the string comparisons (there's only ct there), so we set the book ID to 2, and we add a new string comparison : ok
...
list => the first two character don't match anything in the string comparisons (re from ID == 1 and ok from ID ==2 ), so we create another ID = 3 and another string comparison
In the end, you just need to go through the IDs and see which one has the most elements. You can probably count it as you go as well.
The main idea of this algorithm is to memorize every substring we're looking for. If we find a match, we just update the right substring with the two new last characters, and if we don't, we add it to the "memory list"
Repeating this procedure makes it O(n*m), with m the number of different IDs.


text:
Q: How to attach angular component to an third part application I would like to put my component in an application at runtime, and that would integrate with Angular.
I think a similar feature is:

*

*Make a call with XHR

*Put the response on a node with innerHtml

But, in the Angular way, that a component can integrate with the application, respond to lifecycles hooks, can react to click events and call a service.

A: you use Angular web components for it which was introduced in Angular 6.0
Follow along the following tutorial
https://medium.com/@tomsu/building-web-components-with-angular-elements-746cd2a38d5b
After creating web component elements,
we can use it like follows
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Custom Button Test Page</title>
  <script src="elements.js"></script>
</head>

<body>
  <custom-button label="First Value"></custom-button>

  <script>
    const button = document.querySelector('custom-button');
    button.addEventListener('action', (event) => {
      console.log(`"action" emitted: ${event.detail}`);
    })
    setTimeout(() => button.label = 'Second Value', 3000);
  </script>
</body>

</html>


text:
Q: Duda con el Toast en respuesta a Zxing code QR Quiero saber si hay alguna de forma de lograr que el mensaje se muestre en el Toast de manera diferente.
He creado un lector de codigo QR que funciona con zxing. Al escanear el código, el resultado se envía a un toast. Quiero que el mensaje que resulte del código QR se muestre en otra ventana y si es un enlace que me permita abrirlo con el navegador predeterminado de mi teléfono móvil.
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
    private ZXingScannerView zXingScannerView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void scan(View view){
        zXingScannerView =new ZXingScannerView(getApplicationContext());
        setContentView(zXingScannerView);
        zXingScannerView.setResultHandler(this);
        zXingScannerView.startCamera();

    }

    @Override
    protected void onPause() {
        super.onPause();
        zXingScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result result) {
        Toast.makeText(getApplicationContext(),result.getText(),Toast.LENGTH_LONG).show();
        zXingScannerView.resumeCameraPreview(this);

    }
}

A: Supongo que lo que recibes del QR es simple texto, te sugiero lo siguiente:
try{
   URL url = Uri.parse(stringRespuesta));
   Intent browserIntent = new Intent(Intent.ACTION_VIEW, url);
   startActivity(browserIntent);
catch(Exception e){
  //La respuesta no es una url
  Intent intent = new Intent(this, OtraActividad.class);
  intent.putExtra("respuesta", stringRespuesta);
  startActivity(intent);
}

Automáticamente intent de la url te abrirá el navegador determinado y si no es una url entonces te mandara a otra actividad donde podrás recibir la respuesta de este modo:
Bundle bundle = getIntent().getExtras();
String respuesta = bundle.getString("respuesta");

Buena suerte!


text:
Q: Date reading the wrong time zone I have the following date function:
function fixDate($strDateTime) {
 $strFormat = 'M, j, Y';
    $strFormatTime = '\a\t g:ia';
    $intTimeStamp = strtotime($strDateTime);
    $strDate = date($strFormat, $intTimeStamp);
    $strTime = date($strFormatTime, $intTimeStamp);

    if($strDate == date($strFormat)) {
        return "Today " . $strTime;
    }
    elseif($strDate == date($strFormat, strtotime('yesterday'))) {
        return "Yesterday " . $strTime;
    }
    else {
        return " on " . $strDate . " " . $strTime;
    }
}

I'm not sure if it is my date function that is causing this or the way my database is structured, but the date on my pages is reading AM when it is supposed to be PM. It is also reading US - Central time, when I need it to be US - Eastern time. I have the dates stored in phpmyadmin as the Date category.
How can I change the date so that is reads as US - Eastern time?

A: I always set the default time zone to GMT
# store all data internally as GMT:

#   local tz 1 \
#   local tz 2  + <-> webservice.php <-> gmt tz
#   local tz 2 /

date_default_timezone_set('Zulu');
if( ! defined( 'DATE_FORMAT' ) ) define ('DATE_FORMAT', 'Y-m-d H:i:s');

Then render GMT to the local timezone in the "view" layer.  Local time zones are a major pain to deal with, especially with daylight savings time.  :-)
#####################################################
# TIME UTILS
#####################################################

# STORE ALL TIME DATA AS GMT, ALONG WITH THE ORIGINAL TIME ZONE

# format date string referencing one timezone to another timezone, eg
# 'Zulu' -> 'America/Chicago'
# internally, store all data as GMT,
# where each person has a different view of data
# NOTE: full datetime is require, because of dst
function datetime_convert( $datestr, $from, $to, $format = null ) {

    if ( ! $from ) {
        error_log( "no timezone 'from'" );
        return $datestr;
    }

    if ( ! $to ) {
        error_log( "no timezone 'to'" );
        return $datestr;
    }

    if ( ! $format ) {
        $format = DATE_FORMAT; # defined above
    }

    $date = date_parse( $datestr );
    #print_r( $date );

    $dtime = new DateTime();

    # input in $from timezone
    $dtime->setTimeZone(new DateTimeZone($from));
    $dtime->setDate($date['year'],$date['month'],$date['day']);
    $dtime->setTime($date['hour'],$date['minute'],$date['second']);

    # output in $to timezone
    $dtime->setTimeZone(new DateTimeZone($to));
    $newdatestr = $dtime->format($format);

    return $newdatestr;
}

# convert dates with a GMT offset to offset == 0
# 2012-01-20T15:52:22.000-05:00 -> 2012-01-20T20:52:22.000Z
function datetime_normalize( $datestr ) {
    $dtime = new DateTime( $datestr );
    $dtime->setTimeZone(new DateTimeZone('Zulu'));
    $newdatestr = $dtime->format(DATE_FORMAT);
    return $newdatestr;
}

# convert a local time to GMT
function datetime_to_gmt( $datestr, $from, $format = null ) {
    return datetime_convert( $datestr, $from, 'Zulu', $format );
}

# convert a GMT time to local
function datetime_to_local( $datestr, $to, $format = null ) {
    return datetime_convert( $datestr, 'Zulu', $to, $format );
}

A: try to change,
function fixDate($strDateTime) {
$strFormat = 'M, j, Y';

to
function fixDate($strDateTime) {
$strFormat = 'M, j, Y';
date_default_timezone_set('America/New_York');