text:
Q: How to manage Hibernate SessionFactory Beans in the following scenario of my spring boot application? Following is my Bean configuration
@Bean
        public SessionFactory getSessionFactoryBean(@Autowired(required = true) HikariDataSource dataSource) {

        LocalSessionFactoryBean sessionFacBean = new LocalSessionFactoryBean();
        sessionFacBean.setDataSource(dataSource);
        sessionFacBean.setPackagesToScan("com.project");
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        sessionFacBean.setHibernateProperties(hibernateProperties);
        try {
            sessionFacBean.afterPropertiesSet();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sessionFacBean.getObject();

    }

I use this 'SessionFactory' Bean in my controller class. As far as I know, spring creates a new thread with new instance of a controller class during multiple requests. In that case, a new instance of 'SessionFactory' bean will also be autowired to the controller (Explained in this link). The whole point of this sessionFactory is ConnectionPooling, If the sessionFactory is created for each request then How does the connection pooling works properly.
I have the similar situation for other beans too, HttpClient and MongoTemplate with connection pooling.
Please feel free to edit the question if my understanding is wrong.I'm a newbie to all this.

A: *

*You should have only one SessionFactory for your application. It should be configured during application startup.

*Each thread should have their own Session. There are various approaches how to use a Session with requests:
https://stackoverflow.com/a/37526397/3405171

In that case, a new instance of 'SessionFactory' bean will also be autowired to the controller

This is incorrect. @Bean annotation has singleton scope as default. So you will have only one SessionFactory for all threads and controllers.

The whole point of this sessionFactory is ConnectionPooling

To speak more correctly a DataSource is responsible for a connection pool. SessionFactory is for Hibernate specific stuff like persistent classes metadata, SQL generating etc.
Also keep in mind that Hibernate has  org.hibernate.context.spi.CurrentSessionContext which controls how the Session is bounded to the thread.


text:
Q: scrape data from interactive map I'm trying to get the data from each pop-up on the map. I've used beautifulsoup in the past but this is a first getting data from an interactive map.
Any push in the right direction is helpful. So far i'm returning blanks.
Here's what i have, it isn't substantial...
from bs4 import BeautifulSoup as bs4
import requests

url = 'https://www.oaklandconduit.com/development_map'
r = requests.get(url).text
soup = bs4(r, "html.parser")
address = soup.find_all("div", {"class": "leaflet-pane leaflet-marker-pane"})

Updated
On recommendations, I went with parsing the javascript content with re using the script below. But loading into json returns an error
import requests, re
url = 'https://ebrrd.nationbuilder.com/themes/3/58597f55b92871671e000000/0/attachments/14822603711537993218/default/mapscript.js'
r = requests.get(url).content
content = re.findall(r'var.*?=\s*(.*?);', r, re.DOTALL | re.MULTILINE)[2]
json_content = json.loads(content)

A: The interactive map is loaded through and driven by JavaScript, therefore, using the requests library is not going to be sufficient enough to get the data you want because it only gets you the initial response (in this case, HTML source code).
If you view the source for the page (on Chrome: view-source:https://www.oaklandconduit.com/development_map) you'll see that there is an empty div like so:

This is the placeholder div for the map.
You'll want to use a method that allows the map to load and for you to programmatically interact with it. Selenium can do this for you but will be significantly slower than requests because it has to allow for this interactivity by launching a programmatically driven browser.

A: Continued with regex to parse map contents into Json. Here's my approach with comments if helpful to others.
import re, requests, json
url = 'https://ebrrd.nationbuilder.com/themes/3/58597f55b92871671e000000/0/attachments/14822603711537993218/default' \
      '/mapscript.js'
r = requests.get(url).content
# use regex to get geoJSON and replace single quotes with double
content = re.findall(r'var geoJson.*?=\s*(.*?)// Add custom popups', r, re.DOTALL | re.MULTILINE)[0].replace("'", '"')
# add quotes to key: "type" and remove trailing tab from value: "description"
content = re.sub(r"(type):", r'"type":', content).replace('\t', '')
# remove ";" from dict
content = content[:-5]
json_content = json.loads(content)

also open to other pythonic approaches.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $.ajax post timeout after 90 Secs $.ajax post and timeout when the action takes longer than 90 secs. Is there way to increase the timeout more than 90 secs. Success function is called if the action return before 90 secs.
I tried using timeout setting did not make any difference. This timeout works if it is less than 90 secs.
I also tried adding [AsyncTimeout(120000)] attribute to action "ActionName" mentioned in the jQuery below. Still get timeout after 90 secs.
Below is the $.ajax jQuery:
$.ajax({
      url: '@Url.Action("ActionName", "ControllerName")',
      data: $(form).serialize(),
      datatype: 'html',
      type: 'POST',
      success: function(result) {
        var $myDialog1 = $('

')
          .html("Successfully completed.")
          .dialog({
            autoOpen: false,
            modal: true,
            width: 400,
            closeOnEscape: false,
            title: "CONFIRMATION",
            buttons: {
              "OK": function() {
                $(this).dialog("close");
                $("#DivName").html(result);
              }
            }

          });
        $myDialog1.dialog('open');
      }


text:
Q: Access to a drive through a VPN I bought a hosted VPS (with Windows Server 2012) on which i would like to do two things:
- Run a client/server application
- Map as a letter a drive
The idea is to connect through a VPN to secure the data transfer, and to let me access remotely to my files.
Do I need a DC ? What about the certificate ?
What are the essential steps you could recommend me to do in order to set up ?
Thanks in advance
Thomas

A: It's easy. First connect VPN and then connect a share with the Explorer.exe.
In a VPN everything works like in a LAN.

A: Depending on how many users are connecting to the server, I would not setup a DC unless you need one for other reasons.
Create any needed user accounts for access to the files.
Create the file share(s) and assign permissions as needed.
Setup the VPN access for the user(s).
Setup the client VPN side.
Map the network drive using the server's local IP Address. If you want to use hostname, you will either need some sort of DNS server (and settings on the client to use the DNS server) or HOSTS file redirection.
Now to look at your files, as FrankStein said, just connect to the VPN and access files through Windows Explorer. The traffic is encrypted in transit through the VPN tunnel but will be accessible to any application on your computer as if it was on the LAN.


text:
Q: PCA - taking difference with mean What is the intuition behind number 1 and 2 when it comes to considering mean? And how will this affect performance and accuracy?
Number 1:
    pca = decomposition.PCA(n_components=4)
    X_centered = X - X.mean(axis=0)
    pca.fit(X_centered)
    X_pca = pca.transform(X_centered)

Number 2:
    pca = decomposition.PCA(n_components=4)
    pca.fit(X)
    X_pca = pca.transform(X)

Thanks in advance

A: It will be the same. In a way, PCA find a set of basis vectors, which are orthogonal to each and maximize the variance in a set of points projections onto them. PCA therefore has rotation and translation symmetry. Therefore you will have identical PCA results whenever you shift your matrix (which is what subtraction of the mean essentially does) to not.

A: If some variables have a large variance and some small, PCA (maximizing variance) will load on the large variances. For example, if you change one variable from km to cm (increasing its variance), it may go from having a little impact to dominating the first principle component. If you want your PCA to be independent of such rescaling, standardizing the variables will do that. On the other hand, if the specific scale of your variables matters (in that you want your PCA to be on that scale), maybe you don't want to standardize.


text:
Q: I can´t open dialog an mattermost?
When i send a request to mattermost API. I get response error code 400(Bad Request).
  I am using the language of c #, and this serializing an anonymous class to generate the format.

{
    "trigger_id":
         "a2k0eGhveDN3M2dtN2I0Y3c3b3BobXBoZW86bXlubmk3eGg4M2Y3eDhoMThucjE0c3dvb3I6MTU1NTk1MTg3NjAxNjpNRVFDSUU4VDFqYmNSVGswdDZRQVVFU3haZk5URTg3MUhMT1ozK003aWdsQ01nckhBaUFac290SncwMmFSSkRWNEQyTFN0eXpGY0QySFREeVI2SVg3clY3ejVlMjFnPT0=",
               "url": "https://myapi.com/api/values/service",
               "dialog": {
                 "callback_id": "123",
                 "title": "Form Test",
                 "icon_url": "http://www.mattermost.org/wp-content/uploads/2016/04/icon.png",
                 "elements": [
                   {
                     "display_name": "Display Name",
                     "name": "Name",
                     "type": "text",
                    "subtype": "",
                     "default": "default text",
                    "placeholder": "Placeholder",
                    "help_text": "This is a test regular input",
                    "optional": false,
                     "min_length": 0,
                     "max_length": 0,
                    "data_source": "",
                    "options": null
                  },
                   {
                    "display_name": "Email",
                     "name": "youremail@email.com",
                     "type": "text",
                     "subtype": "",
                    "default": "default text",
                     "placeholder": "placeholder@bladekick.com",
                     "help_text": "This is a test regular input",
                 "optional": false,
                  "min_length": 0,
                     "max_length": 0,
                     "data_source": "",
                   "options": null
                  },
                   {
                    "display_name": "Number",
                     "name": "Number",
                     "type": "text",
                     "subtype": "number",
                     "default": "",
                     "placeholder": "",
                     "help_text": "",
                     "optional": false,
                     "min_length": 0,
                     "max_length": 0,
                     "data_source": "",
                     "options": null
                   }
                 ],
                 "submit_label": "Enviar",
                 "notify_on_cancel": false,
                 "state": "Default state"
        }
    }

This is my json that i send
Help me please with this error.
  Attachment Picture
  Code 400

A: Well, I solved it. My error was the way I made the HTTP request.
What I was doing delayed the request and the "trigger_id" expired. Remember that the "trigger_id" has a useful life of 3 seconds.
My recommendation is to try to use different ways to send the request because the JSON that I send (it's the same as yours) is correct.
Another observation from me was that it apparently did not send it properly as an "application / json"


text:
Q: Is there a way to update Win10 OS build from 10586.318 to higher by update? Is there a way to update Win10 OS build from 10586.318 to higher by update?
A few hours back I had automatic updates but the build is the same. Moreover, when I checked for updates manually there was nothing.
In this case, I have no idea how could I have higher builds (I need the build 14317.1000 or higher to install the new Windows Subsystem for Linux - WSL).
By the way, here's a new Facebook group for WSL support.

A: There basically 2 options to do so:
Option 1:
Join the insider Program with your Microsoft account and switch to Fast Ring

After 1 day you should get the option to update to Redstone 1 preview build.
Option 2:
download the ISO from Build 14332, mount the ISO inside your current Windows 10, run setup.exe and select upgrade (keep all software/data or the option that you like).


text:
Q: Android: android.content.res.Resources$NotFoundException: String resource ID #0x5 I get the exception from the title when I run my app. What it does is it has a .txt file with words for a Hangman game and I think the exception is thrown when accessing the file. My file, cuvinte.txt is located into /assets/. Here is my code (i skipped the layout/xml part, which works fine):
public void onCreate() {
    // all the onCreate() stuff, then this:
    try {
        AssetManager am = this.getAssets();
        InputStream is = am.open("cuvinte.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(is);
        BufferedReader b = new BufferedReader(inputStreamReader);
        String rand;
        while((rand=b.readLine())!=null){
            cuvinte.add(rand);
        }
    } catch (IOException e) {
        Toast.makeText(this, "No words file", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

    newGame(newG);
}

public void newGame(View view){
    Random rand = new Random();
    String stringCuvant = cuvinte.get(rand.nextInt(cuvinte.size()));
    cuvant.setText("");
    System.out.println(stringCuvant);
    for(int i = 0; i< stringCuvant.length(); i++){
        cuvant.append("_ ");
    }
    incercari.setText(valIncercari);
}

The function newGame() is called both when the new game button is pressed and at the beginning of the activity, in the onCreate() function.

A: (Just assumption, less info of Exception stacktrace)
I think,  this line, incercari.setText(valIncercari); throws Exception
because valIncercari is int
So it should be,
incercari.setText(valIncercari+"");

Or
incercari.setText(Integer.toString(valIncercari));

A: Another scenario that can cause this exception is with DataBinding,
that is when you use something like this in your layout
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="model"
            type="point.to.your.model"/>
    </data>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@{model.someIntegerVariable}"/>

</layout>

Notice that the variable I'm using is an Integer and I'm assigning it to the text field of the TextView. Since the TextView already has a method with signature of setText(int) it will use this method instead of using the setText(String) and cast the value. Thus the TextView thinks of your input number as a resource value which obviously is not valid.
Solution is to cast your int value to string like this
android:text="@{String.valueOf(model.someIntegerVariable)}"

A: Sometime this happened due to not fond any source like if i want to set a text into a textview from adapter then i should use
 textView.setText(""+name);

If you write something like
 textView.setText(name);

this will not work and sometime we don't find the resource from the string.xml file then this type of error occur.

A: Just wanted to point out another reason this error can be thrown is if you defined a string resource for one translation of your app but did not provide a default string resource.
Example of the Issue:
As you can see below, I had a string resource for a Spanish string "get_started". It can still be referenced in code, but if the phone is not in Spanish it will have no resource to load and crash when calling getString().
values-es/strings.xml
<string name="get_started">SIGUIENTE</string>

Reference to resource
textView.setText(getString(R.string.get_started)

Logcat:
06-11 11:46:37.835    7007-7007/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.app.test PID: 7007
android.content.res.Resources$NotFoundException: String resource ID #0x7f0700fd
        at android.content.res.Resources.getText(Resources.java:299)
        at android.content.res.Resources.getString(Resources.java:385)
        at com.juvomobileinc.tigousa.ui.signin.SignInFragment$4.onClick(SignInFragment.java:188)
        at android.view.View.performClick(View.java:4780)
        at android.view.View$PerformClick.run(View.java:19866)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution to the Issue
Preventing this is quite simple, just make sure that you always have a default string resource in values/strings.xml so that if the phone is in another language it will always have a resource to fall back to.
values/strings.xml
<string name="get_started">Get Started</string>

values-en/strings.xml
<string name="get_started">Get Started</string>

values-es/strings.xml
<string name="get_started">Siguiente</string>

values-de/strings.xml
<string name="get_started">Ioslegen</string>

A: This problem mostly occurs due to the error in setText() method
Solution is simple put your Integer value by converting into string type
as
textview.setText(Integer.toString(integer_value));

A: Using DataBinding and setting background to the EditText with resources from the drawable folder causes the exception.
<EditText
    android:background="@drawable/rectangle"
    android:imeOptions="flagNoExtractUi"
    android:layout_width="match_parent"
    android:layout_height="45dp"
    android:hint="Enter Your Name"
    android:gravity="center"
    android:textColorHint="@color/hintColor"
    android:singleLine="true"
    android:id="@+id/etName"
    android:inputType="textCapWords"
    android:text="@={viewModel.model.name}"
    android:fontFamily="@font/avenir_roman" />

Solution
I just change the background from   android:background="@drawable/rectangle" to  android:background="@null"
Clean and Rebuild the Project.

A: Sometime we add resources in dimen or any other recourse folder, we forget to add dp.
<dimen name="exercise_value">4</dimen>

For example, I was facing this issue because I forgot to add dp in my value.
Then I changed it into
<dimen name="exercise_value">4dp</dimen> <br>

Boom. Error is gone.

A: In order to solve it I had to replace:
Toast.makeText(this, my_int_var, Toast.LENGTH_SHORT).show();

with this:
Toast.makeText(this, String.valueOf(my_int_var), Toast.LENGTH_SHORT).show();

A: You are assigning a numeric value to a text field. You have to convert the numeric value to a string with:
String.valueOf(variable)


text:
Q: How can I detect in angular, when a pdf is loaded? I am using the  tag to dynamically load pdfs. In my real project, I have heavy pdfs and that is why I would like to know if there is any way to detect when the pdf finishes loading and is ready.
how can I do it?
this is my live code:
https://stackblitz.com/edit/angular-vrak1m?file=src/app/app.component.ts
<object *ngIf="link" [data]="link | safepipe" type="application/pdf" width="100%" height="100%"> </object>
{{link}}

<button (click)="link1()">pdf1</button>
<button (click)="link2()">pdf2</button>

A: You can use the load method on object
template:
<object *ngIf="link" [data]="link | safepipe" type="application/pdf" width="100%" height="100%" (load)="loaded($event)"> </object>
    {{link}}

<button (click)="link1()">pdf1</button>
<button (click)="link2()">pdf2</button>

and define the method in ts
class:
loaded(e){
  console.log(e);
  // Do your thing here.
}


text:
Q: org.hibernate.exception.GenericJDBCException: could not execute statement in hibernate I am trying to use embeddable annotation to store different values in one object to be persisted in one table.
I have two classes:
userDetails:
package org.hibernet.src;
@Entity
@Table (name="UserDetails")
 public class userDetails {
 @Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
@Temporal(TemporalType.DATE)
private Date dob;
public Date getDob() {
    return dob;
}
public void setDob(Date dob) {
    this.dob = dob;
}
private String userName;
@Embedded
private Address address;

public Address getAddress() {
    return address;
}
public void setAddress(Address address) {
    this.address = address;
}
public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}

}

*Address class which is embeddable class:
 @Embeddable

 public class Address {

@Column(nullable=true)
private String street;

@Column(nullable=true)
private String city;

 @Column(nullable=true)
 private String state;

public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
    return city;
}
 public void setCity(String city) {
    this.city = city;
 }
public String getState() {
return state;
}
public void setState(String state) {
    this.state = state;
}

}
this is my main class:
public static void main(String[] args) {

userDetails user = new userDetails();
Address add = new Address();

user.setUserName("Dipesh");
user.setDob(new Time(0));
add.setCity("vadodara");
add.setState("gujarat");
add.setStreet("raopura");

SessionFactory sessionfactory = new
 Configuration().configure().buildSessionFactory();
Session session = sessionfactory.openSession();
session.beginTransaction();
session.save(user);
session.save(add);
/*user = (userDetails)session.get(userDetails.class, 6);*/

session.getTransaction().commit();
session.close();

}
I was trying to store the data but it was showing:
   ERROR: Field 'pincode' doesn't have a default value
   Exception in thread "main" org.hibernate.exception.GenericJDBCException:
    could not execute statement

      at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at org.hibernate.test.userTest.main(userTest.java:36)
Caused by: java.sql.SQLException: Field 'pincode' doesn't have a default
value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1837)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1961)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2543)
at
    com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1737)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2022)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1940)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1925)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 22 more

I had pincode in my address but it was showing an error so i removed it but still it showing that error.
Please help me to solve it.

A: The table in your db has a field pincode for which you've not defined a default value and is not nullable. However, your entity has no mapping for that field and you are not sending a value  for this field. Thus, java.sql.SQLException: Field 'pincode' doesn't have a default
value

A: 1) Adapt your entity that it includes the field "pincode"
@Entity
@Table (name="UserDetails")
public class userDetails {
...
@Column(name="pincode", columnDefinition="Number(10) default '34562'")
int pincode;
...

2) or alter the underlying table so that the pincode field has a default value:
 ALTER TABLE user_details MODIFY pincode NUMBER(10) NULL DEFAULT NULL;

Number(10) is just chosen as an example. Replace this by the variable type of pincode.

A: I had same error as org.hibernate.exception.GenericJDBCException: could not execute statement where i forgot to initialize session factory.
Initializing(as follow) session factory resolved my issue.
@Autowired
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}


text:
Q: What does the $-\log[P(X)]$ term mean in the calculation of entropy? The entropy (self information) of a discrete random variable X is calculated as:
$$
H(x)=E(-\log[P(X)])
$$
What does the $-\log[P(X)]$ mean? It seems to be something like ""the self information of each possible outcome of the random variable X".
And why do we use log function to calculate it?
ADD 1
Well, below is my reasoning:
The root motivation is to quantify/measure the uncertainty contained in a random variable.
Intuitively, people tend to agree that there's some connection between uncertainty and probability. And still intuitively, people shall agree that:

*

*the more probability an outcome has, the less uncertainty it has.

*thus, the less probability an outcome has, the more uncertainty it has.

So, I think if we want to measure the uncertainty for an outcome of a random variable, the measure function should satisfy:

*

*the value of uncertainty measure should be positive (human instinct when counting)

*the value of this measure for the uncertainty of an outcome should be monotonic decreasing function of the probability of that outcome.

*for outcomes of independent experiments, the uncertainty should be additive. That is for P(A)*P(B), the total uncertainty should be the sum of A's and B's. (This is kind of instinctive, too.)

Then I come to the choice of -log[p(i)] as the measure of uncertainty of each possible outcome, or self-information of each outcome.
Then I treat the entropy as the weighted average of the self-information of all possible outcomes.
I just read the book <Information Theory, Inference and Learning Algorithms> by MacKay. The author indeed gives a similar explanation to mine. And he name it the information content of each outcome. It is not difficult to see that entropy better describes a random variable than the information content.
And it is coincidental that the formula we intuitively found to measure the average information content of a random variable has a similar form to the one of entropy in thermodynamics. Thus comes the name information entropy...
BTW I want to quote some words from Einstein...

"It is not so important where one settles down. The best thing is to
follow your instincts without too much reflection."
--Einstein to Max Born, March 3, 1920. AEA 8-146

ADD 2
Following my above reasoning, I tried to derive the calculation of entropy for a continuous random variable Y in a similar way. But I was blocked. Details below.
Let Y's p.d.f be: $$f(y)$$
Then, if we strictly follow my previous reasoning, then we should pick up a small interval of I, and the probability of Y within interval I is given by: $$P(y\ within\ I)=\int_If(y)dy$$Then the measure of uncertainty for Y to fall in interval I should be: $$m(y\ within\ I) = -log\int_If(y)dy$$ Then, to get the entropy, we should get the expectation/average of this measure m, which is essentially: $$E[m(y\ within\ I)]$$ and it can be expanded as below:
$$
\int{P(y\ within\ I)*m(y\ within\ I)}dI
=\int{(\int_I{f(y)dy}*{(-log\int_If(y)dy)})dI}
$$
I found myself stuck here because the interval I is not strictly defined.
Then I find from here the authoritative definition of entropy of continuous random variable:
$$
H(Y)=-\int{f(y)log[f(y)]dy}
$$
The p.d.f. $f(y)$ can certainly be $> 1$, so the $H(Y)$ can be negative, while in discrete scenario, the $H(X)$ is always non-negative.
I cannot explain the why this in-consistence is happening. For now, I can only consider it as a philosophical difficulty regarding continuity and discreteness.
Some of my personal feeling (can be safely ignored):

In the discrete scenario, the concrete countable outcome provide the
foothold for us to carry out our calculation. But in the continuous
scenario, there's no such ready-made foothold (unless we can somehow
make one). Without such foothold, it feels like we just keep falling
into the endless hollowness of mind.

Anyone could shed some light?
ADD 3 - 4:23 PM 2/21/2022
We created mathematics to quantify the world. And here in probability we even try to quantify our mentality, while our mentality created mathematics in the first place. It's like an endless recursive fall. And it's really hard for one to settle down...

A: In his 1948 paper Claude Shannon introduced the entropy $H$ of a discrete random variable $X$ with probabilities $p_1, \dots, p_n$ as a function which satisfied three requirements, which should provide a measure of the information contained in $X$:

*

*$H$ should be continuous in the $p_i$.

*If all the $p_i$ are equal, $p_i = \frac{1}{n}$, then $H$ should be a monotonic increasing function of $n$. With equally likely events there is more choice, or uncertainty, when there are more possible events.

*If a choice be broken down into two successive choices, the original $H$
  should be the weighted sum of the individual values of $H$.

He further explains what property 3 means with a nice example. Then, in appendix 2, he shows that only a function of the form $$K \sum_{i=1}^n p_i \log(p_i)$$ can satisfy all these three requirements, where $K$ is some multiplicative constant.

A: Assume that one repeatedly draws values from a finite set $S$ of size $|S|$ according to a distribution $p=(p_x)_{x\in S}$. After one draw, there are $|S|$ possible results, after two draws there are $|S|^2$, and so on, so one can get the impression that after $n$ draws, the resulting distribution is spread out on the Cartesian product $S^n$, whose size is $|S|^n$. And indeed it is, but this view is deceptive because the distribution is extremely unevenly spread out on $S^n$. Actually:

There exists a subset $T_n\subset S^n$, often much smaller than $S^n$, on which nearly all the distribution of the sample of size $n$ is concentrated. And in this "vanishingly small" subset $T_n$, the weight of each element is roughly the same...

In other words, everything happens as if the combined result of the $n$ first draws was chosen uniformly randomly in $T_n$. What connects the dots is that the size of $T_n$ is $\mathrm e^{nH}$ for some deterministic finite number $H$. (Actually, the size of $T_n$ is $\mathrm e^{nH+o(n)}$.) Surely you recognized that $H$ is the entropy of the distribution according to which one is drawing the values from $S$, that is,
$$
H=-\sum_{x\in S}p_x\log p_x=-E[\log p_X],
$$
where $X$ is any random variable with distribution $p$.
This surprisingly general phenomenon, related to what is called concentration of measure, quantifies $\mathrm e^H$ as the (growth of the) effective size of the sample space. As direct consequences, $0\leqslant H\leqslant\log|S|$, $H=0$ if and only if $p$ is a Dirac measure and $H=\log|S|$ if and only if $p$ is uniform.

A: Easy illustrative example:
Take a fair coin. $P({\rm each\ result})=1/2$. By independence, $P({\rm each\ result\ in\ n\ tosses})=1/2^n$. The surprise in each coin toss is the same. The surprise in $n$ tosses is $n\times$(surprise in one toss). The $\log$ makes the trick. And the entropy is the mean surprise.


text:
Q: Regenerating a winload.exe If one is missing or has a corrupted winload.exe - and winload~1.exe, winloadOLD.exe, etc. do not work - what can you do to regenerate it?  (Such as after a failed logon screen customization.)

A: sfc /scannow - should do. Eventually offline scan from recovery CD/USB if you cannot boot.
winload.exe is a system protected file and has full access only by "Trusted Installer".
I would not use simple copying, renaming, moving this critical system file !
Copies of winload.exe can be found in:

*

*\windows\system32\boot

*\windows\winsxs subfolders (found in 6 subfolders on my Win 7/64 SP1 system).

The default system loader is "\windows\system32\winload.exe".

A: In my case, I renamed
C:\windows\system32\winload~1.exe

to
winload.exe

I know, it sounds rediculous, the file has a VERY different size, but at least, I could boot into my installation again and go on form there.


text:
Q: Exchange 2010 SSL Certificate Error Right,
I want to issue a certificate for web mail access to exchange, so I've created a request for mail.domain.com (no other domains).
I've then completed the certificate request and imported it and issued the 'IIS' service to the new cert, all other services are still assigned against the locally assigned cert.
However, when I open Outlook I get:

Which Outlook is seeing the certificate issued to CN: mail.domain.com but locally the server is known as exchangeserver.local, so hence the names do not match.
I've tried adding autodiscovery and the local name to the cert but makes no difference, what am I missing???

A: Changing the internal server names, as suggested by MichelZ, is one option, but personally, I find it easier to add a bunch of names to the SAN (Subject Alternative Names) field in the certificate to be a lot easier.
The corporate Exchange server I manage, for example, has 17 SANs on the certificate - so there are 18 names the users can use to access the mail server without generating a certificate error.
Either way, make sure your certificate is loaded in both IIS and Exchange, though.

A: You need to change your "internal URL's" to the external names, and ideally change the DNS of the external names to your internal server IP on your internal DNS
Set-WebServicesVirtualDirectory -Identity "EXCH-1\EWS (Default Web Site)" -InternalURL https://mail.domain.com/EWS/Exchange.asmx -BasicAuthentication:$true
Set-OabVirtualDirectory -Identity "EXCH-1\OAB (Default Web Site)" -InternalUrl https://mail.domain.com/OAB
Set-ActiveSyncVirtualDirectory -Identity "EXCH-1\Microsoft-Server-ActiveSync (Default Web Site)" -InternalUrl "https://mail.domain.com/Microsoft-Server-ActiveSync"
Enable-OutlookAnywhere -Server EXCH-1 -ExternalHostname mail.domain.com -ClientAuthenticationMethod Basic -SSLOffloading:$false

Have a read here for more details

A: An Exchange certificate may need various SANs (Subject Alternate Names) depending on the names the server is going to be accessed with; typically, for a single-server setup, this requires at least three SANs:

*

*mail.domain.com - your server's external hostname

*servername.domain.local - your server's internal hostname

*autodiscover.domain.com - autodiscover for your SMTP domain

Your situation can be quite different, though, depending on your server configuration; the internal and external DNS names can be made identical, and autodiscover might not be needed.
In short: if your server is going to be accessed using a name that is not included in the certificate SANs, you will get that error.

A: While MichelZ's answer is the proper one (and I would urge you to do it regardless) I can understand if you may have some hesitation doing this in a production exchange environment during business hours.  For a quick temporary fix until you can implement the proper one you can try looking for the _autodiscover srv record in your internal domain forward lookup zone _tcp container.  If it does not appear create a new srv record named "_autodiscover" proctocol: _tcp priority: 0 weight: 0 port number: 443 and use your external name for the host offering (make sure you have an A or CNAME record created already.)  For this to work all affected clients will need to clear their DNS cache but it should stop the warning pop-ups until you get the time to do Michel's answer.


text:
Q: Need a Regular Expression C# I need a regular expression to replace text in string:
string s="Insert into VERSION (ENTRYID,APPVERSION,PLATFORMVERSION,TIMESTAMPED,USERNAME,SQLSCRIPTNAME,COMMENTS)VALUES(SWS_Version_ID."NEXTVAL",'[3.02.01P20]','[4.1.38orcl]',sysdate,null,null,null);";

I need to replace 3.02.01P20 in square brackets to NEW_VERSION.
There can be other version except 3.02.01P20 but in the line we can see that the first opening square bracket follows the version.
Also let me know what changes do I have to make if it(3.02.01P20) follows, say 3 opening square bracket ([) so that I wont have to write a separate question for each one.

A: using System;
using System.Text.RegularExpressions;
class Tester
{
    public static void Main()
    {
        string s = "Insert into VERSION " +
            "(ENTRYID,APPVERSION,PLATFORMVERSION,TIMESTAMPED,USERNAME,SQLSCRIPTNAME,COMMENTS)" +
            "VALUES(SWS_Version_ID.\"NEXTVAL\",'[3.02.01P20]','[4.1.38orcl]',sysdate,null,null,null);";
        Match m = (new Regex("^(.*)(\\[.*?\\])(.*?)(\\[.*?\\])(.*)$")).Match(s);
        //Console.WriteLine("{0},{1}", m.Groups[2].Value, m.Groups[3].Value);
        string[] parts = {
                m.Groups[1].Value,
                m.Groups[2].Value, //[3.02.01P20]
                m.Groups[3].Value, //','
                m.Groups[4].Value, //[4.1.38orcl]
                m.Groups[5].Value //tail
            };
        parts[1] = "[NEW_VERSION]";
        Console.WriteLine(string.Join("",parts));
    }
}

You mean like this?

A: Try this:
string output = Regex.Replace(s, @"(.*'\[)(.*)(\]'.*)('\[.*)", "$1" + newVer + "$3$4");


text:
Q: Table with frequencies for multiple variables I want to re-produce with SPSS the table with frequencies, which I usually create with SQL.
Input: one table, 2 fields, both of them are strings.
SQL-Code:
SELECT A,B, COUNT(*) FROM TTABLE GROUP BY A,B

How can I make get the same table, but with SPSS-syntax.
CTABLES seems to work only with 1 field.

A: After opening your table in SPSS I think this should do what you want:
DATASET DECLARE yourNewTable.
AGGREGATE /OUTFILE='yourNewTable'/BREAK=varA varB/N_BREAK=N.

A: CTABLES handles any number of fields.  Use the canvas to lay out the table. Chou could put the variables to count across the top but choose to have the values down the side.  If you need more help, send me a small dataset to work with (jkpeck at gmail.com)


text:
Q: Scope of @Transactional For example, I have a code something like this
@Transactional(propogation=PROPOGATION.REQUIRED)
public class codeForTest {

  public void doSomethins(){
    User user = userRepository.finduserById(userId);
    updateUserDetails(user);
    updateFewOtherDetails(user);
  }

}

public class DifferentClass{

  @Transactional(propogation=PROPOGATION.REQUIRED)
  updateUserDetails() {
    //UPDATES user object
  }

}

I am getting the following in couple of instances with the above logic. I don't get an error in local machine. My question is if updateUserDetails() will commit the transaction and when updateFewOtherDetails() is executed, since the transaction is committed, is it throwing the exception ? I doubt if that is creating the problem since where are annotating it with @Transactional (propogation= PROPOGATION.REQUIRED)
org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:81)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:73)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.checkRowCounts(BatchingBatch.java:151)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.performExecution(BatchingBatch.java:128)
at org.hibernate.engine.jdbc.batch.internal.BatchingBatch.doExecuteBatch(BatchingBatch.java:111)
at org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl.execute(AbstractBatchImpl.java:163)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.executeBatch(JdbcCoordinatorImpl.java:226)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:482)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:349)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
... 130 common frames omitted
 Wrapped by: org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:297)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:765)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:734)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:518)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:292)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy1125.createUserSession(Unknown Source)

A: You are using JPA (Hibernate) with optimistic locking. The actual exception:

org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

means that while your transaction was running another transaction updated the same rows, Hibernate detected their stale state and rolled back current transaction to avoid data consistency problems. This can happen with optimistic locking on a contended resource, but it's not bad because due to rollback the data is still consistent in the database.
There are few ways you can resolve this:

*

*Retry the logic that caused ObjectOptimisticLockingFailureException and hope that next transaction won't be contended.

*Relax transaction boundaries to perform a few smaller and faster transaction

*Queue updates in application logic

A: Both the methods will be executed in bounds of single transaction, once they both marked @Transactional.
user object was loaded in bounds of different transaction or taken from cache, in a case .finduserById() uses the one.
Make sure you've marked @Transactional second .updateFewOtherDetails() method too.
With propagation REQUIRED the transaction won't commit until the end of caller sequence.


text:
Q: Perl CGI::Application::Plugin:Stream + Jquery Taconite plugin - Cannot download file I am using the Stream (qw/stream_file/) Plugin for CGI::Application within a runmode to read a file from the filesystem and stream it back to the user.
The user clicks on a link whose "id" attribute I use in an ajax call using Jquery to fetch the file (/?mode=get_file&fileid=<someid>).
I am also using the Jquery taconite plugin to update page contents in other parts of my application; but I do not return any xml in the get_file runmode, which looks like this:

sub get_file{
  my $self = shift;
  my $fileid=$self->query->param("fileid");
  $self->header_add( -attachment => $fileid );
  $self->header_add( -type => "application/x-download");
  if ( $self->stream_file( $fileid ) ) {
        return;
  } else {
        return $self->error_mode();
  }
}

The result is:

*

*The file does get streamed as expected (Firebug tells me so)

*The headers seem alright (As seen in Firebug)

My problem is:

*

*The file contents are never presented to me as a file that can be downloaded.

My suspicion was that the taqconite plugin somehow removes the headers. Even so, I'm not sure of the best way to solve it.
Any ideas would be most helpful.
Thanks
/ft

A: Until I can figure this one out, I'm just going with a direct  link to download the file. (i.e No xmlhttp) to avoid the Jquery httpdata route.

A: Where is the file going then, if it's being streamed?


text:
Q: typing animation on each element with its class I'm trying to make a typing animation but it doesn't work and I don't know why. I know I could do it in CSS but I'd like to try it in JS. Problem is probably with the function itself I'm not the best in JS.

this will be animated

this aswell

A: You are on the right path. I've just cleaned things up a bit for readability.
Here is a codesandbox of it: https://codesandbox.io/s/typing-animation-kdn8v
I've made the assumption that you want the animations to happen in parallel. For this reason, we want to run through each HTML element and call our animateType function on each of them without any awaiting.
Each call of animateType kind of means there is a copy of this function running for this HTML element. This way, the variables like text, inside of the function don't get mixed up across HTML elements. This is called a "closure". All the variables inside of that "instance" of the function, live only inside of that instance of the function.
We store the original text, then clear the HTML element's contents, then just like you did we loop the letters of the cached text, and add each one to the HTML element.

// Stackoverflow: https://stackoverflow.com/questions/70573442/typing-animation-on-each-element-with-its-class

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const clearAndCache = (elements) => {
  let cachedText = [];
  for (let element of elements) {
    cachedText.push(element.textContent);
    element.textContent = "";
  }
  return cachedText;
};

const animateTypeSync = async (typeables, ms) => {
  const cachedText = clearAndCache(typeables);

  for (let i = 0; i < typeables.length; i++) {
    for (let character of cachedText[i]) {
      typeables[i].textContent += character;
      await sleep(ms);
    }
  }
};

const animateTypeAsync = (typeables, ms) => {
  const cachedText = clearAndCache(typeables);

  Array.from(typeables).forEach(async (element, i) => {
    for (let character of cachedText[i]) {
      element.textContent += character;
      await sleep(ms);
    }
  });
};

const elementsSync = document.getElementsByClassName("typing-animation-sync");
animateTypeSync(elementsSync, 200);

const elementsAsync = document.getElementsByClassName("typing-animation");
animateTypeAsync(elementsAsync, 150);
<!DOCTYPE html>

<title>Typing Animation</title>
<meta charset="UTF-8" />

Typing Animations

Async

These will run

at the same time

Sync

These will animate

one at a time

Edit: Added sync version to code after comment from OP.

A: I think this is what you're after?

this will be animated

this aswell

If you want that effect on several places, and easier to implement, there's a library that already does that, easier to customize and use: Typed.js


text:
Q: let $f : U \rightarrow U$ be an analytic function, whose Taylor series at $0$ is $f(z) = z + a_2z^2 + a_3z^3 + ...$ Let $U \subset \mathbb{C}$ be a bounded open set containing $0,$ and let $f : U \rightarrow U$ be an analytic function, whose Taylor series at $0$ is $f(z) = z + a_2z^2 + a_3z^3 + ...$
Prove that $a_2 = 0$.
Hint: Consider the functions $g_n(z) = f\circ ... \circ f(z)$.
I tried doing this and then noticed the $z^2$ term gets really big (the leading coefficient that is) but that didn't seem to do anything.  Any suggestions?

A: You pretty much solved it already: $g_n(z)=z+na_2z^2 + \ldots$, so $g''_n(0)=2na_2$, but by Cauchy's formula this quantity is bounded.
More explicitly, if $\overline{D}_R(0)\subset U$, then
$$
g''_n(0) = \frac{1}{i\pi} \int_{\partial D_R} \frac{g_n(w)}{w^3}\, dw ,
$$
and this is $\lesssim 1/R^2$ since, by assumption, $g_n(w)$ takes values in the bounded set $U$.


text:
Q: Prompt for information multiple times I am new to programming and I'm writing a simple robot in java to split PDF documents and save them to a file.  AS of right now my program asks how many slips (PDF documents) there are and then it asks how many pages there are.  The problem is that it only asks how many pages once.  I need it to ask how many pages are in each individual slip.  First I tried to wrap the JOption statement in an if statement but then the variable was out of scope.  So I made a method for each question, one for number of slips and one for the amount of pages.  I obviously still have the same result.  Can you please help me out?
Here is my code
//RES. 1366 x 768
import javax.swing.JOptionPane;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

public class automation
{
Robot robot = new Robot();
public static void main(String [] args) throws AWTException
{
    new automation();
}
public automation() throws AWTException
{
    int medDelay = 200;
    int counter2 = 1;
    int slips = slips();
    int pages = pages();
    robot.delay(medDelay);
    while (counter2 <= slips)
    {

    counter2 = counter2 + 1;

    //move to file in bridge and double click opens file
    robot.delay(3000);
    robot.mouseMove(300, 150);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    //maximize reader window
    robot.keyPress(KeyEvent.VK_WINDOWS);
    robot.keyPress(KeyEvent.VK_UP);
    robot.keyRelease(KeyEvent.VK_UP);
    robot.keyRelease(KeyEvent.VK_WINDOWS);

    robot.delay(medDelay);
    //move to tools hit enter
    robot.mouseMove(1190, 100);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    //move to text recognition and click
    robot.mouseMove(1190, 275);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    //scroll down to in this file click and press enter
    robot.mouseMove(1190, 320);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.keyPress(KeyEvent.VK_ENTER);
    robot.keyRelease(KeyEvent.VK_ENTER);
    //move to book marks and click
    robot.delay(60000);
    robot.mouseMove(10, 170);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    //move to patient name and triple click
    int counter1 = 1;
    while(counter1 <= pages){
    //JOptionPane.showInputDialog("You are on page " + i + "." );
    counter1 = counter1+1;
    robot.delay(medDelay);
    robot.mouseMove(335, 200);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_C);
    robot.keyRelease(KeyEvent.VK_C);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    //move to create book mark and click
    robot.mouseMove(180, 175);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseMove(50, 100);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    //JOptionPane.showMessageDialog(null, "You are on page " + i + "." );
    }
    robot.delay(medDelay);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_S);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.delay(medDelay);
    robot.mouseMove(10, 170);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseMove(1190, 275);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseMove(1190, 100);
    robot.delay(medDelay);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    robot.delay(medDelay);
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_Q);
    robot.keyRelease(KeyEvent.VK_Q);
    robot.keyRelease(KeyEvent.VK_CONTROL);
    robot.mouseMove(300, 150);
    robot.delay(300);
    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(300);
    robot.mouseMove(50, 315);
    robot.delay(500);
    robot.mouseRelease(InputEvent.BUTTON1_MASK);

    }
}
private int slips() {
    String slips = JOptionPane.showInputDialog("How many slips are there?");
    int slip = Integer.parseInt(slips);
    return slip;
}
private int pages() {
    String pages = JOptionPane.showInputDialog("How many pages are there?");
    int page = Integer.parseInt(pages);
    return page;
}

}

A: You'll get more help if your code is readable. You won't get/keep a programming position these days with variable names like, m,l,j and t....  Please, consider the maintenance programmer.
That said,  you're probably looking for something in this vein:
int slips = slips();
int outterCounter = 1;
while (outterCounter <= slips)
{
    int pages = pages();
    int innerCounter = 1;
    while (innerCounter <= pages)
    {
        // your logic
       innerCounter++;
    }

    outterCounter++;
}

Edit: OP had it originally as 1 based...


text:
Q: Flink processWindow function emits records with partial information We are seeing some weird behaviour with a processWindow function emitting two records,
the first record contains complete information using aggregated data present in the window and the second record contains partial information with some information removed from the record.
The processWindow function is using state(MapState) as follows:
override def open(parameters: Configuration): Unit = {
    cfState = getRuntimeContext.getMapState(
      new MapStateDescriptor[(String, Int), mutable.Map[Int, mutable.Set[Int]]] (
        "customFieldsState",
        classOf[(String, Int)],
        classOf[mutable.Map[Int, mutable.Set[Int]]]
      )
    )
  }

and the process function manipulates the above state using records present in the window.
Is this an anti-pattern? Using state within a processWindow function? Are there any other recommendations to using state within a processWindow function?
We need to maintain state in this case as we don't capture all fields in a single window and we need to aggregate the records per user, hence the use of a window function.
Thanks

A: If you want to maintain state beyond the lifetime of a single window instance, you should use
KeyedStateStore ProcessWindowFunction.Context#globalState

All other state is cleared when the window is closed.
Since globalState is never cleared by Flink, you should set state TTL on the state descriptor you use if you will have keys that go stale, in order to avoid leaking state over time.


text:
Q: Inserting values from a DataFrame into another dataframe Ok, my real problem is bigger than this, but I have a simple working example.
>>> import pandas as pd
>>> import numpy as np
>>> a = pd.DataFrame(np.array([[2, 1990], [4,1991], [5,1992]]), \
...                  index=[1,2,3], columns=['var', 'yr'])
>>> a
   var    yr
1    2  1990
2    4  1991
3    5  1992
>>> b = pd.DataFrame(index=a.index, columns=['new_var'])
>>> b
  new_var
1     NaN
2     NaN
3     NaN
>>> b[a.yr<1992].loc[:, 'new_var'] = a[a.yr<1992].loc[:, 'var']
>>> b
  new_var
1     NaN
2     NaN
3     NaN

I desire the following output:
>>> b
  new_var
1       2
2       4
3     NaN

A: With that filtering stuff, you're creating a copy of a slice, and thus it won't assign.
Do this instead:
b.loc[a.yr<1992, 'new_var'] = a['var']

A: you can also use assign + query to add intuitiveness
b.assign(new_var=a.query('yr < 1992')['var'])

   new_var
1      2.0
2      4.0
3      NaN

This returns the dataframe you'd want.  You'll have to assign it back to b if you want it to persist.

A: yet another "creative" solution:
In [181]: b['new_var'] = np.where(a.yr < 1992, a['var'], b['new_var'])

In [182]: b
Out[182]:
  new_var
1       2
2       4
3     NaN


text:
Q: Get Resource Calendar with Directory API I really tried but can't figure it out by myself how to retrieve the data of a resource calendar with the Directory API.
What I want:

*

*retrieve the data of my company's resource calendar by using a service account with domain-wide delegation

What I have:

*

*service account with domain-wide delegation (+ credentials.json)

*calendar ID of my company's resource calendar
I'm a non-admin user and as far as I know the service account has to impersonate a user.
Do I need to be an admin user to manage and see the data of the resource calendar and share it with the service account?
I use a jwtClient to authorize and I have no idea whether I have to use the Directory API, Google Calendar API or both to make it work.
I tried to use the Google Calendar API first but it didn't work and now I guess I have to get the resource calendar with the Directory API.
That's what I have so far:
let express = require('express');
let app = express();

app.set('view engine', 'ejs');

let {google} = require('googleapis');
const calendar = google.calendar('v3');

const port = 3000;
const key = require('./credentials.json');
const jwtClient = new google.auth.JWT(
    key.client_email,
    null,
    key.private_key,
    [ 'https://www.googleapis.com/auth/calendar'],
    null
);

jwtClient.authorize(function(err, tokens) {
    if (err) {
        console.log(err);
    } else {
        console.log("Authorization worked!");
        console.log(tokens);
    }
});

app.get('/', function(req, res) {
    calendar.events.list({
        auth: jwtClient,
        calendarId: 'xxxx@resourcexxx.com',
        timeMin: (new Date()).toISOString(),
        maxResults: 5,
        singleEvents: true,
        orderBy: 'startTime'
    }, function(err, resp) {
        res.json(resp);
    });
});

app.use(express.static('public'));

app.listen(port, function(err){
    if (!err) {
        console.log("App is running on port", port);
    } else {
        console.log(JSON.stringify(err));
    }
});

Any help would be appreciated. Thanks in advance!

A:
I'm a non-admin user and as far as I know the service account has to impersonate a user. Do I need to be an admin user to manage and see the data of the resource calendar and share it with the service account?

*

*Service accounts can impersonate users, when they have domain-wide delegation enabled. It is not necessary.
Service accounts behave like "normal" accounts - they have their own permissions on resources. That means that, if you want to get a specific calendar's data from that account, you will have to give it view permission. In case you would prefer to edit it using the service account, you will have to give the account edit permissions. You can do that as you would with any other user, the difference being that you will have to use the service account's e-mail address (which you will find in the developer's console) to reference it.
If you are using service account that has domain-wide authentication enabled, when authenticating, you can specify a "subject" (an existing user of your domain) to impersonate. After a successful authentication, every action performed will be executed as if the "subject" account was the one performing them - and it will use that user's permissions.

I use a jwtClient to authorize and I have no idea whether I have to use the Directory API, Google Calendar API or both to make it work.

*

*Since you are retrieving data from calendars (and not any user's information) you only need to use the Google Calendar API.

What I want: retrieve the data of my company's resource calendar by using a service account with domain-wide delegation

*

*In your case - retrieving data - you can simply share that calendar with your service account. Afterwards, with no need to use domain-wide delegation, it will be able to use calendar.events.list to retrieve the events present in the calendar along with their details, using the same code you provided.

Reference

*

*Google Calendar API

*Performing domain-wide delegation of authority

*Using OAuth 2.0 for Server to Server Applications


text:
Q: Платежная система на сайте Хочу прикрутить на сайт универсальную платежную систему, чтобы можно было с различных карт или кошельков переводить на мой кошелек. Нашел одну такую, но проблема в том, что там только на webmoney можно. Так вот вопрос, есть ли такая система в которой можно организовать вывод с различных кошельков на ЯндексДеньги или Киви?
P.s. Извиняюсь, если не там задал вопрос, уже не знаю просто у кого спросить.


text:
Q: Algorithm analysis, finding a constant c and a point n? Say for example I say that:
$$
2n^2 + n - 8 \quad\text{is}\quad O(n^3)
$$
To prove this I must find a constant $c$ and a point $n_0$ for which $n^3$ is an upper bound of the equation.
This is easy to see because $n^3$ will always be larger than $2n^2$ (dominant term) for any constant $c$. How do I find $n_0$?

A: The $-8$ makes the examples harder to see, so I will ignore it.  As you say, you want to choose $c$ and $n_0$ so that $n \gt n_0 \implies cn^3 \gt 2n^2+n$.  You get to choose $c$ and $n_0$ and there are many choices that will work.  One choice would be $c=1$, in which case you can show that $n_0=2$ (or anything larger) will work.  Also, you could choose $n_0=0,$  in which case $c$ needs to be at least $4$.


text:
Q: Distribution of largest entry in a random vector If we have a random unit vector on $\mathbb{C}^n$, drawn from the Fubini-Study metric, the marginal distribution of the squared absolute values of each of the coefficients in the vector is given by a Beta distribution with shape parameters $\alpha=1$, $\beta=n-1$. (See for example Zyczkowski and Sommers).
However, this doesn't immediately translate to a statement about the order statistics, since the variables are not independent (they are constrained to sum to 1, for example).
What is the distribution of the largest magnitude of the coefficients in the vector, that is, the first order statistic?

A: This problem was solved in Extreme statistics of complex random and quantum chaotic states (2007). The first two moments of the maximum absolute value of the elements of the random unit vector, $t=\max(|z_1|^2,|z_2|^2,\ldots |z_n|^2)$, are
$$\langle t\rangle=\frac{H(n,1)}{n},\;\;\langle t^2\rangle=\frac{H^2(n,1)+H(n,2)}{n(n+1)}$$
where $H(n,k)$ is the $k$-th harmonic number. The cumulative density $F(t)$ in the large-$N$ limit is
$$F(t)\rightarrow (1-e^{-nt})^n\approx\exp\left(-e^{-nt+\ln n}\right),\;\;\text{for}\;\;n\rightarrow\infty,$$
which is a Gumbel distribution.

A: $\newcommand{\C}{\mathbb C}$$\newcommand{\R}{\mathbb R}$Let $U=(U_1,\dots,U_n)$ be a random vector uniformly distributed on the unit sphere in $\C^n$. Then the distribution of the random vector $V:=(X_1,Y_1,\dots,X_n,Y_n)$ is uniform on the unit sphere in $\R^{2n}$, where $X_j:=\Re U_j$ and $Y_j:=\Im U_j$. So, $V$ equals $W:=(W_1,\dots,W_{2n})$ in distribution, where
$$W_j:=\frac{Z_j}{\sqrt{Z_1^2+\dots+Z_{2n}^2}}
$$
and $Z_1,\dots,Z_{2n}$ are iid standard normal random variables (r.v.'s).
So, the random vector $(|U_1|^2 ,\dots,|U_n|^2)$ equals
$R:=(R_1,\dots,R_n)$ in distribution, where
$$R_j:=\frac{T_j}{T_1+\dots+T_n}
$$
and $T_k:=Z_{2k-1}^2+Z_{2k}^2$, so that $T_1,\dots,T_n$ are iid standard exponential r.v.'s. So, $\max_j|U_j|^2$ equals $\max_j R_j$ in distribution. The distribution of $\max_j R_j$ was found a long time ago; see e.g.
Irwin (1955) and historical references therein going
back to as far as 1897. In particular, according to formula (1) in Irwin's paper,
\begin{equation}\label{eq:fisher}
 P(\max_j |U_j|^2>x)=P(\max_j R_j>x)=\sum_{j=1}^n(-1)^{j-1}\binom nj(1-jx)_+^{n-1}
\end{equation}
for $x\in[0,1]$.


text:
Q: LINQ to Entities ToString() - None of the proposed solutions work? I'm posting this more because I'd like to learn more, because my work-around has been to basically avoid using LINQ to Entities! It would nice if I could use it though. So if anyone can enlighten me..
I'm working on an ASP.Net MVC 3 application (my first one) using code-first Entity Framework as my data model. It's going to be an online shop and I am working on the 'Admin' controller where, as an admin, you will be able to edit products etc. When it comes to adding a new product, you must specify a category, which means a dropdown list of categories.
I started off by just returning an IEnumerable collection of categories in the ViewBag, based on the information I found here. This seemed like a really nice way to approach things.
But I got the same error you'll see below. So following a suggestion I read online, I created a separate model specifically for creating new and editing existing products. The Categories collection is used to build a dropdown list in the view.
public class ProductModel
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public double Price { get; set; }
    public bool IsVisible { get; set; }

    public IEnumerable<SelectListItem> Categories
    {
        get
        {
            return new DataAccess()
                .Categories
                .OrderBy(c => c.Description)
                .Select(c => new SelectListItem
                    {
                        Value = c.Id.ToString(),
                        Text = c.Description
                    });
        }
    }
}

This results in the following error message: "LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.". One proposed online solution was to use the SqlFunction methods provided by the Entity Framework. So I tried this instead ...
    public IEnumerable<SelectListItem> Categories
    {
        get
        {
            return new DataAccess()
                .Categories
                .OrderBy(c => c.Description)
                .Select(c => new SelectListItem
                    {
                        Value = SqlFunctions.StringConvert((double)c.Id),
                        Text = c.Description
                    });
        }
    }

But this results in this error message: "The specified method 'System.String StringConvert(System.Nullable`1[System.Double])' on the type 'System.Data.Objects.SqlClient.SqlFunctions' cannot be translated into a LINQ to Entities store expression.".
I've even tried adding a read-only property to the data class called IdAsString, but this obviously makes the Entity Framework very unhappy!
In the end, I realised that it wasn't worth all the time I was putting into it, and just stopped using LINQ altogether. This works fine, but it would be nice to know if there is a "correct" way to do this that actually works!
This is my current working solution:
    public IEnumerable<SelectListItem> Categories
    {
        get
        {
            var dal = new DataAccess();
            var categories = dal.Categories;
            var items = new List<SelectListItem>();

            foreach (var category in categories)
                items.Add(new SelectListItem
                    {
                        Value = category.Id.ToString(),
                        Text = category.Description
                    });

            return items;
        }
    }

So if anyone is already doing this and they think they're doing it the "correct" way, then I'd love to know what you think!

A: Materialize the query before you invoke ToString will make the last part a non linq-to-entities query. You could optimize this by only selecting the id and description, then calling AsEnumerable, and then getting the selectlistitems.
    return new DataAccess()
        .Categories
        .OrderBy(c => c.Description)
        .AsEnumerable()
        .Select(c => new SelectListItem
            {
                Value = c.Id.ToString(),
                Text = c.Description
            });


text:
Q: Rails structure.sql is invalid (foreign keys reference tables not yet created) We have had to switch from schema.rb to structure.sql, since we needed a VARBINARY field in MySQL with an index of a specified length on it, which schema.rb doesn't handle, but structure.sql does.
Unfortunately, we've now hit a bigger issue. The structure.sql file contains CREATE TABLE statements in alphabetical order. Our tables have foreign key constraints on them. The structure.sql file includes these key constraints, but references tables that don't get created until further down the file.
e.g.
CREATE TABLE attachments (
  id INT NOT NULL auto_increment PRIMARY KEY,
  user_id INT,
  /* ... snip ... */
  CONSTRAINT attachments_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE
) ENGINE=InnoDB CHARSET=utf8;

/* ... snip ... */

CREATE TABLE users (
  id INT NOT NULL auto_increment PRIMARY KEY,
  /* ... snip ... */
) ENGINE=InnoDB CHARSET=utf8;

Is there a workaround for this? It seems so fundamentally broken for such a common DB schema design principle I can't even believe this is a thing. We're on Rails 3.2.12.

A: Best I'm aware, there's no fix short of rewriting your SQL file to sort the create table statements in the correct order, or creating the foreign key constraints at the very end.
Consider changing whatever tool you used to create the dump file, too. Dump files should be able to run, and this one evidently doesn't...


text:
Q: Java Regex Doesn't Work For Characters As Like \n I want to remove all characters that starts with {{ and ends with }} I've written that regex:
String templatePattern = "\\{\\{.*?\\}\\}";

and I use that:
text.replaceAll(templatePattern, "");

It works but for strings as like that:
{{Apple \n banana }}

it doesn't work. If I replace all \n characters with space character it works. What is the proper solution for it? Because I should apply same thing for \t and others too.

A: The reason is, a dot matches anything but \n. If you want to match everything, then you can use [\s\S], or [\w\W] or any such variations of complimenting meta-characters:
String templatePattern = "\\{\\{[\s\S]*?\\}\\}";

Another way is to make the dot actually match the newline, by using (?s) flag:
String templatePattern = "(?s)\\{\\{.*?\\}\\}";

The later one is indeed a better way. (?s) is same as Pattern.DOTALL.


text:
Q: Sum items with certain IDs in IEnumerable of a Custom Class CustomClass{
int ID;
int numberToSum;
float numToAverage;
}

IEnumerable<CustomClass> results = MethodToPopulateIEnumerable();
List<int> listOfIDs = MethodToGetListOfIDs();

What I wish to do with these, is take my IEnumberable<CustomClass> and select all the ones where the ID is in the List<int> listOfIDs, then I wish to sum the numberToSum value of this and save it in a variable and get the average of the numToAverage property and save it in a variable.
What is the most elegant way to do this ?

A: I think you are looking for something like this:
IEnumerable<CustomClass> results = MethodToPopulateIEnumerable();
List<int> listOfIDs = MethodToGetListOfIDs();

Query Syntax
 var query = from c in results
             where listOfIds.Any(x => x == c.ID)
             select c;

Method Syntax
var query = results.Where(c => listOfIds.Any(x => x == c.ID));

Calculations
int numberToSum = query.Sum(x => x.numberToSum);
float numToAverage = query.Average(x => x.numToAverage);

Another alternate method which would allievate some of the performances concerns by fellow members, but still allowing the query to be linq-to-whatever friendly (linq-to-entities, linq-to-sql):
var calculations = (from c in results
                   where listOfIds.Any(x => x == c.ID)
                   group c by 1 into g
                   select new {
                     numberToSum = g.Sum(x => x.numberToSum ),
                     numToAverage = g.Average(x => x.numToAverage),
                   }).FirstOrDefault();

A: I think it's something like this:
var matchingIdsList = results.Where(x => listsOfIDs.Any(y => y == x.Id));
var sum = matchingIdsList.Sum(x=> x.numberToSum);
var average = matchingIdsList.Average(x=> x.numToAverage);

A: I'd do this as follows - not very elegant but more efficient:
// Load IDs into a hashset so Contains is O(1) not O(n)
var hashSetOfIDs = new HashSet<int>(listOfIDs);

// Aggreagate count and both sums in one pass, then calculate average.
var result = results.Where(cc => hashSetOfIDs.Contains(cc.ID)).Aggregate(
    new { Count = 0, Sum = 0, AverageSum = 0f },
    (a, cc) => new {
        Count = a.Count + 1,
        Sum = a.Sum + cc.numberToSum,
        AverageSum = a.AverageSum + cc.numToAverage },
    a => new {
        Sum = a.Sum,
        Average = a.Count > 0 ? a.AverageSum / a.Count : float.NaN });

// Extract results
var sum = result.Sum;
var average = result.Average;

A: var results = MethodToPopulateIEnumerable();
var listOfIDs = MethodToGetListOfIDs();

int numberToSum = 0;
float numberToAverage = 0;

var selected = results.Where(c => listOfIDs.Contains(c.ID)).Select(c =>
  {
    numberToSum += c.numberToSum;
    numberToAverage += c.numToAverage;
    return c;
  }).ToList();

float average = numberToAverage/selected.Count;


text:
Q: Why do (microphone) preamp designs tend to limit opamp gain to max 60 dB? Looking at many pro recording quality microphone preamps, I noticed that every design I looked at that uses an opamp (discrete or IC) limits the gain provided by the opamp to about max 60dB. While most preamps use another stage (transformer(s) or another opamp) to get to 70db or even 80dB, I wonder why they don't just use the first opamp to get there. From what I understand, there would be some advantages:

*

*better signal-to-noise ratio as voltage gain rises,

*simpler audio path,

*less parts & cost.

Does it have something to do with opamp stability over 60dB?
Here is a typical schematic. R12 limits gain to 40.1dB. I'm using these formulas:
$$A = 1 + (R_{fb}/R_{in})$$
$$gain_{dB} = 20 * log(A)$$
I also noticed that complete mic preamp ICs made by THAT-Corp also have a maximum gain of 60dB.

A: Many op amp circuits are designed so that they would yield a known finite gain if constructed using ideal components including an infinite-gain op amp.  In practice, such circuits will always be constructed with non-ideal components, and their behavior will not quite match what would have resulted from ideal components.  Consider a very basic amplifier:

simulate this circuit – Schematic created using CircuitLab
When using ideal components, the gain will be (R1+R2)/R2; I'll call that the "nominal gain".  In an actual circuit, if an op amp has a constant open-loop gain, the gain will be 1/(R2/(R1+R2) + 1/opAmpGain).  If the open-loop gain of the op amp is much larger than (R1+R2)/R2, then 1/opAmpGain is going to be very small relative to R2/(R1+R2), and its exact value won't matter much.  Further, even if the open-loop gain might vary due to factors like frequency or--even worse--the input voltage, the maximum and minimum gain for the circuit would be relatively close.  For example, if the open-loop gain might vary between 500x and 1000000X, the net gain of the circuit would range from about 9.8x to 10x.  More variation than might be ideal for some uses, but still pretty small.
If R1 were changed to 99K (changing the nominal gain from 10x to 100x), then the circuit's sensitivity to the actual gain of the op amp would be increased more than tenfold.  The same variation in the op amp's actual gain would cause the circuit's net gain to range from about 83x to 100x--a much larger variation.  If one were to instead cascade the circuit shown below (for 10x gain) with a second copy, the resulting circuit would have a gain that could range from about 96x to 100x.  A larger degree of relative uncertainty than when using one copy of that circuit, but much smaller than when trying to achieve 100x gain in one stage.
A gain of 60dB would entail a 1000:1 voltage gain.  While one op amp with a high enough open-loop gain to make a 1000:1 nominal gain practical at audio frequencies might be cheaper than two op amps with slightly-inferior specifications, op amps that will work well at such higher gains are apt to be much more expensive.  At some level of gain, using two cheaper amps will be more practical than using one amp which is of sufficient quality to work well at the higher gain.

A:
Why (microphones) preamps designs tend to limit opamp gain to max 60
  dB?

A good overall picture of the whole range of what microphones and other audio devices produce: -

Picture taken from here.
As can be seen a studio microphone (depending on type) can produce a range of outputs from -60 dBm (relative to 600 ohm hence 0 dBm = 0.775 volts) to -20 dBm. This is for the standard input pressure level of 1 pascal at 1 kHz.
Line input levels are typically about 0 dBm hence a typical microphone preamp will produce have a gain range of 20 dB to 60 dB.

A: 60 dB means 1 mV from the mic becomes 1 V out.  That's about the maximum you want to amplify a microphone and feed into a "line level" input.  Most microphones produce a few mV out for normal sound levels.

A: In addition to the other excellent answers about gain-bandwidth product, there is another problem. With too much gain, the input op amp can saturate due to the input offset voltage. Many mixer boards use the 5532 op amp for the first gain stage. It has a typical offset voltage of 0.5mV, but it can be as high as 5mV over temperature. With 60dB of gain, a 5mV input offset becomes 5V of DC offset at the output. The 5532 also has 10MHz typical gain-bandwidth product, so at 60dB gain the bandwidth is at most 10kHz.
When there is a lot of gain, there also tends to be a lot of noise. After a preamp, I like to use a low-pass active filter to get more gain, and also filter out some of the high-frequency preamp output noise.  I use the OPA2134 op amp, which I learned about through the good active filter design advice at Linkwitz Lab. Unless the maximum frequency is low, I would use less than even 60dB of gain in a single stage. Two 40dB stages would be better.

A: Gain/Bandwidth product, you want maybe 50KHz bandwidth at 60dB (1,000 times), so you need somewhere around 50MHz, gain/bandwidth product (And more would lower HF distortion)... Make it 80dB and now you need 500MHz GBP, which is getting difficult if you want low noise down near DC (And is getting really bad news to stabilise at low gain).
Also consider that the noise is completely dominated by the noise for the stage having the first 20 or 30dB of gain (Do the maths), there is a lot to be said for splitting things so that the first maybe 30dB of gain happens in a low noise stage designed for low Z sources and low 1/F noise, which now only needs a few MHz of GBP and will be easy to stabilise even with weird source impedance. Then do the rest in a second stage (where noise matters less and you have a known source impedance).
The other difficult thing is that control laws that make sense become increasingly tricky if going for a one knob gain control, a classic instrumentation stage with have a gain setting resistor varying from a few ohms to maybe a few k ohms, which if you think about it is only maybe 3 orders of magnitude, very difficult to make a reverse log pot have more range then that.

A: There is the matter of GBW(gain-bandwidth product), so a single stage is improbable with good performance. It's not enough to just squeak through in bandwidth you also want enough gain to reduce the distortion and get accurate reproduction with flat response (though arguably distortion at more than about 10kHz is unimportant for human hearing). Of course you can always have a couple of stages with more reasonable gain each. Remember bandwidth is defined by the -3dB point (the output will be down to half power at the edge of the pass band), and that's not exactly flat by audiophile standards.
Another issue is that even a very good op-amp may have an input-referred noise level of a couple \$\text{nV}/\sqrt {\text {Hz}}\$, whereas a transformer input stage will provide an essentially noiseless step-up in voltage (at the expense of lowering the input impedance by the square of the turns ratio).
Since very low voltage sources such as ribbon microphones tend to be low impedance as well, this is a good trade-off.
There are other methods of getting extremely low noise performance by using discretes such as multiple JFETs run at rather high drain current. This can reduce the noise, ideally by the square root of the number of JFETs, but the input capacitance is proportional to the number of JFETs in parallel, so again the bad effect increases faster than the improvement.


text:
Q: Creating new dataframe with latest NA values by date, while grouped by another column in R I have a dataframe containing various information as below. However, I would like to retrieve the latest (by date) non-NA value of a certain column (Value), while grouped by another column (Team), to be consolidated into a new dataframe.
INPUT:
Team    Date             Value        Shape        Value_2
A       2021-01-01       500432       Triangle     123
A       2021-01-02       NA           Triangle     23
A       2021-01-03       NA           Triangle     543
B       2021-01-01       NA           Square       8543
B       2021-01-02       473929       Circle       NA
B       2021-01-03       NA           Circle       356
C       2021-01-01       750830       Rectangle    984
C       2021-01-02       894032       Rectangle    NA
C       2021-01-03       NA           Rectangle    342

OUTPUT:
Team    Date             Value        Shape
A       2021-01-01       500432       Triangle
B       2021-01-02       473929       Circle
C       2021-01-02       894032       Rectangle

A: This should work
library(data.table)
dt = fread("
Team    Date             Value        Shape        Value_2
A       2021-01-01       500432       Triangle     123
A       2021-01-02       NA           Triangle     23
A       2021-01-03       NA           Triangle     543
B       2021-01-01       NA           Square       8543
B       2021-01-02       473929       Circle       NA
B       2021-01-03       NA           Circle       356
C       2021-01-01       750830       Rectangle    984
C       2021-01-02       894032       Rectangle    NA
C       2021-01-03       NA           Rectangle    342
")

dt[!is.na(Value),tail(.SD,1),by = Team,.SDcols=1:4]
#   Team       Date  Value     Shape
#1:    A 2021-01-01 500432  Triangle
#2:    B 2021-01-02 473929    Circle
#3:    C 2021-01-02 894032 Rectangle

*

*!is.na(Value) is to select rows with non-NA Value

*tail(.SD,1) is to select lates row of each group

*by = Team is to group by Team

* .SDcols = 2:4 is to select variables 2:4 (by = Team will set Team as first column automatically)

A: A dplyr solution
We can group_by Team, then arrange with decreasing Date, filter out the NAs from Value, then slice the top row per group:
library(dplyr)

df %>% group_by(Team) %>%
        arrange(Team, desc(Date)) %>%
        filter(!is.na(Value)) %>%
        slice(1) %>%
        select(-Value_2)

# A tibble: 3 x 4
# Groups:   Team [3]
  Team  Date        Value Shape
  <chr> <date>      <int> <chr>
1 A     2021-01-01 500432 Triangle
2 B     2021-01-02 473929 Circle
3 C     2021-01-02 894032 Rectangle


text:
Q: Form styling best practices I've created a nice set of form elements in Photoshop and am looking to convert them into HTML and CSS. The simple input-text form will have a background image, as the field does not change in size. However, the text-area form will dynamically change size as the user types.
Normally, to build out this sort of style, I'd wrap the form field in divs, as such:

    <textarea></textarea>

Or by using multiple background-images in one wrapping div:

  <textarea></textarea>

Is there a better way to approach this? To restate, the field styles are advanced images that can be repeated (for the body of the field), and have styling for the top and bottom. The question is, what is the best practice in dealing with these advanced form styling?

A: I'm not entirely sure what you mean by "best practice", but one thing I'd improve are the semantics.
You could (should?) use <fieldset>'s instead of a, rather meaningless,
.
And you don't need to use two
's around the textarea, or even multiple background images on a single
 (which is a CSS3 property, and not widely-supported).
Instead, you should wrap the <textarea> in a  element, and nest your background-images as I've described below:
Try this:
<fieldset class="expandableInput">

    Semantic text:
    <textarea></textarea>

</fieldset>

Bonus: wrapping form elements in 's like this, affords a larger click area, for the user to gain focus on the form element at hand. Just be wary of <select>'s, which doesn't play nice (even though it's valid HTML)
The CSS would be something like:
.expandableInput {background: url(/path/to/first/img);}
  .expandableInput label {display: block; background: url(/path/to/second/img);}
    .expandableInput textarea {display: block; margin-top: 3px; background: url(/path/to/third/img);}

Also;
For consistent looks on form elements, in every browser & platform, I can highly recommend Nathan Smith's Formalize CSS (it requires JS for HTML5 support in older browsers).