text:
Q: react-window and detecting changes in size of list items So I have been trying to figure out a solution for big lists in react. and I almost have the perfect solution - but I can't seem to figure out how to get this one detail to work.
I have a list of cards that I want to render quickly - I'm using the react-window package
import{VariableSizeList as List} from 'react-window';

I have a component called MaterialCard, and a component that contains lists of MaterialCards:
On the MaterialCard if you click on an inspect button - it opens up the innards of the card revealing a form input section.
const [cardOpen, setCardOpen] = useState(false);
const cardInnards = //a bunch of jsx.

//in the return
<button className="btn-inspect" onClick={()=>setCardOpen(!cardOpen)}>inspect/edit</button>
{cardOpen?cardInnards:

}

In the multi-list component container - I have this code.
const materialCardsNew = materialsNew.map((x,i)=><MaterialCard props={x} key ={`${i}matsnew`} />);
//react-window function to make a row:
const Row = array=> ({ index }) => array[index] //is MaterialCard

//in the return
<List
  height={755}
  itemCount={materialCardsNew.length-1}
  itemSize={()=>130} // this is where I'm having trouble.
  width={634}
>
{Row(materialCardsNew)}
</List>

Currently the itemSize is what I'm trying to fix...
What happens currently is the item has a fixed size area it appears in - and (thanks to z-index) the innards appear over other items in the list.
What I want to happen is the item size of the MaterialCard that is open - to be of a larger size: such that it doesn't cover other cards - I want it to expand and I don't want it to cover other cards at all.
My trouble is I don't know how to read the component's internal state from the top - how do I determine in the list container component which card is open. I understand I require a function for this... but: well...
the pseudocode I've come up with is this: this of course does not work - but it is more or less what I want to do.

//resize function
const getHeight = (arr)=>(index)=>arr[index].state.cardOpen?500:100; //bigger size if the card is open

//jsx
itemSize={getHeight(materialCardsNew)}

//I've also tried arr[index].style.height,
//and searched through the arr[index] properties in the console to see
//if there was anything I could use... no luck.

My first ideas are bunk... and I'm not really sure how to approach this... I'm pretty sure I shouldn't need a massive additional array for each array of material cards (there are a few categories) to keep track of which cards are open... but I can't seem to find the correct way of going about this.
How do I accomplish this?

A: For this issue:

My trouble is I don't know how to read the component's internal state
from the top

Lift state up. So in the containing component, you can use a hook like in the top level component:
const [activeCard, setActiveCard] = useState()

And in the card, pass in the function:
<Card setActiveCard={setActiveCard} key={someKey} {...otherProps}/>

And, in the implementation of the card, you can have something like:
useEffect(() => setActiveCard(key), [key])

And the top level component will have the 'active' card information.
Not sure I completely was clear on the issue, but that is one mechanism for sending child information to the parent.
And, if I am understanding the issue, you could have some logic in the child component to check if the active card is equal to the card:
<Card setActiveCard={setActiveCard} activeCard={activeCard} key={someKey} {...otherProps} />

useEffect(() => activeCard === key ? setComponentSize(activeSize) : setComponentSize(defaultSize), [{dependency array}])

Of course, the setComponentSize would be in the top level component, and passed in a similar fashion to setting the card index in the top level. And if everything is set in the containing (parent component), you could just check the index vs the activeCard.
Finally, just make sure however you are checking for the active card, you cleanup and call setActiveCard(-1), or whatever the default parameter you might want to use when the active card's state changes.


text:
Q: QList proper way of using it I want to poppulate a QList with QLabel Objects, so i've created a List of QLabel Objects.
QLabel *myLabel;
QList<QLabel> *thumbNails;

but as QList awaits a const QLabel &, how can i append to the Qlist in the right ways, should i use a const_cast ?

A: Most likely you put your * in a wrong place, which made thumbNails a pointer to a QList.
You should store pointers to QLabel inside your list. Try this: QList<QLabel*> thumbNails;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error in ggmap, "must be an array" and "HTTP 400 bad request" I'm trying to call a map from google maps using ggmap. Example code:
get_googlemap(center = c(lon = -56.67, lat = 51.47), zoom = 8, size = c(640, 640), scale = 2,
                   format = "png8", maptype = "satellite")

However, this returns the following error:
Source : https://maps.googleapis.com/maps/api/staticmap?center=24.8,-81.7&zoom=8&size=640x640&scale=4&maptype=satellite&key=(removed key for posting)
Error in aperm.default(map, c(2, 1, 3)) :
  invalid first argument, must be an array
In addition: Warning message:
In get_googlemap(center = c(lon = -81.7, lat = 24.8), zoom = 8,  :
  HTTP 400 Bad Request

I have looked at threads where people are experiencing similar problems. It appears they were resolved after some fiddling with the API key and restrictions. I have done the following things in that context:

*

*Enabled billing

*Restricted my API key - however, I am not given an option to restrict it to "Static maps". I currently have it restricted to
"Google Cloud apis". Same error as before, but the key is still
registering hits.

*Restarted R after doing the aforementioned things, and double checking my packages.

Would appreciate some help with this, none of my labmates are having this problem and I'm starting to tear my hair out, lol.

A: After some messing around, I figured it out. It wasn't extremely intuitive, so I'm posting it here in case someone else who is new runs into the same problem.
Essentially, after generating the key, from the cloud console, you need to go into the library and enable the following four APIs:
Static Maps,
Map Embed,
Geolocation,
Geocoding.
Then, go edit the key. Scroll down and restrict it to the aforementioned four APIs. Worked perfectly fine after that.

A: I had the same issue as you and I fixed it regenerating the API key in this link: https://console.cloud.google.com/
First you look for "APIs and services" (or something like that) and later for "Credentials" in the vertical menu.
If your API key is to old, like mine was and I used just a few times, so maybe the key stopped to work. After I regenerate a new one, it's working fine!

A: I have a bit to add to the solutions above. I only use my API key for generating maps in R and was receiving the same error message as you. I went through all the suggested solutions: enabled billing, restricted the key to only four APIs, and yet was still experiencing the issue. My "free trial" on Google Cloud Console had ended and all I needed to do was Renew my billing when the trial ended. Sharing in case this will help someone out in the future.


text:
Q: Entity Framework many-to-many self-reference I have an entity User. Each User is supposed to have many Friends and Teachers. With EF Code First I am a little bit confused on how to achieve what I want. I saw examples of self reference, but not many-to-many. For example:
public class Employee
{
  #region Properties

  public int EmployeeID { get; set; }
  public string FirstName { get; set; }
  public string LastName { get; set; }

  public int? ManagerID { get; set; }
  public Employee Manager { get; set; }

  #endregion
}

and the modelBuilder:
modelBuilder.Entity<Employee>().
      HasOptional(e => e.Manager).
      WithMany().
      HasForeignKey(m => m.ManagerID);

How to create an entity with self-reference in my case, where there are Friends (if a is friend with b this means that b is friend with a) and Teachers (if a is teacher of b, b is student of a)?
Sorry if there already exists a similar thread.
Any help is greatly appreciated.

A: Ok, so because a lot of people answered this ;), I searched a little more and I found the solution for my case. The entity looks like:
public class User
{
    public int ID { get; set; }
    public string UserName { get; set; }

    public virtual ICollection<User> Friends { get; set; }
}

The modelBuilder:
modelBuilder.Entity<User>()
                .HasMany(x => x.Friends)
                .WithMany();

And finally I made helper methods BeFriend and BecomeTeacherStudent, which make sure that when you become friend with someone he becomes friend with you (and the respective thing for teacher-student).


text:
Q: Change the type of a numeric string with a space separating the decimal places to int/float I have a pandas column with str values. I need to change its type to int. The problem is that all values are separated with (' ') to differentiate the Ks and the Ms, ex:
a = '17 000 000'
int(a)
print(a)

output:
17000000

A: It is also possible to do this by changing locale settings and applying locale.atof().
CAUTION: don't use this if other locale-related logics were present.
Code:
import locale
import pandas as pd

# data
df = pd.DataFrame({"A":["17 000 000", "15 000,22"]})

# change locale settings
locale._override_localeconv["thousands_sep"] = " "
locale._override_localeconv["decimal_point"] = ","

# apply
df["A"] = df["A"].apply(locale.atof)

Result:
print(df)
             A
0  17000000.00
1     15000.22

Personally I think the df["A"].str.replace(" ", "").astype(int) construct mentioned by @Erfan is recommended.


text:
Q: illustrate a special function using scilab I have written a function to find Log(Fn) / n, where Fn is the sequence of Fibonacci numbers F_{n+1} = F_n + F_{n-1}:
function [g] = logf(n)
    u = 0;
    v = 1;
    f = v;
    for i = 2:n do
        f = u + v;
        u = v;
        v = f;
    end
    g = log(f) / n;
endfunction

What I need is to plot this function for 1< n < 200.

A: First all please try to learn MarkDown language to post readable questions. Your first question had some information which was not shown due to the conflicts with StackOverflow's MarkDown rendering.
Secondly try to modularize your code as much as possible and use the convention I have used to have a more readable code. Define a Fibonacci using a for loop:
function y = fibonacci(N)
    select N
    case 0 then
        y = 0;
    case 1 then
        y = 1;
    else
        y0 = 0;
        y1 = 1;
        y = 1;
        for ii = 3:N do
            y0 = y1;
            y1 = y
            y = y1 + y0;
        end
    end
endfunction

Then you have two options:
A. define your function in a vectorized form:
function [g] = logf(n)
    for ii = n do
        g(ii) = log(fibonacci(ii)) / ii;
    end
endfunction

consider that Scilab does not broadcast matrices / lists over functions and you should do that your self.
Now you can plot with:
n = 1:200;
plot(n, logf(n));

And the result is:

B. Alternatively you could map or broadcast your function over the sequence using feval. Define your function in scalar form:
function [g] = logf(n)
    g = log(fibonacci(n)) / n;
endfunction

and then plot with:
n = 1:200;
plot(n, feval(n, logf));


text:
Q: JavaFX, why is TableColumn null? As you will see I am a massive noob when it comes to Java and Javafx. I have spent a lot of time reading around (various forum posts, and tuts) and trying to figure out myself where I am getting this issue but it has come to the point for me to post for feedback from someone who knows their business.
When replying, please could you take the time to also explain why something isn't working and some general pointers? Here is what I have so far (my FXML and my two classes) any pointers would be fantastic!!
My FXML;
<Pane id="myScene" fx:id="myScene" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity"
      prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1"
        fx:controller="sample.TestController">
   <children>
      <TableView id="employeesTable" fx:id="employeesTable" layoutX="131.0" layoutY="64.0" prefHeight="200.0" prefWidth="360.0">
        <columns>
          <TableColumn id="colFirstName" fx:id="colFirstName" prefWidth="75.0" text="First Name" />
          <TableColumn id="colLastName" fx:id="colLastName" prefWidth="75.0" text="Last Name" />
            <TableColumn id="colEmail" fx:id="colEmail" prefWidth="75.0" text="email" />
        </columns>
      </TableView>
   </children>
</Pane>

Now the Employee class I have;
public class Employee {

private StringProperty firstName;
private StringProperty lastName;
private StringProperty email;

public Employee(String a, String b, String c) {
    this.firstName = new SimpleStringProperty(a);
    this.lastName = new SimpleStringProperty(b);
    this.email = new SimpleStringProperty(c);
}

public Employee() {
}

public String getFirstName() {
    return firstName.get();
}

public StringProperty firstNameProperty() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName.set(firstName);
}

public String getLastName() {
    return lastName.get();
}

public StringProperty lastNameProperty() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName.set(lastName);
}

public String getEmail() {
    return email.get();
}

public StringProperty emailProperty() {
    return email;
}

public void setEmail(String email) {
    this.email.set(email);
}

}
And finally the class for my test controller is
public class TestController {
public Label login;
public TextField loginUserName;
public PasswordField loginPassword;
public TextField testOutput;
@FXML TableView<Employee> employeesTable;
@FXML TableColumn<Employee, String> colFirstName;
@FXML TableColumn<Employee, String> colLastName;
@FXML TableColumn<Employee, String> colEmail;
@FXML Pane myScene;

//public javafx.scene.control.TableView employeesTable;
private ObservableList<Employee> myData;
private MainController MainController;

public void loadEmployeeForm(ActionEvent actionEvent) throws IOException, SQLException, ClassNotFoundException {
    myData = FXCollections.observableArrayList(DBCON.getEmployees());
    System.out.println(myData.size());
    Parent root = FXMLLoader.load(getClass().getResource("frmEmployees.fxml"));
    Scene myScene = new Scene( root );
    sample.MainController.setScene(myScene);
    colFirstName.setCellValueFactory(new PropertyValueFactory<Employee, String>("firstName"));
    colLastName.setCellValueFactory(new PropertyValueFactory<Employee, String>("lastName"));
    colEmail.setCellValueFactory(new PropertyValueFactory<Employee, String>("email"));
    employeesTable.setItems(null);
    employeesTable.setItems(myData);
    employeesTable.setVisible(true);
}

I get a null pointer exception when I go to set colFirstName to the property value factory which make me think I haven't initialized something somewhere but I am utterly clueless on how to go about adding that.
If I add in lines such as;
TableColumn colFirstName = new TableColumn("firstName");
for each of my columns and the tablename it works (ie it doesn't throw a load of error messages at me) that way but then I don't get any data loading into the tableview because I think that's me creating a new tableView not using the one generated from the FXML?
I have a feeling it will be very simple, but as I said I am a massive noob and any points would be much obliged.
Thanks
Mark
Update 1;
The method for load employee form is called from a button on myMain.fxml;
    <GridPane alignment="CENTER" hgap="10" prefHeight="300" prefWidth="300" vgap="10" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8"
          fx:controller="sample.TestController" stylesheets="/sample/myFirst.css">
    <children>
       <Button onAction="#login" text="Login" GridPane.halignment="CENTER" GridPane.rowIndex="5" GridPane.valignment="CENTER" />
        <Button text="GoEmployees" onAction="#loadEmployeeForm" GridPane.halignment="CENTER" GridPane.rowIndex="3" GridPane.valignment="CENTER" />
       <Label fx:id="login" GridPane.rowIndex="1" />
      <Label text="UserName" GridPane.columnIndex="0" GridPane.rowIndex="1" />
      <Label text="Password" GridPane.columnIndex="0" GridPane.rowIndex="2" />
      <TextField fx:id="loginUserName" GridPane.rowIndex="1" GridPane.columnIndex="1" />
      <PasswordField fx:id="loginPassword" GridPane.rowIndex="2" GridPane.columnIndex="1" blendMode="OVERLAY" />
        <TextField fx:id="testOutput" GridPane.rowIndex="4" GridPane.columnIndex="0" GridPane.columnSpan="3" />
   </children>
   <columnConstraints>
      <ColumnConstraints prefWidth="125.0" />
   </columnConstraints>
   <rowConstraints>
      <RowConstraints prefHeight="50.0" />
   </rowConstraints>
   <padding>
      <Insets bottom="10.0" left="9.0" right="10.0" top="10.0" />
   </padding>

</GridPane>

Is having my testController control two different FXMLs a problem/a no go?

A: When the FXMLLoader tries to load an fxml file, it will create new instance of the controller class defined with fx:controller in fxml file. Then it creates and maps the @FXML annotated fields with fx:id components in fxml file. Finally, it calls the controller's initialize() method. You can get the instantiated controller with fxmlloader.getController() after fxmlloader.load().
According to this basic work flow, the pitfall in your code is:
myMain.fxml's controller is TestController, but myMain.fxml does not contain TableColumns with fx:id colFirstName etc. So these fields are null, when the myMain.fxml has been loaded. As a result, there will be NPE in loadEmployeeForm() while trying to use these fields.
Move the TableView and TableColumns to frmEmployees.fxml's controller, and configure them (setCellValueFactory, initial data etc.) in this controller's initialize() method.

A: You never use your Employee(String, String, String) constructor. This constructor initializes the firstName, lastName, and email. Otherwise, your references will point to nothing.


text:
Q: Tomcat Server gets unresponsive I am new in JPA and java Web App development.Please help me.
Overview:
I am developing one java web application with Apache Tomcat Server [Version 7.0.70]. And It is multi-user system.
Platform : JVM Java 1.7
Framework : JPA
Database : My-Sql Workbench 6.3
Jars: MySQL Connector and Eclipse-link
Problem:
Once deploying war file into server 10 clients parallel accessing to the server with 10 unique log-in sessions . After sometime [Uncertain] server gets un-responssive and no database operations working.
After this it need to restart the tomcat server. and system gets work finely. its a continuous process to handle the system.
Image : My Tomcat Server Error
This image content that shows error when server gets un-responssive
Is there any caching problem
Image persistence.xml : Persistence Unit Cashing
Thank you,
Please give me solution.


text:
Q: Global variable not showing I'm trying to make an global variable that counts numbers up to 50 and stops all input if the variable reaches < 50
I've tried declaring a global variable in the OnStart function and tried displaying it in a Label but the numbers dont show, what am I doing wrong?
code in "OnStart": Set (Amount;0)
code in a Label: Amount

A: Once you declare a variable in your onStart event, you have to let PowerApps know that your variable exists. you can do this by forcing onStart again. I have added a picture of this, simply click on the imgur link. Good luck!
Run onStart to get your variable in memory


text:
Q: $_SESSION doesn't start When user is logged in nothing is displayed on the screen(Error-reporting is on).
It's like the $_SESSION is  not true?
<?php

 include_once('../includes/connection.php');

 if (isset($_SESSION['logged_in'])) {
 ?>

 <title>wa</title>
 <link rel="stylesheet" type="text/css" href="../assets/stylesheet.css">

 CMS

Add Article

Delete Article

Logout

<?php

 } else {

 if (isset($_POST['username'], $_POST['password'])) {
 $username = $_POST['username'];
 $password = md5($_POST['password']);

 if (empty($username) or empty($password)) {
 $error = 'All fields are required!';
 }else {

$query = $pdo->prepare("SELECT * FROM users WHERE user_name = ? AND user_password =
         ?");

$query->bindValue(1, $username);
$query->bindValue(2, $password);

$query->execute();
$num = $query->rowCount();

 if ($num == 1) {
 $_SESSION['logged_in'] = true;

 header('Location: index.php');
 exit();

} else{

 $error = 'Incorrect details!';
}
}

}

  ?>

 <title>Visuality dashboard</title>
<link rel="stylesheet" type="text/css" href="../assets/stylesheet.css">

CMS

 <?php if (isset($error)) { ?>
 <?php echo $error; ?>

<?php } ?>

<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="något">
<input type="password" name="password" placeholder="något">
<input type="submit" value="Login" />

<?php
}

?>

A: You need to call session_start(); at the beginning of your PHP file. If you have multiple files then adding it once to your connection file will work for all of them.
Read more on Sessions in PHP here

A: At line 39 md5$_POST['password']); you missed "("
md5($_POST['password']);

A: Every php file which has $_SESSION variable needs to include session_start(); on the top of the page.
When page gets a white screen after loading, you should see php_error_log for possible syntax errors (could be missing ";").
Please, review your code.
Hope it helps you.


text:
Q: Result not shown with this function I wrote the following function to fetch some RSS feeds data.
It's interesting because both alerts at the end of script will shown but the result not append to it's div via jQuery::append(), I have to mentioned that the passed ID to append function is completely correct.
    function generateTopNews() {
        // Manage RSS url
        var targetsURLs = new Array("http://www.jamejamonline.ir/rssfeed?code=01-10-95", "http://www.khorasannews.com/RSS.aspx?type=1", "http://www.tabnak.ir/fa/rss/1", "http://www.varzesh3.com/rss/");
        var logoURLs = new Array("images/jm_logo.png", "images/kh_logo.png", "images/tb_logo.png", "images/v3_logo.png");
        // Temp variables
        var resultArray = new Array();
        var rssCounter = 0;
        // RSS Loader
        for (var i = 0; i < targetsURLs.length; i++) {
            $.ajax({
                url:  "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=" + encodeURIComponent(targetsURLs[i]),
                dataType: "json",
                success: function(data) {
                    var fetchedFeed = data.responseData.feed.entries;
                    for (var j = 0; j < fetchedFeed.length && j < 2; j++) {
                            // RSS HTML Template
                            var htmlContent = "
";
                            htmlContent += "
";
                            htmlContent += "
";
                            htmlContent += "            ";
                            htmlContent += "
" +  fetchedFeed[j].title + "
";
                            htmlContent += "
";
                            htmlContent += "
";
                            htmlContent +=              fetchedFeed[j].contentSnippet;
                            htmlContent += "
";
                            htmlContent += "
";
                            htmlContent += "
";
                            // Count up the RSS
                            resultArray[rssCounter++] = htmlContent;
                    }
                }
            });
        }
        // Start
        $("#rss-container").append("@Start");
        alert("@Start");
        // Append the results
        for (var i = 0; i < resultArray.length; i++) {
            $("#rss-container").append(resultArray[i]);
        }
        // End
        $("#rss-container").append("@End");
        alert("@End");
    }

A: Since ajax is asynchronous, You should write the code for append() inside the success event. Otherwise append() happen before the data getting fetched from the server.
function generateTopNews() {
      // Manage RSS url
      var targetsURLs = new Array("http://www.jamejamonline.ir/rssfeed?code=01-10-95", "http://www.khorasannews.com/RSS.aspx?type=1", "http://www.tabnak.ir/fa/rss/1", "http://www.varzesh3.com/rss/");
      var logoURLs = new Array("images/jm_logo.png", "images/kh_logo.png", "images/tb_logo.png", "images/v3_logo.png");
      // Temp variables
      var resultArray = new Array();
      var rssCounter = 0;
      // RSS Loader
      for (var i = 0; i < targetsURLs.length; i++) {
          $.ajax({
              url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=" + encodeURIComponent(targetsURLs[i]),
              dataType: "json",
              success: function (data) {
                  var fetchedFeed = data.responseData.feed.entries;
                  for (var j = 0; j < fetchedFeed.length && j < 2; j++) {
                      // RSS HTML Template
                      var htmlContent = "
";
                      htmlContent += "
";
                      htmlContent += "
";
                      htmlContent += "            ";
                      htmlContent += "
" + fetchedFeed[j].title + "
";
                      htmlContent += "
";
                      htmlContent += "
";
                      htmlContent += fetchedFeed[j].contentSnippet;
                      htmlContent += "
";
                      htmlContent += "
";
                      htmlContent += "
";
                      // Count up the RSS
                      $("#rss-container").append(htmlContent);
                  }
              }
          });
      }

  }


text:
Q: LoadPackage calls initialize, but registerClass won't work I have a unit wich defines TBla and the following code in the initialize section:
initialization
  RegisterClass(TBla);
  showMessage('registered');

This unit is inside a package. ok.
In a button click on my app I have the following code:
  LoadPackage('C:\temp\testes_packs\pack1\Package1.bpl');
  pc := GetClass('TBla');
  if pc = nil then
    ShowMessage('didnt work');

When I click the button the 'registered' message shows up. But, 'didnt work' shows too. Which indicates that the initialization wass called but the register class for some reason didn't work.
Ok, to prove that the LoadPackage was the problem, I included my unit (that contains TBla class) directly into my project and removed the loadPackage line and, tada the 'registered' message shows and the getClass works.
Any ideas?

A: Your package needs to include "rtl" and "vcl" in its "requires" list. That way, the class-registration list will be the one in the shared package and not private to your own package.
Also, your application needs to be compiled to use run-time packages. In particular, the "rtl" and "vcl" packages need to be on its list of run-time packages.
Without doing both those things, the class-registration list used by one module will not be the same as the list used by the other module. They both have to use the same one, and the way to do that is to make sure that both modules are sharing the list exposed by the RTL.


text:
Q: An XML file can break? Well, I want to store information in an XML file and send it to be processed on a server. The structure of the XML file is simple:
<name></name>
<age></age>
<sex></sex>
<info></info>

The problem is that the information will be saved in the XML, are information that will be inserted by the users through text fields.
Assuming the User inserted a XML tag, and the final file becomes this:
<name> <age></name></age> </name>

There is a possibility of xml reader encounters a problem and not able to read the file?

A: Yes. It is even very likely. This is why you should always be performing input sanitization:
For examples see here: santization done in PHP

A: If the XML is created properly, the value should be encoded:
<name> <age></name></age> </name>

That makes the value harmless for the XML, and there is no problem reading it.


text:
Q: Bisection index search - why compare to len(a)? So I'm trying to understand bisection. I get that it's a useful, computation-saving algorithm, I get the general concept of what it does and how it does it.
What I don't get involves this search function that uses it, taken from https://docs.python.org/2/library/bisect.html
from bisect import bisect_left

def index(a, x):
        'Locate the leftmost value exactly equal to x'
        i = bisect_left(a, x)
        if i != len(a) and a[i] == x:
            return i
        raise ValueError

Could somebody please break down for me exactly what the i != len(a) part of the if line does? I can read it - it checks whether the insertion index of x is equivalent to the length of the list a - but I can't understand it. Why is it necessary? What would happen without it?
I follow that, let's say x has an insertion index greater than the length of a, then x obviously doesn't exist in a so it spews out the error - but if that's the case then the a[i] == x check trips it up anyway...?
Thanks!

A: Since lists are indexed from 0 then a[i] doesn't make sense for i == len(a) (the last element has index len(a) - 1). Doing a[i] for such i will throw an IndexError.
Now if bisect_left(a, x) returns len(a) then it means that the element should be added at the end of the list in order to preserve the order.
On the other hand if there is a match for x in a then
bisect_left(a, x) != len(a)

because If x is already present in a, the insertion point will be before (to the left of) any existing entries. If it is before then obviously the insertion index has to be smaller or equal to the last index (since in worst case this matched element will have last index) and the last index is len(a)-1 which is smaller then the length.
All in all if bisect_left(a, x) == len(a) then there is no x in a. This allows us to easily get rid of "IndexError problem" that I've mentioned at the begining.
Note that this (obviously) is not true for bisect_right. However following similar logic you can reach something analogous: if bisect_right(a, x) == 0 then there is no x in a. Unfortunately implementing index function via bisect_right would be more difficult since you would still need this check for i == len(a) to avoid an IndexError.

A: Zero based indexing. The i != len(a) is to catch the exact case where i is equal to the length of the list, in which case a[i] will raise an index error (lists start at index 0 and go up to len(a) - 1).


text:
Q: How to fork, make significant changes, and give proper credit? There is an elisp project on github I have forked. Some of the source files and functions I don't want to change, some I want to change drastically, and others only slightly. The original copyright at the top of each source file mentions the project that it came from.
1) Should I rename all functions or only those that have code changed (no matter how minor)?
2) If I modify some functions within a file but not all/most should I rename the file and change the copyright at the top to reflect my project instead of the original?
3) If many/all of the files get renamed how should I give credit to the original authors (other than their commits showing up in git log)?
notes
I'm forking due to wanting to take the code in a very different direction from the original's stated purpose and my fork would not be pulled in by the original authors.
The original project and my fork both use GPLv3
Elisp code by convention prefixes the name of functions/variables with the project name to avoid namespace collisions.
** Edit **
Found some additional information after posting...
How to rebrand/copyright a forked project (GNU/GPL)?

1) Sure. In fact, not changing it at least a little would imply it's the original project, which is a bad idea.
2) You can't remove copyright notices. Add yours on top.
3) Why do you want to remove the reference to the old project? It's a suggestion, but removing it would be impolite and potentially misleading. The Open Source/Free Software communities value correct attribution.

Need advice on attribution/copyright of heavily modified OSS code (BSD, Apache, etc) in source headers

If you copy even a single function out of a file, unless you could convince a court that the function was too trivial for copyright to apply, then the license of the source file stays with the function

Between Stefan's answer and these stackoverflow posts I've decided to:
1) Rename all files and functions even if unchanged to use my project's name.
2) Keep the original copyright as is in all existing files (and a few new files resulting from moving the old code into more logical subdivisions)
3) Add my copyright to all files new and old.
4) Make a note just above the old copyright to check git history before a certain commit id to see the original project at the time of fork as well as a reference to the url of the original project to see the most up to date version.
I think these changes should make clear that this is a separate project while maintaining credit where due to the original and avoiding any namespace conflicts or copyright violations.

A: Copyright is cumulative (i.e. as long as you keep using some of the original code in the new code, the original's author still applies to that part of the code).  So don't replace his copyright with yours, but just add yours next to his instead.


text:
Q: Pixel correlation / similarity in an image Python I am new in Python.
I have an image of size 8*8, and when flattened = 64. Is there any function that measures the correlation between the pixel i and all the other pixels in this image ?
So at the end I want to plot a 64*64 matrix of correlation.
Thanks !

A: Correlation is a measure to evaluate mutual relationship or connection between two or more things, usually vectors, not single point. Pixel is a single point with a single value. So, in your case, I would subtract pixel value form each pixel value of the image, looking at the difference in this case.

A: Correlation in the context of just 1 image makes no sense. I guess (or I am almost certain) that the question arose from a misunderstood course question where it is about many images and not just one.
That is why I am just answering here for this new understanding of the question even though the exact question is different.
Example of 2 images:
As soon as you take the pixel of index 30 of 2 images instead of just 1 imgage, and then compare them with pixel of index 20, you can compare the 2 values each of those 2 images and only then the correlation of (2 x index 20, 2 x index 30) makes sense.
In that case, you would simply loop over all 64 index columns of the 2 images (number of images = number of rows), apply the Python corr function as in this example, and add the results up in a vector of size 64. Mind that there are cases when the variance of the index column is 0, then you should add a 0 to the result vector instead of applying the corr function.


text:
Q: AWS CloudFormation init services as bash script I would like to know what's the bash equivalent for below CloudFormation code.
ServerLaunchConfiguration:
    Type: AWS::AutoScaling::LaunchConfiguration
    Metadata:
      AWS::CloudFormation::Init:
        configSets:
          install_all:
            - install_cfn
        install_cfn:
          ..some important staff..
          services:
            sysvinit:
              cfn-hup:
                enabled: 'true'
                ensureRunning: 'true'
                files:
                  - /etc/cfn/cfn-hup.conf
                  - /etc/cfn/hooks.d/cfn-auto-reloader.conf

I want services part to be done by bash script because at the time it's executed, files /etc/cfn/cfn-hup.conf and /etc/cfn/hooks.d/cfn-auto-reloader.conf does not exist. I'm creating them as part of UserData. I'm aware that they can, and probably should be created by files in Init.
When I run command:
systemctl status cfn-hup.service

I get:

Loaded: loaded (/etc/rc.d/init.d/cfn-hup; bad; vendor preset:
  disabled)    Active: failed (Result: exit-code)

This is predictable as those files does not exist while trying. But I can actually start this service later with success using service cfn-hup start.
Question:
Will results be the same when I leave those services as they are and then after crating .conf files I will call: service cfn-hup start?

A: Perhaps, Configsets can solve this problem for you.

Configsets If you want to create more than one config key and to have
  cfn-init process them in a specific order, create a configset that
  contains the config keys in the desired order.


text:
Q: understanding c++ ranges, transforms and filters I am very new to using ranges in C++. I am using gcc 12.1 with the c++23 standard. As a toy example, I would like to use piping to print the indices of all even values contained in some vector. First we define some useful lambdas...
auto square_number = [idx=int{0}]() mutable { ++idx; return idx*idx; };
auto make_pair = [idx=int{0}](int e) mutable { return pair<int,int> {++idx, e};};
auto has_even_value = [](const pair<int,int>& p){ return p.second % 2 == 0; };

Then we create some numbers, use a range::views::transform to create the pairs of indices and values, and then explicitly store those pairs in a new vector.
namespace srv = std::ranges::views;
vector<int> squares(20);
generate(squares.begin(), squares.end(), square_number);

auto pair_view = squares | srv::transform(make_pair);
auto all_pairs = vector<pair<int,int>> {pair_view.begin(), pair_view.end()};

Next we create a filter view to generate even squares and print the result.
auto even_pair_view = all_pairs | srv::filter(has_even_value);
for(const auto& p : even_pair_view) cout << p.first << " - " << p.second << endl;

As expected we get the (index - value) pairs 2 - 4 up to 20 - 400. Great.
However, if I try to pipe the transform and the filter directly, without first storing all_pairs, like so
auto even_pair_view = squares
    | srv::transform(make_pair)
    | srv::filter(has_even_value);

the same printing as before gives me 3 - 4, 6 - 16 up to 30 - 400. So apparently, the ++idx in my make_pair lambda is applied multiple times.
I do not understand, where exactly that index is increased, and therefore I also don't know how to solve this problem using range views and piping. All help would be highly appreciated.


text:
Q: What are the differences between: main(){}, int main(){} and int main(void){} I am currently learning C and I have written many small programs. However, I have noticed that the main function could start as
    main()
    {
       //code
    }

or
    int main()
    {
      //code
      return 0;
    }

or
    int main(void)
    {
       //code
       return 0;
    }

Which option should I use? Thanks!

A: For Standard C

For a hosted environment (that's the normal one), the C99 standard
  says:

5.1.2.2.1 Program startup
The function called at program startup is named main. The implementation declares no prototype for this function. It shall be
    defined with a return type of int and with no parameters:
int main(void) { /* ... */ }

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they
    are declared):
int main(int argc, char *argv[]) { /* ... */ }

or equivalent;9) or in some other implementation-defined manner.
9) Thus, int can be replaced by a typedef name defined as int, or the type of argv can be written as char **argv, and
    so on.

This (is valid in C89) main() implicitly meant (previously) int main(void). However the default return type rule has been abandoned in C99.  Also:
main() means - a function main taking an unspecified number of arguments of.
main(void) means "a function main  taking no arguments.

A: Your first example uses a feature inherited from the outdated dialect of C which predated the first ANSI(1989) and ISO(1990) standard: namely, that you can write a function which doesn't specify its return type, and in that case the type defaults to int.
In early C, the void keyword and associated type did not exist. When programmers wanted to write procedures ("functions that have a side effect, but do not return anything"), they simulated it using this feature. They wrote a function without any keyword specifying the return type. They allowed the function to execute to it last statement without returning a value (or alternatively, they used return; to exit from the middle without supplying a value), and they wrote the calls to the function such that those calls did not try to use the return value:
parse_input() /* similar to a procedure in Pascal, but fake! */
{
   /* ... */
   if (condition())
     return; /* no value */
   /* ... */
   /* fall off end here */
}

int main()
{
   parse_input(); /* no return value extracted, everything cool! */
   return 0;
}

Unfortunately, some programmers also started not caring about the termination status of a program and writing main itself in this procedure style:
main()
{
  /* do something */
  /* fall off the end without returning a value */
}

(A mixed style also existed: omitting the int declarator but returning an integer value.)
These programs failing to return a value had an indeterminate termination status. To the operating system, their execution could look successful or failed. Woe to the script writer who tried to depend on the termination status of such a program!
Then things took a turn for the worse. C++ came along and introduced void, and it was adopted into C. With the void keyword in C++, one could declare a function that actually returns nothing (and make it an error to have a return; statement in any other kind of function). The dummy programmers who used to write main with no return type got dumber, and started sticking this new-fangled, fresh-out-of-C++ void in front:
void main() /* yikes! */
{
  /* do something */
  /* fall off the end without returning a value */
}

By this time they had forgotten that when they wrote main(), it actually meant int main(), which made the function have a compatible type with the startup call invoked by the environment (except for the matter of neglecting to return a value). Now they actually had a different function type from the expected one, which might not even be successfully called!
Where things stand now is that in C++ and in the latest C++ standard, main is still required to return an int. But both languages make a concession for the original dummy programmers: you can let execution "fall off" the end of main and the behavior is as if return 0; had been executed there. So this trivial program now has a successful termination status as of C99 and, I think, C++98 (or possibly earlier):
int main()
{
}

But neither language makes a concession for the second-generation dumber programmers (and everyone else who read the C books that those programmers wrote in the 1980's and since). That is, void is not a valid return declarator for main (except where it is documented by platforms as being accepted, and that applies to those platforms only, not to the portable language).
Oh, and allowance for the missing declarator was removed from C in C99, so main() { } is no longer correct in new dialects of C, and isn't valid C++. Incidentally, C++ does have such a syntax elsewhere: namely, class constructors and destructors are required not to have a return type specifier.
Okay, now about () versus (void). Recall that C++ introduced void. Furthermore, though C++ introduced void, it did not introduce the (void) argument syntax. C++ being more rigidly typed introduced prototype declarations, and banished the concept of an unprototyped function.  C++ changed the meaning of the () C syntax to give it the power to declare. In C++, int func(); declares a function with no arguments, whereas in C, int func(); doesn't do such a thing: it declares a function about which we do not know the argument information. When C adopted void, the committee had an ugly idea: why don't we use the syntax (void) to declare a function with no arguments and then the () syntax can stay backward compatible with the loosey-goosey legacy behavior pandering to typeless programming.
You can guess what happened next: the C++ people looked at this (void) hack, threw up their arms and copied it into C++ for the sake of cross-language compatibility. Which in hindsight is amazing when you look at how the languages have diverged today and basically no longer care about compatibility to that extent. So (void) unambiguosly means "declare as having no arguments", in both C and C++. But using it in C++ code that is obviously pure C++ never intended to be C is ugly, and poor style: for instance, on class member functions! It doesn't make much sense to write things like class Foo { public: Foo(void); virtual ~Foo(void) /*...*/ };
Of course, when you define a function like int main() { ... }, the function which is defined has no arguments, regardless of which language it is in. The difference is in what declaration info is introduced into the scope. In C we can have the absurd situation that a function can be fully defined, and yet not declared, in the same unit of program text!
When we write main, usually it is not called from within the program, and so it doesn't matter what the definition declares. (In C++, main must not be called from the program; in C it can be). So it is immaterial whether you write int main() or int main(void), regardless of whether you're using C or C++. The thing which calls main does not see any declaration of it (that you write in your program, anyway).
So just keep in mind that if you write:
int main()  /* rather than main(void) */
{
}

then although it is perfect C++ and correct C, as C it has a slight stylistic blemish: you're writing an old-style pre-ANSI-C function that doesn't serve as a prototype. Though it doesn't functionally matter in the case of main, you may get a warning if you use some compilers in a certain way. For instance, GCC, with the -Wstrict-prototypes option:
test.c:1:5: warning: function declaration isn't a prototype [-Wstrict-prototypes]

Because -Wstrict-prototypes is a darn useful warning to turn on when programming in C, for improved type safety, (along with -Wmissing-prototypes), and we strive to eliminate warnings from our compile jobs, it behooves us to write:
int main(void) /* modern C definition which prototypes the function */
{
}

which will make that diagnostic go away.
If you want main to accept arguments, then it is int main(int argc, char **argv) where the parameter names are up to you.
In C++, you can omit parameter names, so this definition is possible, which serves nicely in the place of main().
int main(int, char **) // both arguments ignored: C++ only
{
}

Since the argument vector is null-pointer-terminated, you don't need argc, and C++ lets us express that without introducing an unused variable:
#include <cstdio>

int main(int, char **argv)  // omitted param name: C++ only
{
  // dump the arguments
  while (*argv)
    std::puts(*argv++);
}

A: You should use 1 one of these 4 choices:
int main(void);
int main();

int main(int argc, char **argv);
int main(int argc, char *argv[]);

where it's conventional to use the names argc and argv; you can change them but don't.
Take care never to use void main(void); which is too-often seen in production code.

A: first :
declares a function main - with no input parameters. Although main should have returns ( your compiler will take care of this )
2nd/3rd:
Declare a function main which returns an int and takes in no input parameters
You should use 3rd format. Rather this is the best way:
int main(int argc, char *argv[]){
     return 0;
}

A: *

*By default main function returns an integer type, hence its "int main()" or you can give simply "main()"

*"main(void)" is same as "main()", it tells the compiler that main function has no arguments.

*In case if you want to pass arguments via main function:
int main(int argc, char *argv[]){
     return 0;
}

A: main(){}

The above line give you an error. The default return type of any function in c is int. As the above code return nothing it gives you an error.
int main(){
//body
return 0;
}

In above code it fulfill all requirement so the above code will run.In above code we pass no argument in the function. So this function can take global and local variables to process.
int main(void)
{
   //code
   return 0;
}

In above code we pass no argument in the function. But specifying void tells the compiler that it does not take any argument. void is the default datatype of argument that signifies no input.


text:
Q: How could BRO-IDS compare strings with NUL-terminator I am testing string comparison with BRO, and got some runtime errors. Hope you guys could take a look and give me some hints.
For example i have two strings, let's say str_A and str_B, str_A is sort of a pattern, like: str_A = "\x13\x02\xf0\x80";
And str_B is a payload(contents) string from the function:
event tcp_packet(c: connection, is_orig: bool, flags: string, seq: count, ack: count, len: count, contents: string)

I compared the two of the strings with: if(str_A in str_B), which reduced the runtime errors like:
1467860547.182543 error: string with embedded NUL: "\x13\x00\xf0\x13"
1467860547.182543 error: string without NUL terminator: "\x13\x00\xf0\x13\x02\xf0\x80\x02\x00\x00\xc0\x01\x00\x00\x00\x00\x87\x02"

It looks like the 'x00' in the middle of the pattern string was considered as a terminator, and for the latter there wasn't a NUL at the end of the str_B.
So the (silly) question is how i could append a NUL at the end of str_B within BRO? and how to make BRO ignore the embeded NUL in the middle of a string when comparing? Many Thanks.

A: This was figured all right by translating(calling the function string_to_ascii_hex()) the hex-string into an ASCII-hex-string.


text:
Q: RecycleView Select multiples How I can select multiples rows in a recycleview correctly ?
I see this example : https://github.com/kiddBubu/RecyclerViewDemo but is so bat because when move up or down screen value disappear or change  or assing position to other row, so bad.
I try show more content of the row.
Example :
Row 1 (uncollapsed)
Row 2 (uncollapsed) - > click - > (collapsed) add + padding or margin
Row 3 (uncollapsed)
.
.
Row x (uncollapsed)

But when I try move list up or down the value selected is randomly and others views change automatically, I don't know why, ListView, RecycleView  are equals...
I know how do with listviews normals with "tags" (but also is bad)
I don't want "expandablelistview".
Any help ?
Update
I want this efect : http://i.stack.imgur.com/fuFFl.png
I have not found anything, not a complete example in google
Code :
I tried 4 or 5 methods, this is the first
boolean [] check; check = new Boolean[Fragment2.recyclerView.size()];

Arrays.fill(array, Boolean.FALSE);

.
.
.
 public class ViewHolder extends RecyclerView.ViewHolder {

        // l1
        public TextView text1,text2,text3,text4;
        LinearLayout imgLayout,l1;

        // l2
        public TextView text5,text6,text7;
        LinearLayout l2;
        public ViewHolder(final View itemView) {

            super(itemView);

            l1 = (LinearLayout) itemView.findViewById(R.id.l1);
            imgLayout = (LinearLayout) itemView.findViewById(R.id.imgLayout);
            text1 = (TextView) itemView.findViewById(R.id.text1);
            text2 = (TextView) itemView.findViewById(R.id.text2);
            text3 = (TextView) itemView.findViewById(R.id.text3);
            text4 = (TextView) itemView.findViewById(R.id.text4);

            l2 = (LinearLayout) itemView.findViewById(R.id.l2);
            text5 = (TextView) itemView.findViewById(R.id.text5);
            text6 = (TextView) itemView.findViewById(R.id.text6);
            text7 = (TextView) itemView.findViewById(R.id.text7);

            int itemPosition = Fragment2.recyclerView.getChildPosition(itemView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!check[itemPosition]) {
                        l1.setVisibility(View.VISIBLE);
                        l1.setEnabled(true);
                        check[itemPosition] = true;

                        l2.setVisibility(View.GONE);
                        l2.setEnabled(false);

                    } else {
                        l1.setVisibility(View.GONE);
                        l1.setEnabled(false);
                        check[itemPosition] = false;

                        l2.setVisibility(View.VISIBLE);
                        l2.setEnabled(true);
                    }
                }

A: The RecyclerView connects a data structure like an ArrayList via Adapter. Upon an update of the ArrayList, your RecyclerView's View objects should change state.
If I were to update multiple rows in a RecyclerView, I'd update the value inside the ArrayList and call mAdapter.notifyDataSetChanged(). So when I scroll, the element has been updated properly.


text:
Q: Loop over AngularFirestoreCollection Observable in Angular method I'm using Angularfire2 with the new Firestore database. In my method I'm doing a query like this:
const questionsRef = this.afs.collection('questions', ref => ref.where('category', '==', category).limit(10));

Now I need to get the results in a loop so I can manipulate the data and create a new document in a different collection with the values from that result.
This is how one of the documents returned from the collection is structured:
{
  "description": "Test question",
  "category": "dOULqW4jMkC4E4iopOyk",
  "answers": [
    {
      "description": "test answer",
      "correct": true
    },
    {
      "description": "test answer 2",
      "correct": false
    }
  ]
}

I want to make a copy of the results returned from questionsRef but add a new field to every answer called "selected": false.
I realise I also need to somehow wait until all the data is loaded, but I'm not sure how to do this.

A: I'm going through the same thing on FB collections now. I think there's a mind-shift to approaching it but I'm still struggling with it. Here's a SO post about it but I've just iterated through the collection like this:
      var questionsRef = this.afs.collection('questions', ref => {
         return ref.where('category', '==', category).limit(10);
      });

      var questionsCol = questionsRef.snapshotChanges().pipe(
         map(actions => actions.map(a => {
            return a.payload.doc.data(); // get id using a.payload.doc.id
         }))
      );

      questionsCol.forEach(doc => {
         // operate on the doc here...
      });

Hope that helps.


text:
Q: Vue Router Guard Method still allowing page load I am using the following guard const to prevent user from entering pages while they don't have a token saved on cookies. However if i try it enough time  the user is able to enter the page but the components don't load, is is just a blank page
What else should i add to my router file to prevent this kind of thing from happening?
Here is my guard constant:
const guard = function(to, from, next) {
  const token = Cookies.get('token')
  if(typeof token === 'undefined' || token === null ){
    this.$store.dispatch('logout')
    window.location.href = "/";
  } else {
    next();
  }
};

A: Try to use next('/') instead of window.location.href = "/" :
import store from 'path/to/store/
const guard = function(to, from, next) {
  const token = Cookies.get('token')
  if(typeof token === 'undefined' || token === null ){
   store.dispatch('logout');
    next('/');
  } else {
    next();
  }
};


text:
Q: extract latitude/longitude from specific string I have this specific string:
{"latitude":46.57637,"longitude":26.91551}

I want to extract both coordinates, each coordinate to assign and display separately, like:
<?php
echo $lat;
echo $long;
?>

Anyone have any idea?
Many thanks!

A: <?php

    $json = json_decode('{"latitude":46.57637,"longitude":26.91551}');
    echo $json->latitude;
    echo $json->longitude;
?>

Using json decode you can archive. more details php

A: You can decode the json array like below
$decodeData=json_decode({"latitude":46.57637,"longitude":26.91551});
lat=$decodeData->latitude;
lng=$decodeData->longitude';


text:
Q: Limit point of the closed set $[0,1]$ I am trying to understand the concept of limit point in general.
For the open set $(0,1)$, earlier discussions on stackexchange showed that all point in the open set $(0,1)$ is a limit point.  Similarly, we can say the same about the closed set $[0,1]$, right ?.  For every point $x$ in the set $[0,1]$, we can find $\epsilon$ neighborhood ($V_{\epsilon}$) such that $V_{\epsilon}(x) \cap A \neq \{\emptyset,x\}$.
If the above comment is true, anyone can give an example of a continuous set containing isolated points ?

A: By "continuous", I think you mean connected.  But a connected set might not have all of its limit points.
Here's an example.  Consider the set $(0,1)$.  It is true that every point in the set is a limit point.  For example, let's look at the point $1/2$.  Is this a limit point?  To be a limit point, we need to create a sequence of points in the set that approach this point.  The Sequence $1/2, 1/2, 1/2, ...$ is such a set of points.
What about the point $0$?  Is $0$ a limit point of this set?  It is!  Consider the sequence $1/2, 1/4, 1/8, 1/16, 1/32, ...$  This sequence is getting closer and closer to the point $0$, and no point in this sequence will ever leave the set $(0,1)$.  Therefore, the set $(0,1)$ does not contain all its limit points.
Any set that contains all of its limit points is called a "closed" set.  So $(0,1)$ is not a compact set.  But $[0,1]$ is.


text:
Q: JSON Parsing in c#. The Json string is in a javascript file I am facing  an issue in parsing a JSON data which is retrieved from a javascript file (say xyz.js)
The file size is about 10mb and only one JSON string is present in it.
We were using javascript directly to parse this file, I want to know whether we have any C# classes to parse this file or not?
example of the JSON string is
var JSONString = {
    Level1:{
        DateTime:{
              date:'Wed Sep 14 14:19:32 CDT 2011'
        },
        information:{
              url:'http:\\www.google.com'
        },
        RepetitiveLevel:[
            {
                ids:{
                    courses:[
                        "BE",
                        "MS"
                    ]
                },
                SubRepetitiveLevels:{
                    DetailedLevel:[
                        {
                            name:"Trial 1",
                            type:"blah",
                            latest:"no",
                            version:"1",
                            description:"This is a test 1.",
                            recommendation:"blah",
                            prerequisite:"WARNING! xyz",
                            releasedate:"2012-06-18T15:38:55.79",
                            support:{
                                degree:[
                                    "MSC",
                                    "BSC",
                                    "HSE"
                                ]
                            },
                            OperatingSystem:{
                                os:["Win 2008 x64"
                                ]
                            },
                            previousversions:{
                                version:[
                                ]
                            },
                            allversions:{
                                version:[
                                    "1",
                                    "2",
                                    "3"
                                ]
                            },
                            ftppath:"ftp://",
                            files:{
                                file:["note1.txt"
                                ]
                            },
                            filesizes:{
                                filesize:["5MB"
                                ]
                            },
                            checkSum:{
                                md5:["abc"
                                ]
                            },
                            note:"
NOTE:  NOTE 1

",
                            fix:"
 xyz

"

                        },
                        {
                            name:"Trial 2",
                            type:"blah",
                            latest:"yes",
                            version:"2",
                            description:"This is a test 2.",
                            recommendation:"blah",
                            prerequisite:"WARNING! xyz",
                            releasedate:"2012-06-18T15:38:55.79",
                            support:{
                                degree:[
                                    "MCA",
                                    "BCA",
                                    "BE"
                                ]
                            },
                            OperatingSystem:{
                                os:["Win XP"
                                ]
                            },
                            previousversions:{
                                version:[
                                ]
                            },
                            allversions:{
                                version:[
                                    "4",
                                    "5",
                                    "6"
                                ]
                            },
                            ftppath:"ftp://",
                            files:{
                                file:["Note2.txt"
                                ]
                            },
                            filesizes:{
                                filesize:["2MB"
                                ]
                            },
                            checkSum:{
                                md5:["abc"
                                ]
                            },
                            note:"
NOTE:  NOTE 2

",
                            fix:"
 ahahah

"

                        }

                    ]
                }
            }
        ]
    }
}

The tag named "RepetitiveLevel" will be repeating more than 10 times
Under this tag, there will be repetitions of "SubRepetitiveLevels", which in turn contains more than one entry for "DetailedLevel".
This kind of JSON string fails for Newtonsoft.Json.JsonConvert.DeserializeObject

   I know this is a little bit confusing, but we are not finding any other option.

Any help will suffice. Thanks in advance.

A: Try this library. We used it on one ASP.NET project and it worked fine.
This program writes then reads 100mb file with serialization/deserialization.
class Program
{
    static void Main(string[] args)
    {
        var lst = new List<string>();
        for (var i = 0; i < 1024 * 1024 * 10; i++)
        {
            lst.Add(i.ToString());
            if(i%(1024 * 1024)==0)Console.WriteLine("+1m");
        }
        var wrt = Newtonsoft.Json.JsonConvert.SerializeObject(lst);
        lst = null;
        File.WriteAllText(@"F:\1.txt",wrt);
        Console.WriteLine("written");
        wrt = "";
        GC.Collect();
        wrt=File.ReadAllText(@"F:\1.txt");
        lst=Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(wrt);
        Console.WriteLine("read");
        Console.WriteLine(lst.Count.ToString());
    }
}


text:
Q: how to show/communicate/broadcast messages to android app that is in killed state if device receives push notification from fcm I want to update incoming unread messages badge count on app's icon if device receives push notification from fcm and app is in killed state.
I am able to do so if app is in background but not able to do so if app is in killed state.
If i receives fcm push notification then it is shown only in notification tray but some how i want to pass or communicate with the app that is killed.
So is there any solution for this & how can this be achieved.
Thanks,
Roshan

A: yes , please refer
https://firebase.google.com/docs/cloud-messaging/concept-options#notifications_and_data_messages
and note that , notification mesaages (app in killed state) are handled by android system
but , if the notification received is a data payload notification , then it is handed over to the app's onMessageRecieved method of the FCMlistener, so change the type of notification you send to your device from a notification message to data message, Once you extract your message from the data message , you can then build a notification there to display or run any process or method even if the app was in killed state
public class MyFcmListenerService extends FirebaseMessagingService {
String TAG = "FCM";
@Override
public void onMessageReceived(RemoteMessage message){
    String from = message.getFrom();
    Map data = message.getData();

    Log.e(TAG, "From: " + from);
    Log.e(TAG, data+"Notification Message To : " + data.get("name") +"\n body:"+data.get("body")+"\n time to live:"+data.get("time_to_live"));
    sendNotification( data);

}

create this class in your app , in MyFcmListenerService.java
and use data message as your fcm notification ,it would work as you need


text:
Q: How do i change one of the classes in an element with Javascript If i have the library materialize and an element "h1", how do i change only its background color "black" to "white" using javascript? For example using a button.

Test

A: Give the element an id:

Test

Then you can select it like the following:
var el = document.getElementById('test');

You can then just remove the class black with this code:
el.classList.remove('black');

And append the new class:
el.classList.add('white');

A: Create a function and a white class. Inside the function use document.getElementsByClassName . Since document.getElementsByClassName is a collection so you need to use index like [0] to access it

function changeColor() {
  document.getElementsByClassName("black")[0].classList.add('white')

}
.white {
  background: white !important;
}

.black {
  background: black;
}

.red-text {
  color: red;
}

Test

<button onclick='changeColor()'>Change Color</button>

A: Here is the answer.
Select the element using document. getElementById
and on button click
You can use title.classList.toggle("white"); to toggle given class.

const button = document.getElementById('btn');
const title = document.getElementById('title');

btn.addEventListener('click', () => {
  title.classList.toggle("white");
});
.red-text {
  color: red;
}

.black {
  background-color: #000;
}

.white {
  background-color: #fff;
}

Test

<button id="btn">Change Bg</button>

A: One approach that keeps things neat and tidy in terms of Materialize conventions could be to add or remove classnames, and thus triggering pre-existing styles. Note, you may need a more specific selector if you have multiple elements that share the class:
document.querySelector('h1.black').classList.add('white');

Materialize already has a vast array of colour classes so no need to create new ones.
Codepen here:
And just for clarification:
document.querySelector('h1.black') - this finds the element with a matching class. You could also use ID to be more specific, while
.classList retrieves all the classes applied to that element (in this case .black and .red-text) and .add('white') - well, that adds the class you state in the brackets.

A: Hope this resolves your problem. just check the condition whether the class already exist if not add it.

let h1 = document.querySelector(".red-text");
let btn = document.querySelector("#btn");

function changeColor(){
    if(h1.classList.contains("black")){
      h1.classList.remove("black");
      h1.classList.add("white");
    }else{
         h1.classList.add("black");
      h1.classList.remove("white");
    }
}

btn.addEventListener("click", changeColor);
.black{
  background: black;
  color: red
}

.white{
  background: white;
}

Test

<button id="btn">Change Color</button>


text:
Q: Session expiring in Dialogflow I came to know that context expires in 15 minutes but is there any way to solve it manually i.e by storing the previous conversation in dB so can we handle that session expiring issue or else the whole conversation(output context) under that session ID will get clear and need to start from the first.
exports.fulfillmenttext = functions.https.onRequest((req,res) =>{
    const answer1 = req.body.Text;
    console.log("Text said by the user",answer1);
    const uid = answer1.substring(0,28);
    console.log("uid1 is",uid);
    const answer = answer1.substring(28);
    console.log("answer is",answer);
    const sessionId = uid;
    var count,questvalue;
    runSample();
    async function runSample(projectId = 'xxxxxxx') {
      const languageCode = 'en-US';
      const credentials = {
        client_email: 'xxxxxxxxxx',
        private_key: 'xxxxxxxxx'
      };
      //Instantiate a DialogFlow client.
      const dialogflow = require('dialogflow');
      const sessionClient = new dialogflow.SessionsClient({
        projectId,
        credentials,
      });
    // Define session path
      const sessionPath = sessionClient.sessionPath(projectId, sessionId);
      // The text query request.
      const request = {
        session: sessionPath,
        queryInput: {
          text: {
            text: answer,
            languageCode,
          },
        },
      };
      const responses =  await sessionClient.detectIntent(request);
      console.log('Detected intent');
      const result = responses[0].queryResult;
      let action = result.action;
      console.log("action is"+action);
      console.log(`  Query: ${result.queryText}`);
      console.log(`  Response: ${result.fulfillmentText}`);
      if (result.intent) {
        const question = result.fulfillmentText;
        console.log("question is",question);
        const actionHandlers = {
            'early': () => {
                console.log('earlyaction1', action);
                let name1 = JSON.stringify(result.parameters.fields.Name.stringValue);
                name1 = name1.toString().replace(/"/g,"");
                var data1 = {
                    Name: name1
                };
                var setDoc1 = admin.firestore().collection('User').doc(uid).collection("Popop").doc(uid).collection('Answers').doc('Earlyyears').update(data1);

            },
            'family': () => {
                console.log('familyaction1', action);
                let mname1 = JSON.stringify(result.parameters.fields.M_Name.stringValue);
                let mname_string = mname1.toString().replace(/"/g,"");
                var data20 = {
                    MName: mname_string
                };
                var setDoc20 = admin.firestore().collection('User').doc(uid).collection("Popop").doc(uid).collection('Answers').doc('Family').update(data20);

            }

        };
        if (action === 'early') {
             console.log('1');
             actionHandlers[action]();
        }
        else if (action === 'family') {
            console.log('2');
            actionHandlers[action]();
        }

        res.status(200).send({"question":result.fulfillmentText,"action":action});

      } else {
          console.log(`  No intent matched.`);
          res.status(400).send({"action":"empty"});
      }
    }
});

A: I stumbled upon this problem as well. My solution was to save the userID and save the contexts to Firestore.
UPDATE:
This is how I stored Dialogflow's contexts in Firestore:
function saveContexts(userId, contexts) {
let UID = userId;

//get all contexts + parameters

if (contexts === undefined) {
    console.log("contexts are undefined! returning");
    return false;
}
db.collection("user-contexts-prod").doc(UID).set({
    dateCreated: new Date(),
    contexts: JSON.stringify(contexts)
})
    .then(function () {
        console.log("success!");
        return true;
    })
    .catch(function (error) {
        console.log("error writing document..", error);
        return false;
    });
}

Retrieving user contexts:
async function getContexts(userId) {
    let UID = userId;
    let docRef = db.collection("user-contexts-prod").doc(UID);
    return docRef.get()
        .then(res => {
            if (res.exists) {
                let contexts = JSON.parse(res.data().contexts);
                console.log("<><> parsed contexts <><>: ");
                console.log(contexts);
                return contexts;
            } else {
                console.log(" UID DOES NOT EXIST!");
                return false;
            }
        })
}

You can set the contexts again by looping over them and using the contextClient to create new contexts. Or use this method to loop through the contexts and find the one you need:
contexts.forEach(function(context) {
                if (context.name === 'projects/{DIALOGFLOWPROJECTID}/agent/sessions/' + senderId + '/contexts/{CONTEXTNAME}') {
                    sessionData = context.parameters;
                    // all data that you saved in CONTEXTNAME is now available in the sessionData variable

                }
            });

Original answer:
Whenever a user started talking that didn't have any active contexts I check if I had the userID stored in my Database. If this user existed in my DB I retrieved the user information with all his data like this:
knownUser = await db.isKnownUser(senderId);
                if (knownUser) {
                    //knownUser
                    console.log("Known user");
                    let userData = db.getUserDataById(senderId)

                    //initialize contexts with data you need

                    payload = returningUser_useSameData();
                    messenger.send(payload, senderId);

                    dashbot.logBotMessage(payload.toString, sessionId, intentName);
                    break;

                } else {
                    //newUser
                    console.log("new user");

                    createContext('await_fillInTogether', '', sessionPath, sessionId, 1);
                    createContext('session', '', sessionPath, sessionId, 500);

                    payload = fillInTogetherNewUser();
                    messenger.send(payload, senderId);

                    dashbot.logBotMessage(payload.toString, sessionId, intentName);
                    break;
                }


text:
Q: Would Injecting dependencies in C# as default parameters be a bad practice? Given the (old) debate over whether Singletons are overused/abused/are worth it - would it be a bad idea to inject the dependencies as default parameters? In this way, we could get rid of defining singletons for the dependency container registry for the corresponding interfaces - while still leaving the objects in question testable - all one needs to do is to explicitly inject a mock as the dependency when Unit Testing such classes.
Example:
public class Foo
{
    IDoSomething x;
    Foo(IDoSomething x = null)
    {
        this.x = x ?? new DoSomething()
    }
}

public class DoSomething : IDoSomething
{
   ...
}

in Program.cs
services.AddSingleton(IDoSomething, DoSometing);

This way I am rid of holding singletons throughout my app, without losing testability.
public class FooTests
{
    Foo SUT;
    Mock<Foo> FooMock;
    FooTests()
    {
        FooMock = new Mock<Foo>();
        FooMock.Setup(...);
        SUT = new Foo(FooMock.Object);
    }
}

Giving it a second thought, if I require a singleton (if I need to assure no 2 instances exist for this object) than it's more like a matter of defining the lifetime of that instance (singleton, scoped, transaction). In other words, there should be nothing wrong in injecting a dependency as a mandatory parameter - and properly registering the instantiation type at the dependency container.

A: First things first: what you have heard is correct, the Singleton pattern is an anti-pattern that is often abused to gain what the pattern considers it's "cost" or "disadvantages", but being able to deflect blame in a code review and say "oh, but it's the pattern".
But the "Singleton Lifetime" is not the same as the "Singleton Pattern". Specifically, it does not have the same drawbacks and is therefore not abused by people this way.
So in short, using Singleton Lifetime in your Dependency Injection Container is perfectly fine.
So your actual question: you can do this, but it is it worthwhile? You obviously get some of the advantages of dependency injection, because you can inject dependencies. However, you still get tight coupling between your components, because they know each other.
I have used this "pattern" in the past, when I had no use for a full dependency injection container, because each solution would only contain three classes. And yes, those were coupled tightly this way. But it was three. Very  clearly laid out. But in turn we had about a hundred of those assemblies. Putting in a hundred dependency injection containers, each with exactly 2 registrations would only have complicated things.
So to summarize: normally, you should not do this. Not because Singleton is an anti-pattern (it is, but it is not used here), but because you do not get the full benefits since you still have very tight coupling of components. Only if you are sure you do not need this benefit, you can do this. And it will work well for those rare cases. If in doubt, you probably don't have such a case.

A: In any reasonably sized codebase, the nested DI parameters are going to explode, which is going to bite you when you want to write those concrete constructors like that. Even if reasonable on a whiteboard, tyour idea does not pass the smell test in actual production code.
Based on that alone, it's probably worth letting go of this idea.
If you're going to be using singletons (which I advise against but never mind that), using a DI container is a better way to do so.
However, that doesn't explain why you're trying to make these optional parameters. What would be the benefit of deciding the concrete type DoSomething in the constructor, as opposed to deciding it when registering your DI container?
If multiple classes depend on the same dependency, you have to repeat the same concrete class over and over.
I don't see any upside to this. It seems to me that the only thing you're achieving is that you sidestep the DI container in favor of manually mapping (and tightly coupling) the concrete dependency types. That's a step in the wrong direction.

A: There's no singleton in your example, but what you are doing isn't bad per se.
Its fairly common practice to provide default implementations where there is going to be tight coupling regardless. Obviously you are not quite as decoupled, but as long as the default class is small the downside is small or nothing and you gain convenience of use.


text:
Q: Is it Good to make so many methods for even small task also? I want to know that many developers do the same thing as to decrease the size of long method , they create so many small sized methods from it for the same task. I want to know that does it affects the performance of an application or not?

A: Functions should normally be short, between 5-15 lines is my personal "rule of thumb" when coding in Java or C#. This is a good size for several reasons:

*

*It fits easily on your screen without scrolling

*It's about the conceptual size that you can hold in your head

*It's meaningful enough to require a function in its own right (as a
standalone, meaningful chunk of logic)

*A function smaller than 5 lines is a hint that you are perhaps
breaking the code up too much (which makes it harder to read /
understand if you need to navigate between functions). Either that or
your're forgetting your special cases / error handling!

But I don't think it is helpful to set an absolute rule, as there will always be valid exceptions / reasons to diverge from the rule:

*

*A one-line accessor function that performs a type cast is clearly
acceptable in some situations.

*There are some very short but useful functions (e.g. swap as
mentioned by user unknown) that clearly need less than 5 lines. Not a
big deal, a few 3 line functions don't do any harm to your code base.

*A 100-line function that is a single large switch statement might be
acceptable if it is extremely clear what is being done. This code can
be conceptually very simple even if it requires a lot of lines to
describe the different cases. Sometimes it is suggested that this
should be refactored into separate classes and implemented using
inheritance / polymorphism but IMHO this is taking OOP too far - I'd
rather have one big 40-way switch statement than 40 new classes to
deal with.

*A complex function might have a lot of state variables that would get
very messy if passed between different functions as parameters. In
this case you could reasonably make an argument that the code is
simpler and easier to follow if you keep everything in a single large
function (although as Mark rightly points out this could also be a
candidate for turning into a class to encapsulate both the logic and
state)

*Sometimes smaller or larger functions have performance advantages
(perhaps because of inlining or JIT reasons as Frank mentions). This
is highly implementation dependent, but it can make a difference -
make sure you benchmark!

So basically, use common sense, stick to small function sizes in most instances but don't be dogmatic about it if you have a genuinely good reason to make an unusually big function.
Taken from here.

A: It's impossible to say in the general case, but no, probably not.
For one thing: Method calls are really, really fast.
For another, the JVM monitors the work done by your code and when it sees a "hot spot" (a part of the code that gets run a lot), it aggressively optimizes that part of the code. One of the ways it does that is by inlining methods where possible — that is, by relocating the code from the method into the method that's calling it. At which point, the performance is the same as if you had put the code there yourself. So you get the maintenance and testability benefits of small methods, but the benefit of inlined code if it's useful to inline it.
Again, though, it cannot be answered in the general case. If you have a specific performance problem, benchmark to see whether it matters in that specific situation.


text: Q: In spring based application database is incrementing id by 50 not by 1 in postgresql? I wrote simple CRUD application using Spring MVC + JPA + Postgresql. When I add data to database manually(using sql query in pgAdmin) the Id sequence increments by 1. But when I add data to my database using my application, the Id sequence increments by 50. Why? How can I configure this sequence to increment by 1 when adding data using application?


text:
Q: Testing a remote web service with soapUI I have a Javax web service deployed in a remote Linux machine within a JBoss ESB container.  I am able to test the web service using soapUI on the same machine as where the service is deployed. The WDSL URI I used was something like http://127.0.0.1:8080/abcd/abcd?wsdl.
What I would like to do is to be able to test the same service from another machine using soapUI. I tried replacing 127.0.0.1 with the IP address of the machine where the service is deployed. This does not seem to work. Can someone tell me what I am missing here?
Thanks.

A: a sum of things could go wrong there - as already mentioned by the others the firewall is blocking access for the given (address, port) pair. Another thing that happened to me was that the WSDL was generated using the name of the machine it was deployed on and whenever I was trying to call the service from a different machine it was complaining that I cannot find the given machine.

A: You need to test network connectively.  One tool you can use is plain old telnet.  If you telnet to the ip/port combo of the web server, you will get a response (an HTTP error).  For example:
$ telnet 192.168.0.10 8080

If you get nothing then there is almost certainly a firewall blocking access.
If you are convinced that no firewall is blocking you, the other possibility is that the web server is only bound to the local network adapter (127.0.0.1) and not the other network adapters (ethernet/wifi).  This is very unlikely however.


text:
Q: Office 365 EWS application with OAuth authentication and impersonation - Error 401 I was to trying to build an app that connect to EWS with OAuth and application persmissions using the following example code from Microsoft (https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth)
I registered my application in Azure AD, set the Application permissions to full_access_as_app and generated a client secret.
But always when i start the app i get a 401 error code (Error: Microsoft.Exchange.WebServices.Data.ServiceRequestException: The request failed.)
When i use the code for delegated permissions and entered my username and password it works, but i need the feature tu run my app in background with ImpersonatedUserId.
using System;
using System.Configuration;
using Microsoft.Exchange.WebServices.Data;
using Microsoft.Identity.Client;

namespace ews_oauth_samples
{
    class Program
    {
        static void Main(string[] args)
        {
            MainAsync(args).Wait();

            if (System.Diagnostics.Debugger.IsAttached)
            {
                Console.WriteLine("Hit any key to exit...");
                Console.ReadKey();
            }
        }

        static async System.Threading.Tasks.Task MainAsync(string[] args)
        {
            // Configure the MSAL client to get tokens
            var ewsScopes = new string[] { "https://outlook.office.com/.default" };

            var app = ConfidentialClientApplicationBuilder.Create(ConfigurationManager.AppSettings["appId"])
                .WithAuthority(AzureCloudInstance.AzurePublic, ConfigurationManager.AppSettings["tenantId"])
                .WithClientSecret(ConfigurationManager.AppSettings["clientSecret"])
                .Build();

            AuthenticationResult result = null;

            try
            {
                // Make the interactive token request
                result = await app.AcquireTokenForClient(ewsScopes)
                    .ExecuteAsync();

                // Configure the ExchangeService with the access token
                var ewsClient = new ExchangeService();
                ewsClient.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
                ewsClient.Credentials = new OAuthCredentials(result.AccessToken);

                //Impersonate the mailbox you'd like to access.
                ewsClient.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "test@demotenant.onmicrosoft.com");

                // Make an EWS call
                var folders = ewsClient.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(10));
                foreach (var folder in folders)
                {
                    Console.WriteLine($"Folder: {folder.DisplayName}");
                }
            }
            catch (MsalException ex)
            {
                Console.WriteLine($"Error acquiring access token: {ex.ToString()}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.ToString()}");
            }
        }
    }
}

A: It is easy to miss something when you register the application, so try a new application and make sure you follow the additional steps to use Application permissions.
If the app Id, tenant Id and client secret are all correct you should not get the 401 error if you use the access token within 1 hour.
The 401 error is "normal" after the access token has expired. Your application needs to call AcquireTokenForClient to get a fresh token at least once an hour.
Even when the token is still fresh, the FindItems will probably fail on user "test@demotenant.onmicrosoft.com", with a different error: "The SMTP address has no mailbox associated with it".


text:
Q: Why does Method access seem faster than Field access? I was doing some tests to find out what the speed differences are between using getters/setters and direct field access. I wrote a simple benchmark application like this:
public class FieldTest {

    private int value = 0;

    public void setValue(int value) {
        this.value = value;
    }

    public int getValue() {
        return this.value;
    }

    public static void doTest(int num) {
        FieldTest f = new FieldTest();

        // test direct field access
        long start1 = System.nanoTime();

        for (int i = 0; i < num; i++) {
            f.value = f.value + 1;
        }
        f.value = 0;

        long diff1 = System.nanoTime() - start1;

        // test method field access
        long start2 = System.nanoTime();

        for (int i = 0; i < num; i++) {
            f.setValue(f.getValue() + 1);
        }
        f.setValue(0);

        long diff2 = System.nanoTime() - start2;

        // print results
        System.out.printf("Field Access:  %d ns\n", diff1);
        System.out.printf("Method Access: %d ns\n", diff2);
        System.out.println();
    }

    public static void main(String[] args) throws InterruptedException {
        int num = 2147483647;

        // wait for the VM to warm up
        Thread.sleep(1000);

        for (int i = 0; i < 10; i++) {
            doTest(num);
        }
    }

}

Whenever I run it, I get consistent results such as these: http://pastebin.com/hcAtjVCL
I was wondering if someone could explain to me why field access seems to be slower than getter/setter method access, and also why the last 8 iterations execute incredibly fast.

Edit: Having taken into account assylias and Stephen C comments, I have changed the code to http://pastebin.com/Vzb8hGdc where I got slightly different results: http://pastebin.com/wxiDdRix .

A: The explanation is that your benchmark is broken.
The first iteration is done using the interpreter.
Field Access:  1528500478 ns
Method Access: 1521365905 ns

The second iteration is done by the interpreter to start with and then we flip to running JIT compiled code.
Field Access:  1550385619 ns
Method Access: 47761359 ns

The remaining iterations are all done using JIT compiled code.
Field Access:  68 ns
Method Access: 33 ns

etcetera

The reason they are unbelievably fast is that the JIT compiler has optimized the loops away.  It has detected that they were not contributing anything useful to the computation.  (It is not clear why the first number seems consistently faster than the second, but I doubt that the optimized code is measuring field versus method access in any meaningful way.)

Re the UPDATED code / results: it is obvious that the JIT compiler is still optimizing the loops away.


text:
Q: In an irregular trapezium of ABCD with diagonals that intersect at point E in the middle, are all the triangles similar?
In this diagram above, let's imagine this was an irregular trapezium. This means that none of the four sides are the same length.
I know that AB is parallel to DC.
<dec = bea =  vertically opposite
<abe = cde = alternate angles
Therefore by AA we can show that these triangles are similar.
Without measuring or anything is it possible for <ade and <bce to be similar?
My understanding is that they would be similar because if AD = BC then it would be congruent. But because it is an irregular trapezium of each side having varying lengths then it would be similar because the angle should be the same?

A: Since $\angle AED = \angle BEC$, the two triangles $AED$ and $BEC$ are similar if and only if:

*

*either $\angle DAE = \angle BCE$,

*or $\angle DAE = \angle CBE$.

In the first case, $AD$ is parallel to $BC$ and we get a parallelogram.
In the second case, we get a cyclic quadrilateral, and it is easy to see that a cyclic trapezium is necessarily isosceles.
In both cases, we would have $|AD| = |BC|$, which is excluded by assumption.


text:
Q: How is bash commandline stdin propagated to child process I have a script (file_redirection.sh), where I have tried various combinations to get what I want:
#!/bin/bash
echo "cat " $*
echo "cat $*"
echo "cat $@"
echo "cat " $@

I would like to be able to run
file_redirection.sh < tmp_file

And have it show
"cat < tmp_file"

Is that possible?

A: No, that's not possible.  The < on your command line is interpreted by the shell before your script ever runs.  You need to escape the < to get it into your script.  For example:
file_redirection.sh \< tmp_file

will generate the output you're looking for, but does not do any file redirection.

A: You ask "how it works".  UNIX processes are created using an action known as fork.  This takes a copy of the current process and copies it almost exactly as it is, in a very efficient manner.  Copying also includes the file descriptor table, where stdin, stdout, stderr, live.
When you do redirection, the shell forks, then alters it's own file descriptor (fd) table in the child.  It then runs the new script with the same fd table in the same process.  Using conventional mechanisms, the only thing that a process can check is if stdin is connected to a terminal or not.  In C it uses isatty() and in bash you can if [[ -t 0 ]]... (zero is the fd for stdin).
In Linux (if you are using Linux) you have an additional option, the fd table is presented in a readable form in /proc/$$/fd ($$ give the current proces id).  ls -l /proc/$$/fd and you will see what I mean.
So, am I redirected?
if [[ -t 0 ]]   # is stdin a terminal?
then
    suffix=""
else
    line=$(ls -l /proc/$$/fd/0)
    file="${line##*-> }"

    suffix="< $file"
fi

echo "cat $suffix"

On the commandline:
/home/user1$ file_redirection.sh < tmp_file
cat < /home/qa/tmp_file

BUT.  Why on earth do you want to do that?

A: Use this:
file_redirection.sh "< tmp_file"
and in your file this:
echo "cat $1"
OR
file_redirection.sh \< tmp_file
and in your file this:
echo "cat $*"


text:
Q: No rights to view file as member of root group I am in the group root who owns a file and all the directories above. Why do I have no access to this file? CentOS 7
$ ls /etc/systemd/system | grep parts.service

ls: cannot access /etc/systemd/system/parts.service: Permission denied
-????????? ? ? ? ?            ? parts.service

With SUDO:
$ sudo ls /etc/systemd/system | grep parts.service

-rw-rw-rw-  1 root root  563 Feb 13 09:59 parts.service

Checking for an ACL:
$ sudo getfacl /etc/systemd/system/parts.service
getfacl: Removing leading '/' from absolute path names
# file: etc/systemd/system/parts.service
# owner: root
# group: root
user::rw-
group::rw-
other::rw-

My groups:
$ groups
root wheel docker poweruser

Parent directories
drwxr-xr-x  155 root root 12288 Jul 17 09:04 etc/
drwxr-xr-x    4 root root      151 Nov 11  2019 systemd/
drw-rw-r--   19 root root  4096 Jun 19 18:14 system/

A: sudo is used to verify that you are the user with which you are logged. you can access root files with your user, but you have to tell your PC that you want to acces files from the root group


text:
Q: Forward to a servlet from another servlet or from a filter Usually I forward to a jsp or to a mapped URL from a servlet, and internet is full of such examples. But I need to forward a request to an internal servlet. For example by using its full class name, without mapping that servlet to an URL. How to forward a request to an internal servlet from another servlet, or from a filter?

A: As Shadab commented, I think you should use @WebServlet annotation (and RequestDispatcher), for example:
@WebServlet(urlPatterns = { "/sample" })
public class SampleServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    RequestDispatcher dispatch = req.getRequestDispatcher( "/forwardpath");
    dispatch.forward(req, res);
}

SampleServlet -> ForwardedServlet
@WebServlet(urlPatterns = { "/forwardpath" })
public class ForwardedServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    ...
}

A: The method you want is RequestDispatcher   getNamedDispatcher(String name); that  returns a RequestDispatcher object that acts as a wrapper for the named servlet.
And the javadoc for ServletConfig.getServletName() says:

The name may be provided via server administration, assigned in the web application deployment descriptor, or for an unregistered (and thus unnamed) servlet instance it will be the servlet's class name.

You you just have to do:
getServletContext().getNamedDispatcher("full.class.name.for.new.servlet");


text:
Q: Strange matrix multiplication behavior in Matlab I noticed strange behavior of some calculations in Matlab.
Matlab code listing:
% w_x, w_y, w_z are scalars
Q_0 = [0.788604; 0.41303067; 0.41303067; 0.192129]        % 4d vector
A = [ 0 -w_x -w_y -w_z; w_x 0 w_z -w_y; w_y -w_z 0 w_x; w_z w_y -w_x 0 ]       % 4x4 matrix
w = sqrt(w_x^2 + w_y^2 + w_z^2)        % scalar

Q_w1 = (cos(w*t/2.) + sin(w*t/2.) * 1./w * A ) * Q_0             % 4d vector
Q_w2 = (cos(w*t/2.) * Q_0+ (sin(w*t/2.) * 1./w * A)* Q_0 )       % 4d vector

I've got diffenet values of Q_w1 and Q_w2. Do theese sentenses equal in terms of math?  For me, it seems like they do. Is it just a Matlab bug?

A: When you have $+$ in the two lines, it's not doing the same thing in both places. Under the current definition, cos(w*t/2.) is a number, and the $+$ operator in the code
Q_w1 = (cos(w*t/2.) + sin(w*t/2.) * 1./w * A ) * Q_0
adds that real number to every element in the matrix on the right. The second code multiplies the matrix and vector beforehand, so the behaviour is different.
If you replace the first line of code with
Q_w1 = (cos(w*t/2.)*eye(4) + sin(w*t/2.) * 1./w * A ) * Q_0
then it gives the same output as line 2.

So the key difference is that adding a number to a matrix is not the same as adding the scalar times the identity matrix.
Note: I tested this in Octave, not Matlab - but AFAIK, they treat these the same.