text:
Q: Using a JavaFX PopOver for a TabPanes Tab to peek at its content I try to create an Peek Control for a TabPane. So if an Panel was already opened an Snapshot gets saved. When the user hovers over the Tab it will show a PopOver. This is similar to Windows Aero Peek.
My problem is that the PopOver gets hidden when it should not... because it receives a hide() event from the Tabs Graphic.
I created a small runnable Example to demonstrate the Problem:
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.control.SingleSelectionModel;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class Main extends Application {
    Peek peek;
    Tab lastPeek;
    boolean show = false;

    public static void main(String[] args) {
        System.out.println("WE HAVE PROBLEMS WITH FOCUS HERE");
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) {
        peek = new Peek();
        primaryStage.setTitle("Tabs");
        Group root = new Group();
        Scene scene = new Scene(root, 400, 250, Color.WHITE);

        TabPane tabPane = new TabPane();

        BorderPane borderPane = new BorderPane();

        final PopOver popOver = new PopOver();
        popOver.setArrowLocation(ArrowLocation.TOP_LEFT);
        final ImageView preview = new ImageView();
        preview.setFitHeight(100);
        preview.setSmooth(true);
        preview.setPreserveRatio(true);
        popOver.setContentNode(preview);

        for (int i = 0; i < 5; i++) {
            Tab tab = new Tab();
            HBox hbox = new HBox();
            hbox.getChildren().add(new Label("", new ImageView(new Image(Main.class.getResourceAsStream(i + ".jpg")))));
            hbox.setAlignment(Pos.CENTER);
            tab.setContent(hbox);
            tabPane.getTabs().add(tab);

            final Label decoration = new Label("Tab" + i);
            tab.setGraphic(decoration);
            System.out.println("tab.getGraphic() = " + tab.getGraphic());

            final int index = i;
            tab.getGraphic().setOnMouseEntered(mouseEvent -> {
                boolean show = false;
                if (lastPeek != tab) {
                    // Show PopOver when mouse enters label
                    Image previewImage = peek.get(tab);
                    if (previewImage != null) {
                        show = true;
                    }
                    System.out.println("previewImage = " + previewImage);
                    preview.setImage(previewImage);
                    System.out.println("show() " + "Tab" + index);
                    lastPeek = tab;
                }
                if (!tab.isSelected() && !tab.isDisabled() && show) {
                    popOver.show((Node) mouseEvent.getSource(), -3);
                }
            });

            tab.getGraphic().setOnMouseExited(mouseEvent -> {
                // Hide PopOver when mouse exits label
                // how can we handle this correct??
                 popOver.hide();
                System.out.println("hide() " + "Tab" + index);
            });

        }

        tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {
            @Override
            public void changed(ObservableValue<? extends Tab> ov, Tab oldTab, Tab newTab) {
                Image preview = oldTab.getContent().snapshot(new SnapshotParameters(), null);
                peek.set(oldTab, preview);
            }
        });
        tabPane.selectionModelProperty().addListener(new ChangeListener<SingleSelectionModel<Tab>>() {

            @Override
            public void changed(ObservableValue<? extends SingleSelectionModel<Tab>> ov,
                    SingleSelectionModel<Tab> oldValue, SingleSelectionModel<Tab> newValue) {
            }
        });

        // bind to take available space
        borderPane.prefHeightProperty().bind(scene.heightProperty());
        borderPane.prefWidthProperty().bind(scene.widthProperty());

        borderPane.setCenter(tabPane);
        root.getChildren().add(borderPane);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

}

and this is the Peek class, that chaches the Snapshots
public class Peek {
    ObservableMap<Object, Image> peeks = FXCollections.observableHashMap();

    public void set(Object key, Image preview) {
        peeks.put(key, preview);
    }

    public Image get(Object key) {
        Image preview = peeks.get(key);
        return preview;
    }

}

A: It is actually because of the popOver you show. As soon as the popOver is shown, it takes the focus, and a MouseExit event is dispatch to your tab's graphic.
You can observe it by adding a bigger offset to your popup :
popOver.show((Node) mouseEvent.getSource(), -15);

Or simply by entering your mouse from the top of the tab instead from the bottom (the problem does not appear anymore).
Also, as the event seems not well-synchronized (when moving your mouse fast enought from a tab to another one) I advise you to create one PopOver by tab.
public class Main extends Application {

   Peek peek;

   Tab lastPeek;

   HashMap<Label, PopOver> popMap = new HashMap<>();

   boolean show = false;

   public static void main(String[] args) {
      System.out.println("WE HAVE PROBLEMS WITH FOCUS HERE");
      Application.launch(args);
   }

   @Override
   public void start(Stage primaryStage) {
      peek = new Peek();
      primaryStage.setTitle("Tabs");
      Group root = new Group();
      Scene scene = new Scene(root, 400, 250, Color.WHITE);

      TabPane tabPane = new TabPane();

      BorderPane borderPane = new BorderPane();

      for(int i = 0; i < 5; i++) {
         Tab tab = new Tab();
         HBox hbox = new HBox();
         hbox.getChildren()
               .add(new Label("", new ImageView(new Image(Main.class.getResourceAsStream(i + ".jpg")))));
         hbox.setAlignment(Pos.CENTER);
         tab.setContent(hbox);
         tabPane.getTabs().add(tab);

         final Label decoration = new Label("Tab" + i);
         tab.setGraphic(decoration);
         System.out.println("tab.getGraphic() = " + tab.getGraphic());
         final PopOver popOver = new PopOver();
         popOver.setArrowLocation(ArrowLocation.TOP_LEFT);
         final ImageView preview = new ImageView();
         preview.setFitHeight(100);
         preview.setSmooth(true);
         preview.setPreserveRatio(true);
         popOver.setContentNode(preview);

         popMap.put(decoration, popOver);
         final int index = i;
         decoration.setOnMouseEntered(mouseEvent -> {

            PopOver lPop = popMap.get((Label) mouseEvent.getSource());

            boolean show = false;
            if(lastPeek != tab) {
               // Show PopOver when mouse enters label
               Image previewImage = peek.get(tab);
               if(previewImage != null) {
                  show = true;
               }
               System.out.println("previewImage = " + previewImage);
               preview.setImage(previewImage);
               System.out.println("show() " + "Tab" + index);

            }
            if(!tab.isSelected() && !tab.isDisabled() && show) {
               lPop.show((Node) mouseEvent.getSource(), -decoration.getHeight() / 2);
            }
         });

         tab.getGraphic().setOnMouseExited(mouseEvent -> {
            // Hide PopOver when mouse exits label
            // how can we handle this correct??
            PopOver lPop = popMap.get((Label) mouseEvent.getSource());
            if(lPop.isShowing())
               lPop.hide();
            System.out.println("hide() " + "Tab" + index);
         });

      }

      tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {

         @Override
         public void changed(ObservableValue<? extends Tab> ov, Tab oldTab, Tab newTab) {
            Image preview = oldTab.getContent().snapshot(new SnapshotParameters(), null);
            peek.set(oldTab, preview);
         }
      });
      tabPane.selectionModelProperty().addListener(new ChangeListener<SingleSelectionModel<Tab>>() {

         @Override
         public void changed(ObservableValue<? extends SingleSelectionModel<Tab>> ov,
               SingleSelectionModel<Tab> oldValue, SingleSelectionModel<Tab> newValue) {
         }
      });

      // bind to take available space
      borderPane.prefHeightProperty().bind(scene.heightProperty());
      borderPane.prefWidthProperty().bind(scene.widthProperty());

      borderPane.setCenter(tabPane);
      root.getChildren().add(borderPane);
      primaryStage.setScene(scene);
      primaryStage.show();
   }
}


text:
Q: My carousel does not work properly on IOS I would like to take back this code: https://codepen.io/kellyex/pen/JjoYpEx
The problem is that I don't understand how and why the first card only is draggable on IOS (while everything works on Android).
On IOS, everything works fine but only on the Codepen editor, not elsewhere.
Can you help me? Thank you!
HTML :

Many Items

Item 1

Item description

Item 2

Item description

Item 3

Item description

Item 4

Item description

Item 5

Item description

Item 6

Item description

Item 7

Item description

Item 8

Item description

Item 9

Item description

Item 10

Item description

Item 11

Item description

Item 12

Item description

Item 13

Item description

Item 14

Item description

Item 15

Item description

Item 16

Item description

Fewer Items

Item 1

Item description

Item 2

Item description

Item 3

Item description

Item 4

Item description

Item 5

Item description

Item 6

Item description

Item 7

Item description

Item 8

Item description

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get the percentage of each unique value from a column grouped by another column? I have a problem where I have a column filled with the year of the event (2007, 2008, ..., 2019) and another column with the type of the event (event_A, event_B, event_C). I want to know from each year what the percentage of the events B that happened.
Basically, I have this:
Year    Event_Type
2007    Event_A
2007    Event_A
2007    Event_B
2007    Event_B
2008    Event_B
2008    Event_B

And I want to achieve this:
2007    Event_B    50%
2008    Event_B    100%

I've been looking for this in a while, but I keep getting to group by posts that are not related to this. So I am still far from achieving the result I want.
The closest I got was by doing:
df.groupby(['Year', 'Event_Type']).size()

A: Method 1:
Using crosstab/pivot to count the no of occurrences per year followed by slicing Event_B column and dividing it by sum of df across axis=1
c = pd.crosstab(df['Year'],df['Event_Type'])
c.loc[:,'Event_B'].div(c.sum(1),axis=0).mul(100).astype(str).add('%')

Method 2:
You can use count the no. of times Event_B occurs in a group divided by the group size:
(df['Event_Type'].eq('Event_B').groupby(df['Year']).sum()
.div(df.groupby('Year').size(),axis=0).mul(100).astype(str).add('%'))

Year
2007     50.0%
2008    100.0%


text:
Q: BigQuery streaming data not available instantly Since couple of days some data i am streaming to bigquery is not available instantly (as it normally happens) within bigquery web ui after being inserted successfully.
My use case consists of inserting thousand of lines using :
bigquery.tabledata().insertAll(...)

The results of the streaming inserts into the table are :
(i am also checking for insertErrors to be sure as described here):
BigQuery insert status : {"kind":"bigquery#tableDataInsertAllResponse"}
BigQuery insert errors  : null

Total number of lines available in bigquery web ui is different that total inserted.
I would be grateful for any help.
Bigquery project details :
Project ID  : favorable-beach-87616
Table : mtp_UA_xxxx_1_20150410

Project dependencies on google libraries:
compile 'com.google.api-client:google-api-client:1.19.0'
compile 'com.google.http-client:google-http-client:1.19.0'
compile 'com.google.http-client:google-http-client-jackson2:1.19.0'
compile 'com.google.oauth-client:google-oauth-client:1.19.0'
compile 'com.google.oauth-client:google-oauth-client-servlet:1.19.0'
compile 'com.google.apis:google-api-services-bigquery:v2-rev171-1.19.0'
compile 'com.google.api-client:google-api-client:1.17.0-rc'

Great thanks in advance for your help!

A: When you say the total number of lines available in the web UI, do you mean the number of rows that show up in the 'details' pane on the table, or the number of rows that are returned if you do a SELECT COUNT(*) query?
If the former, that is expected, since that counter only returns the number of rows that have been flushed to long-term storage (as opposed to the short-term storage buffers the streaming data originally gets written to). This is admittedly confusing, and we are working on a fix.
If the latter, the rows don't show up in a query, that is more concerning. If that is the case, please let us know and we'll investigate.


text:
Q: Is my server toast? Last night I received an e-mail from mdadm about the possible failure of two drives on my array. The raid array was set up as a 4 2TB drive raid5 with one hot spare. Is this system truly fried? Did the hot spare pick up anything at all, or did the two drives fail at once? Did one drive fail, start to rebuild onto the spare, and then cause another drive failure? I'm fairly new to working with raids, and this system is one I inherited from a previous employee, so I'm unsure of what the proper troubleshooting steps are here. Any help would be much appreciated.
Output of cat /proc/mdstat:
sudo cat /proc/mdstat
Personalities : [raid6] [raid5] [raid4] [linear] [multipath] [raid0] [raid1] [raid10]
md0 : active raid5 sdc[4](F) sdd[5](F) sda[6](S) sdb[0] sde[3]
      5860543488 blocks level 5, 64k chunk, algorithm 2 [4/2] [U__U]

Output of mdadm --detail:
#sudo mdadm --detail /dev/md0

/dev/md0:
        Version : 0.90
  Creation Time : Mon Jun 21 13:54:13 2010
     Raid Level : raid5
     Array Size : 5860543488 (5589.05 GiB 6001.20 GB)
  Used Dev Size : 1953514496 (1863.02 GiB 2000.40 GB)
   Raid Devices : 4
  Total Devices : 5
Preferred Minor : 0
    Persistence : Superblock is persistent

    Update Time : Mon Apr 29 10:52:27 2013
          State : clean, FAILED
 Active Devices : 2
Working Devices : 3
 Failed Devices : 2
  Spare Devices : 1

         Layout : left-symmetric
     Chunk Size : 64K

           UUID : 2874db80:a0f02d66:999df3c7:ff8f8e6e (local to host bigkahuna)
         Events : 0.10984

    Number   Major   Minor   RaidDevice State
       0       8       16        0      active sync   /dev/sdb
       1       0        0        1      removed
       2       0        0        2      removed
       3       8       64        3      active sync   /dev/sde

       4       8       32        -      faulty spare   /dev/sdc
       5       8       48        -      faulty spare   /dev/sdd
       6       8        0        -      spare   /dev/sda

A: If there are no smartctl errors on the drives in logs or in dmesg.
You can try to reassemble the RAID:
mdadm --assemble /dev/md0 --scan --force


text:
Q: Datastore API version This Dart appengine package refers two protocol buffers API versions - V3 and V4
https://github.com/dart-lang/appengine/tree/master/lib/src/protobuf_api/internal
(see also
https://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/datastore/)
(The public API of this Dart package forwards only to V3)
I made several attempts to find background information about the differences.
Are there suggestions how to migrate from v3 to v4?
Can v4 already be used?
Are there criterias which makes v3 a better fit than v4?

A: *

*V3 seems to be used only inside AppEngine

*V4 seems to be the protocol used by the Google Cloud Datastore service.

*V1 is very similar to V4 and seems to be the successor of V3 and V4 for both AppEngine and Google Cloud Datastore.


text:
Q: typeahead suggestions do not appear hello everyone I'm trying to use a small project and typeahead.js mine but it just does not work no matter what I do, I've re-written the code, removed other javascript libraries but nothing works, what can be?
My javascript
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery(function(){
var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
        var matches, substringRegex;

        // an array that will be populated with substring matches
        matches = [];

        // regex used to determine if a string contains the substring `q`
        substrRegex = new RegExp(q, 'i');

        // iterate through the pool of strings and for any string that
        // contains the substring `q`, add it to the `matches` array
        $.each(strs, function(i, str) {
            if (substrRegex.test(str)) {
                // the typeahead jQuery plugin expects suggestions to a
                // JavaScript object, refer to typeahead docs for more info
                matches.push({ value: str });
            }
        });
        cb(matches);
    };
};

var colors = ["red", "blue", "green", "yellow", "brown", "black"];
jQuery('.typeahead').typeahead( {}, {source: substringMatcher(colors)} );
});
});

html
<input type="text" class="typeahead" data-provide="typeahead">

A: When you use
jQuery.noConflict();

you cannot use $ anymore, as in
$.each(strs, function(i, str) {

that line should be
jQuery.each(strs, function(i, str) {

This solves the problem. Have a look at the jsbin:
http://jsbin.com/ratuho/1/


text:
Q: Run a task when UWP app is being deleted I need to do some process when the app is being deleted in order to remove all impacts that the app incurs to the system. My app stores some credentials in Windows-Hello-Secure storage (CredentialService) and these credentials only can be removed by the app that registered them.
Is there any way for doing that by running a task before uninstalling?

A: I believe that there are no chance to remove the key at uninstallation. But, is this a real issue? If you use the Key Credential Manager for Windows Hello, only YOUR app can access the key. No one - except your app - can access for it.

A: No there isn't. the app model should take of leaving the system in the right state back. it deletes the app store, it removes protocol and file handler. Do you have a specific  example for what you need to do this manually?


text:
Q: Is there a way to access the current session from within a substitution control? Looks like context parameter of asp:net substitution control method is missing the current session once the page is output cached.
Aside from getting the substitution control's content thru ajax or using some other method to store data that would otherwise be in session (like database) is there anything else I can do?
Is there a workaround to use native asp.net session in substitution control?
<asp:Substitution  ID="myid" MethodName="method1"></asp:Substitution>

public static string method1(HttpContext context) <--  [1]

[1] --- conext.session is null after page is cached

A: From the same blog.
re: Tip/Trick: Implement "Donut Caching" with the ASP.NET 2.0 Output Cache Substitution Feature
Friday, February 23, 2007 1:30 AM by ScottGu
Hi Scott,
I think the error you are seeing is because you are trying to access the session object.
Unfortunately I don't think you can access the session in this scenario - since the session object is never populate (since the page is never created).
Sorry!
Scott

A: What happens if you ensure that context.Session isn't null before accessing the value? I've had session problems before, not when using the Substitution control though, because Context.Session isn't set for the first request a user makes. You may be having a related problem as it wouldn't sit in the standard page lifecycle.
According to ScottGu everything should be available.
This static method will be passed an HttpContext object at runtime that contains the standard ASP.NET Request, Response, User, Server, Session, Application intrinsics, and which you can then use ...
Tip/Trick: Implement "Donut Caching" with the ASP.NET 2.0 Output Cache Substitution Feature


text:
Q: Options for external monitor display Every time I plug in an external monitor via hdmi, I get presented four options, of which the only 'extend' option is to extend the display to the right. The way my desk is set up, I need to extend the display to the left. I can open Display from the menu to change this, but this requires about four more clicks than desirable. Is there any way to change the defaults in the menu that comes up when you plug in an external monitor?
I am running Xubuntu 15.04.


text:
Q: How can I view the hierarchy of function calls when an error occurs in Visual Studio? Before working in Visual Studio, I worked in the Matlab program and there, when an error occurred, function calls were consistently displayed in the command window, indicating the line number, which part of the code caused the error. Now I work in Visual Studio and I really need the same a tool.
I found the "call hierarchy" window, but unfortunately it does not display so conveniently, since entering a function can be from different functions, it is not clear which one caused the error.

A: If you are using Visual Studio when you get an error you can go to Debug>Windows>Call Stack


text:
Q: For loop R, skip first 125 rows and then loop over for each row after I have a problem looping through my rows in a vector.
My dataset looks like this:
 FullDataTest$Prices
 [1] 1131.130 1135.260 1136.030 1126.520 1128.590 1142.760 1139.810 1145.540 1157.760 1152.110 1145.810 1156.990
 [13] 1151.820 1147.060 1144.110 1140.990 1139.090 1143.670 1144.910 1144.940 1155.960 1149.100 1151.040 1154.880
 [25] 1156.870 1147.210 1140.580 1123.890 1106.780 1120.570 1104.490 1110.700 1123.750 1122.320 1109.780 1095.400
 [37] 1093.950 1091.330 1109.190 1108.060 1122.470 1127.000 1126.210 1132.170 1141.810 1150.570 1148.160 1140.530
 [49] 1139.320 1139.320 1145.200 1129.440 1128.170 1128.840 1134.610 1135.820 1118.150 1124.090 1139.930 1140.600
 [61] 1135.530 1138.110 1122.410 1113.890 1107.300 1117.490 1119.550 1121.530 1113.990 1098.700 1087.120 1095.450
 [73] 1097.280 1096.440 1095.700 1084.100 1091.490 1088.680 1089.190 1093.560 1095.410 1113.050 1114.940 1121.280
 [85] 1120.680 1121.200 1124.990 1116.640 1122.500 1140.420 1142.180 1131.330 1136.470 1136.470 1125.290 1132.010
 [97] 1133.560 1132.050 1135.020 1130.300 1134.410 1144.060 1140.650 1134.430 1133.350 1136.200 1140.840 1128.940
 [109] 1125.380 1116.210 1118.330 1109.110 1112.810 1114.350 1115.140 1111.470 1106.690 1101.390 1100.900 1108.670
 [121] 1093.880 1096.840 1086.200 1084.070 1094.830 1095.420 1100.430 1101.720 1106.620 1099.690 1098.630 1080.700
 [133] 1063.970 1065.220 1079.040 1075.790 1063.230 1064.800 1079.340 1081.710 1095.170 1091.230 1098.350 1095.680
 [145] 1096.190 1104.960 1105.090 1107.770 1099.150 1104.240 1105.910 1118.310 1113.630 1121.300 1116.270 1118.380
 [157] 1123.920 1125.820 1128.330 1120.370 1123.500 1128.550 1122.200 1129.300 1113.560 1108.360 1110.110 1103.520
 [169] 1110.060 1114.800 1114.580 1131.500 1135.170 1134.480 1142.050 1130.650 1122.140 1121.840 1113.650 1103.290
 [181] 1108.200 1114.020 1103.230 1103.660 1106.490 1095.740 1094.810 1111.090 1125.400 1127.440 1130.200 1130.510
 [193] 1130.540 1143.200 1161.670 1166.170 1164.890 1164.080 1162.910 1184.170 1183.810 1175.430 1181.940 1183.550
 [205] 1170.340 1177.240 1176.940 1181.760 1182.650 1178.570 1173.820 1191.370 1190.330 1191.170 1190.250 1177.070
 [217] 1182.810 1189.240 1188.000 1198.680 1203.380 1205.720 1203.210 1194.220 1194.660 1205.450 1209.570 1210.130
 [229] 1210.130 1204.920 1213.540 1213.450 1213.550 1211.920 1202.080 1188.050 1183.740 1187.890 1186.190 1190.250

From these prices I'm calculating the daily log-returns through the R code:
   log_returns <- diff(log(prices),lag=1)

This works perfectly fine and I get the daily log returns throughout the data.
I then want to loop through this data, skipping the first 125 rows, and then calculating the sum of the previous 125 days/rows. However, after I skip the 125 days. I want the loop to go 1 day/row forward and for each row calculating the sum of the past 125 daily log-returns for the rest of the dataset.
I cannot seem to figure out how to do this, and I have tried different methods in the for-loop, with none of them working.
Can anybody help here?

A: You don't need a loop - just use cumulative sums and take the differences 125 apart...
cumprices <- cumsum(log_returns)

sums_125 <- tail(cumprices, -125) - head(cumprices, -125)


text:
Q: Is using setState in every iteration of a loop bad practice? Here is a little code snippet:
async componentDidMount() {
    ...
    this.state.postList.forEach(element => {
      this.fetchItem(element);
    });
}

async fetchItem(query) {
    ...
    this.setState( previousState => {
        const list = [...previousState.data, data];
        return { data: list };
    });
}

I'm curious to know if using setState in every iteration of a forEach loop is a bad idea or not. I'm suspecting that it impacts performance, but I'd like to know for sure because this seemed like the simplest solution to this problem.

A: Here's an alternative approach: Update your fetchItem to just return the item. In your componentDidMount use Promise.all to get all the items and then commit them to the state in a single operation.
async componentDidMount() {
    const items = await Promise.all(this.state.postList.map(element => fetchItem(element)));
    this.setState({data: items});
}

async fetchItem(query) {
    const item = await getItem(query) // however you accomplish this
    return item;
}

A:
I'm curious to know if using setState in every iteration of a forEach loop is a bad idea or not.

If it would be directly inside of an iteration then definetly yes, as React than has to merge all the updates you make during the iteration, which will probably take much more time than if you would just set the state after the loop.
In your case however, you do start an asynchronous action in each iteration, and as all asynchronous tasks finish at different times, the updates aren't run all at once. The main benefit of your approach is that if these asynchronous tasks take some time (e.g. if you fetch a lot of data for each), then some information can already be shown, while some are still loading. If all those asynchronous calls only load a small amount of data, well then you should actually change your API to deliver all the data at once. So it really depends on your usecase wether thats good or bad.


text:
Q: Spring - Change request Content-Type: text/plain to Content-Type: multipart/form-data in a Filter I'm using custom encryption to communicate front-end and back-end.
I'm trying to change the request Content-Type in a filter (Spring GenericFilterBean) before it reaches the controller.
To be more specific I want to change the request Content-Type: text/plain sent by front-end to Content-Type: multipart/form-data.
I made an infographic:

CustomFilter.java
public class CustomFilter extends GenericFilterBean {

...

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    // ORIGINALS
    HttpServletRequest originalRequest = (HttpServletRequest) request;
    HttpServletResponse originalResponse = (HttpServletResponse) response;

    // DECRYPT REQUEST
    String bodyDecrypted = bodyDecrypted = decryptRequest(originalRequest);

    CryptRequestWrapper wrappedRequest = new CryptRequestWrapper(originalRequest, bodyDecrypted.getBytes());
    CryptResponseWrapper wrappedResponse = new CryptResponseWrapper(originalResponse);

    // ---------------------------------------------//
    //           CHANGE CONTENT TYPE HERE?          //
    // ---------------------------------------------//

    // CHAIN
    chain.doFilter(wrappedRequest, wrappedResponse);

    // ENCRYPT RESPONSE
    String responseEncrypted = encryptResponse(vec, wrappedResponse);
    response.getOutputStream().write(responseEncrypted.getBytes());

}

private String decryptRequest(HttpServletRequest originalRequest){
    // STUFF
}

private String encryptResponse(ModifyResponseBodyWrapper wrappedResponse){
    // STUFF
}

}
CryptRequestWrapper.java
public class CryptRequestWrapper extends HttpServletRequestWrapper {

    private final Logger log = LoggerFactory.getLogger(CryptRequestWrapper.class);

    private final ByteArrayInputStream decryptedDataBAIS;

    CryptRequestWrapper(HttpServletRequest request, byte[] decryptedData) {
        super(request);
        decryptedDataBAIS = new ByteArrayInputStream(decryptedData);

    }

    @Override
    public BufferedReader getReader() throws UnsupportedEncodingException {
        return new BufferedReader(new InputStreamReader(decryptedDataBAIS, StandardCharsets.UTF_8.name()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {

        return new ServletInputStream() {
            @Override
            public int read() {
                return decryptedDataBAIS.read();
            }

            @Override
            public boolean isFinished() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                // TODO Auto-generated method stub
            }
        };

    }
}

Question
Its possible to do this? What I'm missing?
On the front-end side I tried to send a multipart request with body encrypted, but it's not working because the multipart request seems to need a "key/value" body. This is why i'm sending a text/plain.


text:
Q: JQuery Shift-Select Issues List of items in a listbox populated using jquery.
I click the first item and it's selected.
I shift clicked the 3rd item and now items 1-3 are selected.
Shift clicking the 6th item only selects 3-6th instead of 1st-6th as you would expect.
Any idea how to fix something like this? :)
Turns out it WAS a logic error on my side. Took me awhile to find the code. :P

A: Unless this is a custom select replacement, this is browser behavior, not jQuery.


text:
Q: Обработка нажатия на ENTER Я уже спрашивал это здесь, но немного не понял и появились еще вопросы по этому поводу.
На клаве стоит кнопка ENTER - со стрелкой, которая переносит на новую строку и именно такая мне нужна и именно такая не обрабатывается, не реагирует.
В общем работает со всеми видами интера, только не с тем, которая мне нужна. Почему именно она не работает? Так и должно быть? Или я что то не так делаю. И как это сделать? Делал KeyListener'ом, OnEditorActionListenerом - всё тоже самое.
Код вот. В разметке у эдита обычные id , ширина и высота.
edit.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (KeyEvent.ACTION_DOWN == event.getAction()){
                switch (keyCode){
                    case KeyEvent.KEYCODE_ENTER:
                        Log.e("TAG", "Нажат интер");
                        break;
                    default: Log.e("TAG", "Нажато что то");
                }
                return true;
            }
            return false;
        }
    });

Насчет TextWatcher, не знаю как им сделать то, что мне нужно. Если keyListenerом нельзя то объясните пожалуйста как делать через TextWatcher.
В предыдущем примере по ссылке написано "нужная кнопка" и в общем не понял как туда вставлять ENTER.
Задача такая, нужно получить первую строку в EditText, определяется она по кнопке ENTER. То есть написали что то, нажали ENTER и это первая строка. Курсор на новой строке, печатаем дальше. Строки разделяются кнопкой ENTER. Получить ее можно как я понял split`ом.
Это я рассказал, чтобы было понятно о чем я. Я новичок.

A: Enter на "нужная кнопка" не прописывается, да.
Если нужен именно Enter, попробуйте так: (пример взят отсюда)
EditText editText = (EditText) findViewById(R.id.myEditText);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
      if (actionId == EditorInfo.IME_ACTION_DONE) {
          ...ваши действия
          return true;
      }
    return false;
    }
});

в самом EditText (в xml) надо выставить android:imeOptions = "done" (или более подходящий).

A: Сделал. Получил первую строчку edittext'а. Не обрабатывая ENTER, Код
edit.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (!s.toString().contains("\n")){
                Log.e("TAG", "Первая строка: Печатается");
            }else {
                String[] str = s.toString().split("\n");
                Log.e("TAG", "Первая строка: " + str[0]);
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

A: Была такая же проблема, использовал тоже TextWatcher
        @Override
        public void afterTextChanged(Editable s) {
            if (chooseCity.getText().toString().trim().isEmpty()) {
                return;
            }
            if (s.toString().contains("\n")) {
                chooseCity.setText(s.toString().replace('\n', ' ').trim());
                hideSoftKeyboard(getApplicationContext());
            }
        }


text:
Q: Custom JsonConverter gets reader with TokenType "EndObject" when it shouldn't be I have a stream with an array of JSON objects which come in two different formats but contain the same sort of data, and I want to deserialize both of these formats into the same type so my view doesn't need custom logic for both formats of data. Currently I am handling this using a custom JsonConverter.
Here is my model:
[JsonObject]
[JsonConverter(typeof(MyCommonObjectJsonConverter))]
public class MyCommonObject {
    // some common fields, e.g.
    public String Id { get; set; }
    public string Text { get; set; }
}

Here is my custom JsonConverter:
public class MyCommonObjectJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // don't need to worry about serialization in this case, only
        // reading data
        throw new NotImplementedException();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);

        MyCustomObject result;
        if (IsFormatOne(jObject))
        {
            // the structure of the object matches the first format,
            // so just deserialize it directly using the serializer
            result = serializer.Deserialize<MyCustomObject>(reader);
        }
        else if (IsFormatTwo(jObject))
        {
            result = new MyCustomObject();

            // initialize values from the JObject
            // ...
        }
        else
        {
            throw new InvalidOperationException("Unknown format, cannot deserialize");
        }

        return result;
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(MyCustomObject).IsAssignableFrom(objectType);
    }

    // Definitions of IsFormatOne and IsFormatTwo
    // ...
}

However, when I deserialize the first format's objects, I get an error saying that it can't load the JObject, since the JsonReader has TokenType "EndToken". I'm not sure why this is happening, the data I am loading in is correctly formatted. Any suggestions on what I should be looking out for?

A: You want to fall back to the default deserialization when reading your MyCommonObject, however:

*

*The call to JObject.Load(reader) has already advanced the reader past the object, as you have observed, and

*calling serializer.Deserialize<MyCustomObject>(reader) would in any event result in infinite recursion.

The customary way to avoid unwanted recursion in ReadJson() in cases like this is to allocate your result manually then call serializer.Populate(jObject.CreateReader(), result).  I.e.:
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        JObject jObject = JObject.Load(reader);

        MyCommonObject result;
        if (IsFormatOne(jObject))
        {
            result = (existingValue as MyCommonObject ?? (MyCommonObject)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator()); // Reuse existingValue if present
            // the structure of the object matches the first format,
            // so just deserialize it directly using the serializer
            using (var subReader = jObject.CreateReader())
                serializer.Populate(subReader, result);
        }
        else if (IsFormatTwo(jObject))
        {
            result = (existingValue as MyCommonObject ?? (MyCommonObject)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator());

            // initialize values from the JObject
            // ...
        }
        else
        {
            throw new InvalidOperationException("Unknown format, cannot deserialize");
        }

        return result;
    }

A: Figured it out while writing this up, calling serializer.Deserialize<MyCustomObject>(reader) was recursing into my converter again, at which point the reader will have reached an end token from being loaded into the JObject, making the TokenType equal to EndToken. I should have checked the stack trace more carefully. For now I'm going to write custom initialization logic for both formats, making my model class format-agnostic.


text:
Q: Group by causing datagrid to fail I have a c# application whose GUI has datagrid which is being populated at the moment with the following sql
      UPDATE    mi
      SET       mi.ClientName = c.ClientName
      FROM      generic.MasterInventory mi INNER JOIN
                generic.Client c ON mi.FK_Client = c.PK_Client
      SELECT DISTINCT
                ClientName, FundName, PK_MasterInventory, FK_Fund, FK_Client, ISIN,  Status, ShareCurrency, PriceFrequency, ClassCode, Simulation, Hedged,
                                              FundCurrency, [Type]                                                             FROM         generic.MasterInventory

However I am having trouble removing the duplicate records . I have tried using groupby
      UPDATE    mi
      SET       mi.ClientName = c.ClientName
      FROM      generic.MasterInventory mi INNER JOIN
                generic.Client c ON mi.FK_Client = c.PK_Client
      SELECT DISTINCT
                ClientName, FundName, PK_MasterInventory, FK_Fund, FK_Client, ISIN,  Status, ShareCurrency, PriceFrequency, ClassCode, Simulation, Hedged,
                                              FundCurrency, [Type]                                                               FROM         generic.MasterInventory
       GROUP BY ClientName

However doing this results in an empty datagrid ...Does anyone know why this is/ a workaround ?
Running Group by in Query builder gives this error message
      Column generic.masterInventory.FundName is invalid
      in the select list because it is not contained in
      either an aggregate function or the group by clause


text:
Q: Pandas combine two dataframes to update values of a particular column in 1st dataframe I have two dataframes:

df1 :
    A     B     C
0   a0    b0    c0
1   a1    b1    c1
2   a2    b2    c2
3   a3    b3    c3
4   a4    b4    c4

df2 :
    A     B     C
0   a0    b0    c11
1   a1    b1    c5
2   a70   b2    c20
3   a3    b9    c9

In df1, for every row, whenever Column A and Column B values are equal to values in df2, column C should be updated with value from df2.
Output:
    A     B     C
0   a0    b0    c11
1   a1    b1    c5
2   a2    b2    c2
3   a3    b3    c3
4   a4    b4    c4

I tried the following, but it did not work.
df1.set_index(['A', 'B'])
df2.set_index(['A', 'B'])
df1.update(df2)
df1.reset_index()
df2.reset_index()

A: df1["C"][:4] = np.where((df1["A"][:4]==df2["A"])&(df1["B"][:4]==df2["B"]),df2["C"],df1["C"][:4])

    A   B   C
0   a0  b0  c11
1   a1  b1  c5
2   a2  b2  c2
3   a3  b3  c3
4   a4  b4  c4


text:
Q: If with Find not working as intended I'm very new to VBA and have created a chart based on the Macro Recorder in Excel 2007. I'm having some trouble with an If statement that I expected to find the value of FALSE in a cell range and change the color of a marker in my chart. I'm not getting the desired results, but all of the markers are changing to the Else condition. Here is the snippet for reference:
Dim rSeries As Range
Dim MyChart As Chart

Set rSeries = Sheets("Data").Range("I24:I39")
Set MyChart = Sheets("Sheet1").ChartObjects("PT_Schedule").Chart
With MyChart
    If rSeries.Find("FALSE") Then
        .SeriesCollection(8).MarkerForegroundColor = RGB(255, 255, 0)
        .SeriesCollection(8).MarkerBackgroundColor = RGB(255, 255, 0)
    Else
        .SeriesCollection(8).MarkerForegroundColor = RGB(255, 0, 0)
        .SeriesCollection(8).MarkerBackgroundColor = RGB(255, 0, 0)
    End If
End With

Can any one explain why any cell value of FALSE is not meeting the criteria and what should the code be changed to?
Thanks in advance!

A: the method Find() returns a Range, not a Boolean.
You should verify if the range returned is not null (Nothing in VBA)
If Not rSeries.Find("FALSE") Is Nothing Then


text:
Q: cygwin1.dll is missing - Cannot run program I wrote a program in C/C++ and compiled it using Cygwin. When I ran the compiled file, I receive an error about a missing library.

A: Cygwin is like a simple framework: With every program you build you have to include the library cygwin1.dll.
Important note: Downloading the library online might be risky as it can be a virus.
To fix the issue:
 1. Go to your cygwin directory. Usually that is C:\cygwin or C:\cygwin64.
  If you don't know where cygwin is, download the setup file and run it. The installation path the installer suggests is the Cygwin installation location.
Tip: Don't use a directory to put cygwin in that includes spaces (" ") as it will be easier to run programs with command-line parameters.
 2. Copy the file. It should be in <Drive>:\cygwin\bin\cygwin1.dll.
 3. Copy the file to your program folder, the same directory as your exe file.
Your program should run without throwing an exception.


text:
Q: How to change the destination for SIP BYE message in Sofia SIP Let me describe my problem first. I'm using Sofia SIP for a telephony application and the SIP proxy I'm using is behind a NAT. This means that an incoming invite from the proxy has as Contact header the internal proxy IP (for example 10.0.0.1). This means that when I hang up the phone from my application Sofia automatically sets as destination for the BYE message the IP 10.0.0.1, which as you can imagine is not routable and as a result it fails.
So what I want to do is to change the destination for the BYE message to be the 'external' proxy IP address. The problem is that Sofia doesn't seem to allow me to change the destination for the SIP message; it always uses the contact it got when receiving the INVITE. Here's what I've tried:

*

*Enforcing a hardcoded value for SIPTAG_TO:
nua_bye(op->op_handle,
    SIPTAG_TO(sip_to_make(ssc->ssc_home, "sip:alice@54.15.123.11")),
    TAG_END());
The result for this was that the To header was updated with external ip but the SIP message was still destined to the internal proxy ip

*Enforcing a a hardcoded value to NUTAG_URL:
sip_to_t * to = sip_to_make(ssc->ssc_home, "sip:alice@54.15.123.11");
ua_bye(op->op_handle,
   NUTAG_URL(to->a_url),
   TAG_END());
This had no effect.

*Enforcing hardcoded value for SIPTAG_REQUEST_STR:
nua_bye(op->op_handle,
  SIPTAG_REQUEST_STR("BYE sip:alice@54.15.123.11 SIP/2.0"),
  TAG_END());
This had no effect.

*Did the same but through the transaction handle:
nua_set_hparams(op->op_handle,SIPTAG_REQUEST_STR("BYE sip:alice@54.15.123.11 SIP/2.0"), TAG_NULL());
nua_bye(op->op_handle, TAG_END());
Again no effect
Then I thought of going a little earlier when the incoming INVITE arrived from the proxy and maybe alter the contact, since this is where the subsequent BYE is sent, but again no luck: trying to update it through nua_set_hparams had no effect same for the global params with nua_set_params.
Seems that what I want to do is very simple (and necessary given the NAT configurations out there) but yet it's as if Sofia specifically disallows it (if you check the nua_bye docs there aren't any relevant TAGS documented).
I also thought of using one of Sofia's lower level APIs such as NTA (instead NUA) but it seems very hard to mix NUA with any of the lower level APIs.
Any ideas are more than welcome
Best regards,
Antonis

A: A BYE is an in-dialog request, and so it should follow the Route headers, if they are present.  I'm only vaguely familiar with Sofia, but if you added the IP:port the INVITE was actually received from to the routeset on your side and added it to the list of Route headers when you send future in-dialog requests, Sofia should route by the Route headers first, then the RURI (which is usually derived from the Contact of the other side).


text:
Q: Profound Calculus Theorems list Is there a website or a book with a calculus theorems list?
Or what are the ways remembering calculus theorems list?

A: http://www.math.csi.cuny.edu/~ikofman/calculus_formulas.pdf
or you could try Wikipedia.
http://en.wikipedia.org/wiki/List_of_calculus_topics
http://en.wikipedia.org/wiki/Category:Theorems_in_calculus

A: Try ProofWiki, which has a Calculus section.


text:
Q: Is there a way to use LINQ to change the 'checked' radio button in a radio button list? I have a repeater control that houses several RadioButtonLists with various RadioButtons in each list. When my page loads I have several different values. For the sake of clarity let's say I have values "1", "2", and "3". I want to have whichever radio buttons in all of the radiobuttonlists that contain that value to be pre-selected. I already have the RadioButtonLists I want, I just don't know how to access it further.
Is there a way I can do this in LINQ? Something like find the first or default radio button in the radiobuttonlist and checked = true?

A: I was actually over complicating it. All you need to do is change the list.SelectedValue equal to whatever values you already have.

A: I'm not exactly sure where linq comes into it but you can set the RadioButtonList.SelectedValue property either declaratively or at runtime in the code behind file. This page on MSDN should point you in the right direction:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.selectedvalue.aspx
Alternatively post your ASPX and ASPX.CS code and I'd be happy to be a bit more specific.


text:
Q: using  element from javascript Is there any JS library designed for working with canvas elements?
I don't really care about IE compatibility.
I need to create objects(complex drawings with text) , draw lines between them, linear, bezier with different strokes, and attach event handlers to them(i need mouseOver and click).
Anyone has any experience with a library that has built-in support for this?

EDIT:
http://raphaeljs.com/ seems to have these features

A: Canvas doesnt support javascript, but SVG does. You could use jQuery to attach events etc to elements, just like other Dom elements.

A: CAKE fulfills some of your requirements:
http://glimr.rubyforge.org/cake/canvas.html#KeyboardTest
It's been abandoned by its author, though, so it's doubtful that the areas its lacking in will be improved any time soon.

A: Well the Mozilla's API is quite good for working with canvas
https://developer.mozilla.org/en/drawing_graphics_with_canvas
What's lacking? What would you like to see in a canvas library? - it might be a good project to be done on sourceforge or perhaps YUI or jquery can include it if you write to them about it.

A: Maybe Processing.js is what you look for...


text:
Q: http post using tcpclient in c# not working Hi i am trying to post to login page using tcpclient class . but it says 302 error. same thing i can do using webclient. please suggest where i am missing something.  i have already achieved using webclient class. but i have asked to do at lower level. please suggest.
i have tried following
 string sPost =  "POST  http://www.udupikrishnarestaurant.com/ HTTP/1.1\r\n"  +

 "Host: www.udupikrishnarestaurant.com\r\n" +

 "Connection: keep-alive\r\n" +

 "Content-Length: 632\r\n" +

 "Cache-Control: max-age=0\r\n" +

 "Origin: http://www.udupikrishnarestaurant.com \r\n" +

"Upgrade-Insecure-Requests: 1\r\n" +

"User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36 \r\n" +

"Content-Type: application/x-www-form-urlencoded\r\n" +

"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 \r\n" +

"Referer: http://www.udupikrishnarestaurant.com/ \r\n" +

"Accept-Encoding: gzip, deflate, br\r\n" +

"Accept-Language: en-US,en;q=0.8\r\n" +

"\r\n" +

"__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=/wEPDwUKLTM0ODY4NTA5Mg9kFgRmD2QWAgIBDxYCHgdWaXNpYmxlaGQCAQ8WAh4EVGV4dAUOMTgyLjY5LjEwOC4yMTFkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBQlidG5TdWJtaXQFCWJ0bkZvcmdvdCvBSicNzlFc1g4UTZeO96HhGK8T&__VIEWSTATEGENERATOR=CA0B0334&__EVENTVALIDATION=/wEdAAr0HIr+WBkxh8yUckvqwLD4LqRynaTFa/5Hs7sApa3/2aRDGrH080vTDzQFiILKSswLyPw09K59GBb2rr9Ouzg352npSE7sRexHKIcGFqd4MCl0Pj8zqX34hAcL3lPJ6TZjemWCTRgEB59HPczIGVNwdjb4xzpKucCqKjegIpvFhjzmltaUM7aEAN+g9cP/m13MQ92x/wmKgUDwu+2MEZnSA5KkNGEzQJYQmFWkBWmYqAdLpnM=&ddlFloor=2&txtUserName=test&txtPassword=1234&btnSubmit.x=15&btnSubmit.y=3";

byte[] buf = new byte[1024];
  string header = sPost;

  var client = new TcpClient();
  client.Connect("182.50.132.48", 80);

  // send request

  var stream = client.GetStream();
  var streamReader = new StreamReader(stream);
  var streamWriter = new StreamWriter(stream);

  streamWriter.Write(header);
  streamWriter.Flush();
  stream.Flush();

  // get response

  var response1 = streamReader.ReadLine();

A: 302 is not an error. It is a request for redirection - the form tells you "go there instead", most likely as a result of your login attempt. WebClient handles the redirection, your client doesn't.
There's a lot of HTTP to implement. Unless this is purely an excercise, don't try to write your own HTTP client. Redirection is just the top of the iceberg.


text:
Q: Spring Application throwing error and WAR not building I would like to deploy the package onto tomcat so tried extending it with SpringBootServletInitializer and the following error occurred but on normal deploy without any SpringBootServletInitializer there seems to be no error.
What am i doing wrong?
My build.gradle file looks like this
plugins {
    id 'java'
    id 'war'
}

group 'com.nithin.ms'
version '0.5.0'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    mavenCentral()
}

configurations {
    providedRuntime
}

dependencies {
    compile group: 'commons-io', name: 'commons-io', version: '2.4'
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.4.RELEASE'
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:2.0.4.RELEASE'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

The error is
org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [in.nithin.Application]; nested exception is java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.boot.web.servlet.support.SpringBootServletInitializer
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:184) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:316) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:233) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:271) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:91) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:694) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at in.nithin.Application.main(Application.java:28) [classes/:na]
Caused by: java.lang.IllegalStateException: Failed to introspect annotated methods on class org.springframework.boot.web.servlet.support.SpringBootServletInitializer
    at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:169) ~[spring-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.retrieveBeanMethodMetadata(ConfigurationClassParser.java:393) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:318) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:245) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:202) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:170) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    ... 12 common frames omitted
Caused by: java.lang.NoClassDefFoundError: javax/servlet/ServletContext
    at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_181]
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_181]
    at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_181]
    at org.springframework.core.type.StandardAnnotationMetadata.getAnnotatedMethods(StandardAnnotationMetadata.java:158) ~[spring-core-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    ... 17 common frames omitted
Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContext
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_181]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_181]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349) ~[na:1.8.0_181]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_181]
    ... 21 common frames omitted

Process finished with exit code 1

My Application.java file looks like this
package in.nithin;

// Our packages
import in.nithin.property.FileStorageProperties;

// Required packages
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;

// Application starts here
@SpringBootApplication
@ComponentScan
@EnableConfigurationProperties({
        FileStorageProperties.class
})
public class Application  extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

EDIT-1
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.4.RELEASE)

2018-09-07 12:03:18.285  INFO 10917 --- [           main] in.nithin.Application                  : Starting Application on XPS-L401X with PID 10917 (/home/signzy/code/java/main/fileupload/out/production/classes started by signzy in /home/signzy/code/java/main/fileupload)
2018-09-07 12:03:18.324  INFO 10917 --- [           main] in.nithin.Application                  : No active profile set, falling back to default profiles: default
2018-09-07 12:03:18.639  INFO 10917 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2145433b: startup date [Fri Sep 07 12:03:18 IST 2018]; root of context hierarchy
2018-09-07 12:03:21.313  WARN 10917 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
2018-09-07 12:03:21.350  INFO 10917 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-09-07 12:03:21.370 ERROR 10917 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:155) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.0.8.RELEASE.jar:5.0.8.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:762) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:398) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:330) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1258) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at in.nithin.Application.main(Application.java:28) [classes/:na]
Caused by: org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.getWebServerFactory(ServletWebServerApplicationContext.java:204) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:178) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:152) ~[spring-boot-2.0.4.RELEASE.jar:2.0.4.RELEASE]
    ... 8 common frames omitted

Process finished with exit code 1

A: Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletContext means that the jar `javax.servlet.jar is missing in your classpath
// https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
compile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'

A: I had the same problem on spring-boot web app deployment with Tomcat. I resolved the issue by adding servlet-api dependency with Provided scope.
@Grab(group='javax.servlet', module='javax.servlet-api', version='3.1.0', scope='provided')
after deployment of your app. In WEB-INF you will find folder called lib-provided which
 consists other jars along with the servlet-api one.
Suggestions : Provided scope helps you to retain your deployment capability for embedded tomcat.


text:
Q: How can i upload to ftp multiple files and display it on multiple progressBars? I mean that if i give a List for exmaple of 30 files to upload it will open 30 slots of uploading will upload all the files in real time so i will see 30 progressBars and it will upload all the files paralel.
In form1 designer i have already one progressBar.
This is the class code for the ftp upload:
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Text;

namespace FTP_ProgressBar
{
    /// <summary>
    /// The FtpProgress class is derived from background worker, so it has the built-in functions of
    /// run, report progress, and completed.
    /// It only does upload, as a demonstration of how to transfer a file by FTP and report the progress.
    /// </summary>
    public partial class FtpProgress : BackgroundWorker
    {
        public FtpProgress()
        {
            InitializeComponent();
        }

        public FtpProgress(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
        }

        private void FtpProgress_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = sender as BackgroundWorker;
            FtpSettings f = e.Argument as FtpSettings;
            // set up the host string to request.  this includes the target folder and the target file name (based on the source filename)
            string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(f.SourceFile));
            if(!UploadPath.ToLower().StartsWith("ftp://"))
                UploadPath = "ftp://" + UploadPath;
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
            request.UseBinary = true;
            request.UsePassive = f.Passive;
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(f.Username, f.Password);

            // Copy the contents of the file to the request stream.
            long FileSize = new FileInfo(f.SourceFile).Length;
            string FileSizeDescription = GetFileSize(FileSize); // e.g. "2.4 Gb" instead of 240000000000000 bytes etc...
            int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
            long SentBytes = 0;
            byte[] Buffer = new byte[ChunkSize];    // this buffer stores each chunk, for sending to the web service via MTOM
            using(Stream requestStream = request.GetRequestStream())
            {
                using(FileStream fs = File.Open(f.SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    int BytesRead = fs.Read(Buffer, 0, ChunkSize);  // read the first chunk in the buffer
                    // send the chunks to the web service one by one, until FileStream.Read() returns 0, meaning the entire file has been read.
                    while(BytesRead > 0)
                    {
                        try
                        {
                            if(bw.CancellationPending)
                                return;

                            // send this chunk to the server.  it is sent as a byte[] parameter, but the client and server have been configured to encode byte[] using MTOM.
                            requestStream.Write(Buffer, 0, BytesRead);

                            // sentBytes is only updated AFTER a successful send of the bytes. so it would be possible to build in 'retry' code, to resume the upload from the current SentBytes position if AppendChunk fails.
                            SentBytes += BytesRead;

                            // update the user interface
                            string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
                            bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
                        }
                        catch(Exception ex)
                        {
                            Debug.WriteLine("Exception: " + ex.ToString());
                            if(NumRetries++ < MaxRetries)
                            {
                                // rewind the filestream and keep trying
                                fs.Position -= BytesRead;
                            }
                            else
                            {
                                throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString()));
                            }
                        }
                        BytesRead = fs.Read(Buffer, 0, ChunkSize);  // read the next chunk (if it exists) into the buffer.  the while loop will terminate if there is nothing left to read
                    }
                }
            }
            using(FtpWebResponse response = (FtpWebResponse)request.GetResponse())
                System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
        }

        /// <summary>
        /// Returns a description of a number of bytes, in appropriate units.
        /// e.g.
        ///     passing in 1024 will return a string "1 Kb"
        ///     passing in 1230000 will return "1.23 Mb"
        /// Megabytes and Gigabytes are formatted to 2 decimal places.
        /// Kilobytes are rounded to whole numbers.
        /// If the rounding results in 0 Kb, "1 Kb" is returned, because Windows behaves like this also.
        /// </summary>
        public static string GetFileSize(long numBytes)
        {
            string fileSize = "";

            if(numBytes > 1073741824)
                fileSize = String.Format("{0:0.00} Gb", (double)numBytes / 1073741824);
            else if(numBytes > 1048576)
                fileSize = String.Format("{0:0.00} Mb", (double)numBytes / 1048576);
            else
                fileSize = String.Format("{0:0} Kb", (double)numBytes / 1024);

            if(fileSize == "0 Kb")
                fileSize = "1 Kb";  // min.
            return fileSize;
        }
    }

    public class FtpSettings
    {
        public string Host, Username, Password, TargetFolder, SourceFile;
        public bool Passive;
        public int Port = 21;
    }
}

And in form1: Upload button click event:
private void btnUpload_Click(object sender, EventArgs e)
        {
            // the upload button is also used as a cancel button, depending on the state of the FtpProgress thread
            if(this.ftpProgress1.IsBusy)
            {
                this.ftpProgress1.CancelAsync();
                this.btnUpload.Text = "Upload";
            }
            else
            {
                // create a new FtpSettings class to store all the paramaters for the FtpProgress thread
                FtpSettings f = new FtpSettings();
                f.Host = this.txtHost.Text;
                f.Username = this.txtUsername.Text;
                f.Password = this.txtPassword.Text;
                f.TargetFolder = this.txtDir.Text;
                f.SourceFile = this.txtUploadFile.Text;
                f.Passive = this.chkPassive.Checked;
                try
                {
                    f.Port = Int32.Parse(this.txtPort.Text);
                }
                catch { }
                this.toolStripProgressBar1.Visible = true;
                this.ftpProgress1.RunWorkerAsync(f);
                this.btnUpload.Text = "Cancel";
            }
        }

Backgorundworker progresschanged:
private void ftpProgress1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            this.toolStripStatusLabel1.Text = e.UserState.ToString();   // the message will be something like: 45 Kb / 102.12 Mb
            this.toolStripProgressBar1.Value = Math.Min(this.toolStripProgressBar1.Maximum, e.ProgressPercentage);
        }

And completed event:
private void ftpProgress1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if(e.Error != null)
                MessageBox.Show(e.Error.ToString(), "FTP error");
            else if(e.Cancelled)
                this.toolStripStatusLabel1.Text = "Upload Cancelled";
            else
                this.toolStripStatusLabel1.Text = "Upload Complete";
            this.btnUpload.Text = "Upload";
            this.toolStripProgressBar1.Visible = false;
        }

There are in form1 designer some textboxes that i enter password user name ftp address and file to upload.
This is the file browser for uploading:
private void btnBrowse_Click(object sender, EventArgs e)
        {
            if(this.openFileDialog1.ShowDialog() != DialogResult.Cancel)
                this.txtUploadFile.Text = this.openFileDialog1.FileName;
        }

Now instead one single file i want to be able to select multiple files and if i selected more then one file then it will upload the number of selected file at once paralel in real time.
If i selected 2 files it will create another new progressBar and will display on the two progressBars the files upload.
If i will select 34 files it will create 34 progressBars and will display on them the uploading progress.

A: When you browse multiple files at a time, the action takes place only once. i.e; all the files selected will reach the location(Server) which you have specified. So, that is the reason you are able to see only one progress bar.
If you need multiple progress bars, you should try placing multiple buttons for selecting each file through each button.


text:
Q: CRUD front end for mySQL in Wordpress I hope I've come to the right place. I want to enrich my Wordpress site with a front end to MySQL database, which I host on the same server as my WP site.
I have actually migrated my (former) MS Access database to MySQL and I do get "table read/write" access to it using wpdatables.
I guess, what I'm looking for is basically a CRUD-interface for MySQL on WP. I'm aware, I could construct that myself with lots of php code etc.
But there must be a way, to use the many form engines (gravity, wp-forms, formidable, ...) and have the nice looking forms display individual table records, allow editing them, and write them back to the MySQL database...
Any suggestions here? I really don't feel like reinventing the wheel.
Best,
Dirk

A: Tom, I appreciate that WP doesn't provide a CRUD type setup ...
I'm just wondering, whether these nice form-plugins that do a brilliant job in displaying and editing MySQL records of their own making within the WP-plugin-database could not do the same thing to a MySQL database on the same server.
Again, I have been toying around with wpdatatables, and this does a good job for ... tables, which are editable and can be based on MySQL queries for that matters. It's also possible to edit individual table rows in a modal pop-up... but these pop-ups provide nowhere close to the display flexibility that, say gravity forms would be able to provide.
Frustrated at something that seems so possible with WP, being based on MySQL itself.
Also, when it's impossible to do it within WP ... what's a CRUD environment then for MySQL? Something that would be emulate both "Continuous forms" and "Single forms" as they were called on (not so) good old Microsoft Access frontend?


text:
Q: Oracle NUMBER data type max limit with & without decimal points I have a number field in the application which passes a numeric value to my Oracle procedure which is of NUMBER datatype. The numeric value can be positive, negative, with or without decimal points.
I need to restrict it from the application so I need to specify the maximum limit without any round-off. Can I please know what will be the limits for positive, negative, with, and without decimals points.

A: It is not really a range that is allowed, but a precision. You can pass any number with up to 38 digits, no matter if or where the decimal separator.
Okay:

+12345678901234567890123456789012345678
-12345678901234567890123456789012345678
+1.2345678901234567890123456789012345678
-1234567890123456789012345678901234567.8

May get slightly mutilated:

+123456789012345678901234567890123456789
-123456789012345678901234567890123456789
+1.23456789012345678901234567890123456789
-1234567890123456789012345678901234567.89

Demo with some longer numbers: https://dbfiddle.uk/?rdbms=oracle_18&fiddle=aa74ef09157dcf86daa76507e868fe49


text:
Q: csympy cmake error: Compiler does not support C++11 constructs sudo apt-get install cmake libgmp-dev
sudo cmake .
sudo make

I attempted to install csympy from gitub using the instructions above.
running install
running build
-- The CXX compiler identification is unknown
CMake Error: your CXX compiler: "CMAKE_CXX_COMPILER-NOTFOUND" was not found.   Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
CMake Error at /usr/share/cmake-2.8/Modules/CMakeCXXInformation.cmake:37 (get_filename_component):
  get_filename_component called with incorrect number of arguments
Call Stack (most recent call first):
  CMakeLists.txt:4 (PROJECT)

CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage
CMake Error: Internal CMake error, TryCompile configure of cmake failed
CMake Error at CMakeLists.txt:38 (message):
  Compiler does not support C++11 constructs

  CXX11 ERROR LOG :

-- Configuring incomplete, errors occurred!
See also "/home/user/Downloads/csympy-master/CMakeFiles/CMakeOutput.log".
See also "/home/user/Downloads/csympy-master/CMakeFiles/CMakeError.log".
Traceback (most recent call last):
  File "setup.py", line 118, in <module>
    'install' : InstallWithCmake,
  File "/usr/lib/python2.7/distutils/core.py", line 151, in setup
    dist.run_commands()
  File "/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "setup.py", line 99, in run
    _install.run(self)
  File "/usr/lib/python2.7/distutils/command/install.py", line 601, in run
    self.run_command('build')
  File "/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command
    self.distribution.run_command(command)
  File "/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
    cmd_obj.run()
  File "setup.py", line 69, in run
    cmake_build()
  File "setup.py", line 39, in cmake_build
    raise EnvironmentError("error calling cmake")
EnvironmentError: error calling cmake

However I received the above error during cmake. I checked synaptic that I have gcc-4.8 installed.
cmake -std=c++0x .
cmake -std=c++11 .

I forced cmake to use the following compilers above, however I received error messages stating that the specified source directories do not exist. What am I missing to compile the csympy cmake?

A: You are missing a C++ compiler. To install g++
sudo apt-get install g++

After that you need to clean the repo git clean -dfx and run cmake . or python setup.py install again


text:
Q: How to set up authors in LNCS template? I would like to setup the authors and emails in a LNCS paper, but I dont find what is the correct way to do this. I tried this:
\author{FirstAuthor LastName, Second Author LastName}

The problem is that I tried different ways to set the emails and the institute but the document crashes out. Any idea of how to correctly set this parameters in orther to get something like this:
(*)
FirstAuthor LastName, Second Author LastName
    email@email.com      email_2@email.com
                 Institution

Update
I tried this:
\author{FirstAuthor LastName \inst{1} \and SecondAuthor LastName \inst{2}}

%If there are too many authors, use \authorrunning
%\authorrunning{First Author et al.}

\institute{
Insitute 1\\
\email{author1@email.com}\and
Insitute 2\\
\email{author_2@email.com}
}

But I dont get (*) style.
Thanks in advance guys!

A: According to authors instructions for Lecture Notes in Computer Science, you must use \email{<email address>} within \institute{} and therefore you should not obtain the style that you are looking for(*).
Compile  llncs.doc (in spite of the extension, is really a LaTeX file) with pfdlatex to see the instructions for authors.
This is a MWE extracted from llncs.dem (also a LaTeX file):

\documentclass{llncs}
\begin{document}
\title{Hamiltonian Mechanics unter besonderer Ber\"ucksichtigung derh\"ohreren Lehranstalten}
\author{%
Ivar Ekeland\inst{1}  \and
Roger Temam\inst{2}
Jeffrey Dean \and
David Grove \and
Craig Chambers \and
Kim~B.~Bruce \and
Elsa Bertino
}%
\institute{
Princeton University, Princeton NJ 08544, USA,\\
\email{I.Ekeland@princeton.edu},\\
WWW home page:
\texttt{http://users/\homedir iekeland/web/welcome.html}
\and
Universit\'{e} de Paris-Sud,
Laboratoire d'Analyse Num\'{e}rique, B\^{a}timent 425,\\
F-91405 Orsay Cedex, France}
\maketitle
\end{document}

(*) If you want that style for personal use, then is better start with the standard class article:

\documentclass{article}
\date{}
\def\email#1{\texttt{#1}}

\begin{document}
\title{Hamiltonian ...}
\author{%
Ivar Ekeland\\ \email{I.Ekeland@princeton.edu}  \and
Elsa Bertino\\ \email{E.Bertino@princeton.edu}
}%

\maketitle
\end{document}


text:
Q: npm install returns 304 and 404 errors instead of installing packages When I run npm install I see a lot of this:
npm http fetch GET 304 http://registry.npmjs.org/is-arrayish 60ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/spdx-license-ids 67ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/spdx-exceptions 72ms (from cache)
npm http fetch GET 200 http://registry.npmjs.org/arr-union 11ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/is-buffer 68ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/is-data-descriptor 85ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/is-accessor-descriptor 90ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/is-accessor-descriptor 72ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/is-data-descriptor 66ms (from cache)
npm http fetch GET 200 http://registry.npmjs.org/has-value 6ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/p-try 92ms (from cache)
npm http fetch GET 200 http://registry.npmjs.org/set-value 12ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/posix-character-classes 68ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/static-extend 88ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/for-in 89ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/get-value 72ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/collection-visit 88ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/to-object-path 64ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/union-value 85ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/os-homedir 81ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/unset-value 87ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/delegates 76ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/aproba 82ms (from cache)
npm http fetch GET 200 http://registry.npmjs.org/map-visit 8ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/has-unicode 76ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/wide-align 73ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/capture-stack-trace 69ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/prepend-http 83ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/has-values 81ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/object-copy 61ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/object-visit 53ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/code-point-at 52ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/pseudomap 84ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/has-values 53ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/copy-descriptor 42ms (from cache)
npm http fetch GET 304 http://registry.npmjs.org/number-is-nan 76ms (from cache)
npm http fetch GET 404 http://registry.npmjs.org/@apollographql%2fapollo-tools 726ms
npm timing stage:rollbackFailedOptional Completed in 0ms
npm timing stage:runTopLevelLifecycles Completed in 6589ms
npm ERR! code E404
npm ERR! 404 Not Found: @apollographql/apollo-tools@^0.4.0
npm timing npm Completed in 6995ms

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/paulcarron/.npm/_logs/2019-10-01T19_18_38_895Z-debug.log

I'm not sure why my packages won't install. I have a vague recollection of me updating the npm url some time back but the url here looks OK. Any suggestions?

A: Got to the bottom of it. I had deleted the contents of my application folder and copied a fresh set of the program files into it. What I hadn't noticed was when I did the delete my terminal followed the path of my deleted files so was essentially pointing to a location in the trash can which seems to have caused issues with npm install.
Changing to the correct directory and running npm install again resolved the issue.

A: This command helped me:
npm cache clean --force


text:
Q: power BI cannot find function is() in a R script Dear all
I am running the following R script in power BI, with the purpose of getting "data2016" and "df" as output data (both are data frames). With sapply() I am sourcing the function inputFreq() which is a home made function to compute the frequency of an entry in a vector. The function uses is() inside (among other things, see detail below)
setwd("C:/Users/Home/Documents/folder")
data2016 <- read.csv("rawData2016.csv", header = TRUE)
sapply(list.files(pattern="[.]r$", full.names=TRUE), FUN=source)
df <- head(as.data.frame(inputFreq(data2016$var1[1:100])))

Message Error
After doing Get Data > Other > r script and pasting (all in power BI enviroment), I get the following error

Details: "ADO.NET: R script error.
  Error in inputFreq(data2016$var1[1:100]) :
    could not find function "is"
  Calls: head -> as.data.frame -> inputFreq
  Execution halted

The function called, inputFreq() has the is() function inside. For info, here´s the function:
inputFreq <- function(x){

  if( is(x, "factor") == TRUE ) {
    x <- as.character(x)
  } else {
    x
  }

  a <- sort(x)
  n <- length(a)
  k <- numeric(n)
  f <- numeric(n)

  # vector k: algoritmo para computar la frecuencia maxima en vector 'a'

  k[1] <- 1
  for (i in 2:n){
    if ( a[i]==a[i-1] ){
      k[i] <- 1 + k[i-1]
    }  else {
      k[i] <- 1
    }

  }

  # vector N: algoritmo para imputar la frecuencia maxima de cada a(i)

  f[n] <- k[n]
  for (j in (n-1):1){
    if ( k[j] < k[j+1] ){
      f[j] <- f[j+1]
    }  else {
      f[j] <- k[j]
    }
  }

  return( cbind( "x" = x, "fr.x" = f[match(x,sort(x))] ) )
}

More info
The function has already performed well in the rstudio environment, the problems seems to be when power BI tries to read the is() function from methods-R.
Any suggestion? many thanks!!

A: It seems that PowerBI uses Rscript.exe, the commandline version of R used to run scripts without a GUI-based front end. Rscript doesn't load the methods package, which is where the is function is defined.
To fix this, do one of the following:

*

*Add a line library(methods) to the top of your script.

*Use inherits instead of is. This does almost exactly the same thing, but is defined in the base package and hence will always be available.


text:
Q: How do I expand all class="..." attributes to style="..."? I'm parsing forum threads with Nokogiri and putting them into a RSS feed. The forum itself doesn't have RSS or any other kind of news feeds.
The problem I've encountered is that elements are styled with CSS classes and via selectors in forums style file included in the page. I can't include it into a news feed, so I want to replace all class="..." attributes with style="<style properties from classes here>".
Any ideas how do I do that? Maybe there are some gems able to parse CSS and update Nokogiri parser?

A: You need to show a sample of what you are parsing, plus a sample of the code you've written.
In addition, RSS doesn't support styles so rather than replace class="..." with style="" just remove the class info. You can embed HTML in RSS items, but IMO that results in lousy looking feeds and can lead to problems farther down the road if someone else wants to reuse the data. Instead I'd recommend sanitizing the HTML or even stripping all tags.


text:
Q: How to replace all spaces in .txt file using SED in Cygwin I have a huge .txt file that I want all spaces, line-breaks, indentations etc removed. It should literally be one long string.
I tried

sed -i 's/\ //g' test.txt

but nothing happens

A: sed -n "s/[[:blank:]]//g;H
$ {x;s/\n//g;p;}"

The H than $ are needed if you want to include New line due to fact that sed treat by default line by line (so no new line inside a line). The -n  and p  are needed to avoid double display with use of H

A: Seems to work ok for me:
[~/Desktop]
==> cat test.txt
the quick brown fox

[~/Desktop]
==> sed -i "s/\ //g" test.txt

[~/Desktop]
==> cat test.txt
thequickbrownfox

A: Sometimes using " " directly is hard and especially when you use double quotes (which involves that bash will interpret the string before passing it to sed).
sed -i -e 's/\s//g' file.txt

... should work (it works for me). "\s" means all whitespace characters, and with single quotes '', for bash not to interpret it before you passing it to sed.

A: While you use cygwin I think your OS is windows, then you don't need to use bash to implement your goal. Just open your txt file with the text editor, and replace the while space with nothing, then all of the whit space in you txt file will be removed.
This method can meet almost all kinds of removal. And also can apply in excel or word and so on.
Good luck!


text:
Q: Looking for C# algorithm to grab recurring items from a collection of DateTime objects (factoring in both date and time)? I have a collection of DateTime objects.  I need to "parse" out subcollections from this original list to grab related items based on recurrence.  So I need to take this single original collection:
var collectionOfDateTime = GetDateTimeCollection();

and translate that into a list of DateTime collections where each collection includes a set of dates from the first list that following a specific recurrence pattern.
In my examples below I am not including time but in the real requirement, these items have both Date and Time elements to them.  So for example the Dates need to be 7 days apart but also be the same time (one time on Feb 3rd at 11AM doesn't match feb 10th at 3PM but it does match with Feb 10th at 11AM)
For example, lets say my recurrence pattern is "Weekly" (in other cases it might be "Monthly")  and my date collection looks like this:
 var date1 = DateTime.Today.AddHours(8);
 var date2 = DateTime.Today.AddWeeks(1).AddHours(8);
 var date3 = DateTime.Today.AddDays(3);
 var date4 = DateTime.Today.AddWeeks(8).AddHours(6);

 var collectionOfDateTime = new List<DateTime>() { date1, date2, date3, date4 };

I would want a function (lets call it StripOutSubCollections()) to pass in the collectionOfDateTime and the fact that its "Weekly" and return one collection that includes date1, date2 (as they are all part of the same weekly slot).  Note date3 doesn't not fit and date4 also doesn't fit because the hours do not match with the others
For another example to help prove out the requirement, if the input to the original collection was this:
 var date1 = DateTime.Today;
 var date2 = DateTime.Today.AddWeeks(1);
 var date3 = DateTime.Today.AddDays(3);
 var date4 = DateTime.Today.AddWeeks(8);
 var date5 = DateTime.Today.AddDays(3).AddWeeks(2);

 var collectionOfDateTime = new List<DateTime>() { date1, date2, date3, date4, date5 };

I would want this function to return 2 lists  (one list with date1, date2, and date4) and another list with date3 and date5.
Let me know if I need more examples to articulate the requirements? Note that is possible that one of the dates might fall into multiple output lists which is fine.
I can convert weekly into the number 7 and do a loop through each items starting with first item to the end, then the second item to the end, then the third item, etc. but wanted to see if there was a more elegant way

A: If I understand your question properly, you are trying to "chunk" the DateTime values by Day of the Week?
If so, something like this should do it:
var byDayOfWeek = collectionOfDateTime.GroupBy(dt => dt.DayOfWeek);
// Optionally convert to a dictionary by day of week
var asDict = byDayOfWeek.ToDictionary(grp => grp.Key, grp => grp.ToList());

foreach(var kvp in asDict)
{
    Console.WriteLine("Day:" + kvp.Key);
    foreach (var value in kvp.Value)
    {
        Console.WriteLine(value);
    }
}

Output:
Day:Thursday
2/21/2013 12:00:00 AM
2/28/2013 12:00:00 AM
4/18/2013 12:00:00 AM
Day:Sunday
2/24/2013 12:00:00 AM

EDIT: For multiple "grouping by" rules:
public enum ChunkType
{
    Weekly,
    Monthly,
    Yearly
}

public IEnumerable<IEnumerable<DateTime>> ChunkDates(IEnumerable<DateTime> collection, ChunkType chunkBy)
{
    switch(chunkBy)
    {
        case ChunkType.Weekly:
            // roughly equals by day of week
            return collection.GroupBy(dt => dt.DayOfWeek).Select(grp => grp.ToList());
        case ChunkType.Monthly:
            // Trickier - assume by ordinal day of month?
            return collection.GroupBy(dt => dt.Day).Select(grp => grp.ToList());
        case ChunkType.Yearly:
            // Trickier - assume by ordinal day of year?
            return collection.GroupBy(dt => dt.DayOfYear).Select(grp => grp.ToList());
    }
    return new[]{ collection };
}

var date1 = DateTime.Today;
var date2 = DateTime.Today.AddDays(7);
var date3 = DateTime.Today.AddDays(3);
var date4 = DateTime.Today.AddDays(8*7);

var collectionOfDateTime = new List<DateTime>() { date1, date2, date3, date4};

foreach(var type in new [] { ChunkType.Weekly, ChunkType.Monthly, ChunkType.Yearly })
{
    Console.WriteLine("Now grouping by:" + type);
    var grouped = ChunkDates(collectionOfDateTime, type);
    foreach(var groupOfDates in grouped)
    {
        Console.WriteLine("New group!");
        foreach (var value in groupOfDates)
        {
            Console.WriteLine(value);
        }
    }
}

Output:
Now grouping by:Weekly
New group!
2/21/2013 12:00:00 AM
2/28/2013 12:00:00 AM
4/18/2013 12:00:00 AM
New group!
2/24/2013 12:00:00 AM

Now grouping by:Monthly
New group!
2/21/2013 12:00:00 AM
New group!
2/28/2013 12:00:00 AM
New group!
2/24/2013 12:00:00 AM
New group!
4/18/2013 12:00:00 AM

Now grouping by:Yearly
New group!
2/21/2013 12:00:00 AM
New group!
2/28/2013 12:00:00 AM
New group!
2/24/2013 12:00:00 AM
New group!
4/18/2013 12:00:00 AM

A: Use LINQ
Try (something like, this is LINQesque pseudo-code)
var datecollections = from d in collectionOfDateTime
          group d by d.DayOfWeek into g
          select new { Day = g.Key, Date = g };

Give that a go and see where it gets you...

A: var dict = new Dictionary<int, List<DateTime>>();
foreach (var date in collectionOfDateTime)
{
  if (dict.Contains(date.DayOfWeek))
  {
     dict[date.DayOfWeek].Add(date);
  }
  else
  {
     dict.Add(date.DayOfWeek, new List<Date> { date });
  }
}


text:
Q: How can I map a specific keyboard key to be SysRq? I am using Parabola GNU/Linux (Arch variant) on a MacBook Pro laptop. I would like to configure/enable the SysRq key, since I am experiencing fairly frequent system freezes, which are forcing me currently to have to hard-reboot the system. I have checked /proc/config.gz and it seems the SysRq key is enabled in the kernel config:
CONFIG_MAGIC_SYSRQ=y

So, my questions are as follows:
a) How can I verify what (if any) key is currently mapped to SysRq?
b) I would like to remap the Apple 'Command' key to SysRq (since I don't believe it is currently being used). How can I do that?
Edit:
Referring to the answer given here, the contents of `/proc/sys/kernel/sysrq' is as follows:
$ cat /proc/sys/kernel/sysrq
0

this seems to indicate that the SysRq key is disabled (despite apparently being enabled in the kernel config) - why is that? (note that I don't believe that linked answer addresses part a) of my question).


text:
Q: Update a value in db with the help of the id I have this script in codeigniter, and I would like to update the isMultiple column in db based on the question id, how could I do this the simplest?
var html = '

\n' +
                '
\n' +
                '    <input name="question[]" type="text" id="input-name" class="form-control form-control-sm form-control-alternative" placeholder="">\n' +
                '
\n' +
                '
\n' +
                '
\n' +
                '
\n' +
                '
Remove Question
\n' +
                '
\n' + '<input type="checkbox" class="form-check-input" name="checkBoxQuestion[]" value="1">Checked'
                '

';
            $('.append_here').append(html);

function editSpecialization($data){
        $dataInsert = $data;
        $inserted = $data['id'];
        if(@$data['question']) {
            unset($dataInsert['question']);
            unset($dataInsert['id']);
            unset($dataInsert['isMultiple']);
        }
        $checked = (isset($_POST['checkBoxQuestion']))? 1 : 0;
        $this->db->where('id',$inserted);
        $this->db->update('specializations',$dataInsert);
        //if($checked) $this->db->update('isMultiple', 1);
        $this->deleteQuestions($inserted);

        $insert['specialization_id'] = $inserted;
        $insert['sort_nr'] = 0;
        if(@$data['question']){
            foreach($data['question'] as $question){
                $insert['question'] = $question;
                if($checked) $insert['isMultiple'] = 1;
                $this->db->where('id', $inserted);
                $this->db->update('isMultiple', $insert);
                $this->db->insert('questions',$insert);
            }
        }
    }

For now, that check inserts me in all the questions