text:
Q: OpenXML to Create a DataTable from Excel - Money Cell Value Incorrect I am attempting to create a datatable from an Excel spreadsheet using OpenXML. When getting a row's cell value using Cell.CellValue.innerXml the value returned for a monetary value entered by the user and visible on the spreadsheet is not the same value interpreted.
The spreadsheet cell is formatted as Text and the cell value is 570.81.  When obtaining the data in OpenXML the value is interpreted as 570.80999999999995.
This method is used for many different excel imports where the data type for a cell by header or column index is not known when building the table.
I've seen a few post about the Ecma Office Open XML File Formats Standard and mention of numFmtId. Could this be of value?
I assume that since the data type is text and the number has two decimal places that there must be some assumption that the cell has been rounded (even though no formula exists).
I am hopeful someone can offer a solution for properly interpreting the data.
Below is the GetCellValue method:
private static string GetCellValue(SharedStringTablePart stringTablePart, DocumentFormat.OpenXml.Spreadsheet.Cell cell,DocumentFormat.OpenXml.Spreadsheet.Stylesheet styleSheet)
{
    string value = cell.CellValue.InnerXml;

    if (cell.DataType != null && cell.DataType.Value == DocumentFormat.OpenXml.Spreadsheet.CellValues.SharedString)
    {
        return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
    }
    else
    {

        if (cell.StyleIndex != null)
        {
            DocumentFormat.OpenXml.Spreadsheet.CellFormat cellFormat = (DocumentFormat.OpenXml.Spreadsheet.CellFormat)styleSheet.CellFormats.ChildElements[(int)cell.StyleIndex.Value];

            int formatId = (int)cellFormat.NumberFormatId.Value;

            if (formatId == 14) //[h]:mm:ss
            {
                DateTime newDate = DateTime.FromOADate(double.Parse(value));
                value = newDate.Date.ToString(CultureInfo.InvariantCulture);
            }
        }
        return value;
    }
}

A: As you point out in your question, the format is stored separately from the cell value using number formats in the stylesheet.
You should be able to extend the code you have for formatting dates to include formatting for numbers. Essentially you need to grab the NumberingFormat that corresponds to the cellFormat.NumberFormatId.Value you are already reading. The NumberingFormat can be found in the styleSheet.NumberingFormats elements.
Once you have this you can access the FormatCode property of the NumberingFormat which you can then use to format your data as you see fit.
Unfortunately the format is not quite that straightforward to use. Firstly, according to MSDN here not all formats are written to the file so I guess you will have to have those somewhere accessible and load them depending on the NumberFormatId you have.
Secondly the format of the format string is not compatable with C# so you'll need to do some manipulation. Details of the format layout can be found on MSDN here.
I have knocked together some sample code that handles the currency situation you have in your question but you may need to give some more thought to the parsing of the excel format string into a C# one.
private static string GetCellValue(SharedStringTablePart stringTablePart, DocumentFormat.OpenXml.Spreadsheet.Cell cell, DocumentFormat.OpenXml.Spreadsheet.Stylesheet styleSheet)
{
    string value = cell.CellValue.InnerXml;

    if (cell.DataType != null && cell.DataType.Value == DocumentFormat.OpenXml.Spreadsheet.CellValues.SharedString)
    {
        return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
    }
    else
    {
        if (cell.StyleIndex != null)
        {
            DocumentFormat.OpenXml.Spreadsheet.CellFormat cellFormat = (DocumentFormat.OpenXml.Spreadsheet.CellFormat)styleSheet.CellFormats.ChildElements[(int)cell.StyleIndex.Value];

            int formatId = (int)cellFormat.NumberFormatId.Value;

            if (formatId == 14) //[h]:mm:ss
            {
                DateTime newDate = DateTime.FromOADate(double.Parse(value));
                value = newDate.Date.ToString(CultureInfo.InvariantCulture);
            }
            else
            {
                //find the number format
                NumberingFormat format = styleSheet.NumberingFormats.Elements<NumberingFormat>()
                                .FirstOrDefault(n => n.NumberFormatId == formatId);
                double temp;

                if (format != null
                    && format.FormatCode.HasValue
                    && double.TryParse(value, out temp))
                {
                    //we have a format and a value that can be represented as a double

                    string actualFormat = GetActualFormat(format.FormatCode, temp);
                    value = temp.ToString(actualFormat);
                }
            }
        }
        return value;
    }
}

private static string GetActualFormat(StringValue formatCode, double value)
{
    //the format is actually 4 formats split by a semi-colon
    //0 for positive, 1 for negative, 2 for zero (I'm ignoring the 4th format which is for text)
    string[] formatComponents = formatCode.Value.Split(';');

    int elementToUse = value > 0 ? 0 : (value < 0 ? 1 : 2);

    string actualFormat = formatComponents[elementToUse];

    actualFormat = RemoveUnwantedCharacters(actualFormat, '_');
    actualFormat = RemoveUnwantedCharacters(actualFormat, '*');

    //backslashes are an escape character it seems - I'm ignoring them
    return actualFormat.Replace("\"", ""); ;
}

private static string RemoveUnwantedCharacters(string excelFormat, char character)
{
    /*  The _ and * characters are used to control lining up of characters
        they are followed by the character being manipulated so I'm ignoring
        both the _ and * and the character immediately following them.
        Note that this is buggy as I don't check for the preceeding
        backslash escape character which I probably should
        */
    int index = excelFormat.IndexOf(character);
    int occurance = 0;
    while (index != -1)
    {
        //replace the occurance at index using substring
        excelFormat = excelFormat.Substring(0, index) + excelFormat.Substring(index + 2);
        occurance++;
        index = excelFormat.IndexOf(character, index);
    }
    return excelFormat;
}

Given a sheet with the value 570.80999999999995 formatted using currency (in the UK) the output I get is £570.81.


text:
Q: What Filesystem or raid-like structure can I use for broken / dying hard drives? Story: I have a 3TB Hard drive that is failing. I have recovered everything I want from it. Gradually, it is becoming more and more unusable as sectors on it become unstable (re-allocated sectors and unstable sectors are rising).
I would like to continue using this drive in some way instead of just wiping it and throwing it away. I accept that this is unsafe and I can lose everything at any time. I plan to use it for data that is entirely disposable, for example, software installers that can be re-downloaded at any time.
tl;dr
Is there some sort of filesystem or structure I can use to leverage some usability out of this drive? Perhaps something that has a builtin parity system or writes every bit to 2 parts of the drive independently behind the scenes? Ex. A Raid 1 mirror that uses 2 partitions on itself?
An immediate problem that I can see makes the drive too frustrating to use is if that FAT becomes corrupted the partitions don't mount anymore, so that also needs to be addressed somehow.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Histogram not appearing on Python screen I am trying to plot a histogram on IDLE3 using the plotly library.
Here is my code:
import pandas as pd
import plotly.express as px

x = [84, 65, 78, 75, 89, 59, 90, 88, 83, 72, 91, 90, 73, 54]
df20 = pd.DataFrame(x, columns = ["x"])
hist20 = px.histogram(df20, x="x")
print(hist20)

However, instead of the histogram, what is printed out on shell was:
Figure({
    'data': [{'alignmentgroup': 'True',
              'bingroup': 'x',
              'hovertemplate': 'x=%{x}<br>count=%{y}<extra></extra>',
              'legendgroup': '',
              'marker': {'color': '#636efa'},
              'name': '',
              'offsetgroup': '',
              'orientation': 'v',
              'showlegend': False,
              'type': 'histogram',
              'x': array([84, 65, 78, 75, 89, 59, 90, 88, 83, 72, 91, 90, 73, 54]),
              'xaxis': 'x',
              'yaxis': 'y'}],
    'layout': {'barmode': 'relative',
               'legend': {'tracegroupgap': 0},
               'margin': {'t': 60},
               'template': '...',
               'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'count'}}}
})

A: You're trying to print() the histogram object, instead of calling its show() method, to actually render a histogram
change the print(hist20) to hist20.show().
hist20 = px.histogram(df20, x="x")
hist20.show()

This should open a browser and show the histogram. If you want to change the output maybe it's worth to take a look at the documentation.


text:
Q: no sqljdbc_auth in java.library.path I have a Java EE Web Application which connects to a SQL Server 2008 instance. I don't have any problem connecting and retrieving to all my tables, except for one of them. The error in the Tomcat log is:

WARNING: Failed to load the sqljdbc_auth.dll cause :- no sqljdbc_auth in java.library.path

A: The error is clear, isn't it?
You've not added the path where sqljdbc_auth.dll is present. Find out in the system where the DLL is and add that to your classpath.
And if that also doesn't work, add the folder where the DLL is present (I'm assuming \Microsoft SQL Server JDBC Driver 3.0\sqljdbc_3.0\enu\auth\x86) to your PATH variable.
Again if you're going via ant or cmd you have to explicitly mention the path using -Djava.library.path=[path to MS_SQL_AUTH_DLL]

A: 1) Download the JDBC Driver here.
2) unzip the file and go to sqljdbc_version\fra\auth\x86 or \x64
 3) copy the sqljdbc_auth.dll to C:\Program Files\Java\jre_Version\bin
 4) Finally restart eclipse

A: I've just encountered the same problem but within my own application.
I didn't like the solution with copying the dll since it's not very convenient so I did some research and came up with the following programmatic solution.
Basically, before doing any connections to SQL server, you have to add the sqljdbc_auth.dll to path.. which is easy to say:
PathHelper.appendToPath("C:\\sqljdbc_6.2\\enu\\auth\\x64");
once you know how to do it:
import java.lang.reflect.Field;

public class PathHelper {
    public static void appendToPath(String dir){

        String path = System.getProperty("java.library.path");
        path = dir + ";" + path;
        System.setProperty("java.library.path", path);

        try {

            final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths");
            sysPathsField.setAccessible(true);
            sysPathsField.set(null, null);

        }
        catch (Exception ex){
            throw new RuntimeException(ex);
        }

    }

}

Now integration authentication works like a charm :).
Credits to https://stackoverflow.com/a/21730111/1734640 for letting me figure this out.

A: I had to use windows authentication and I tried every suggested solution out there but with no success till I changed the name of the auth file as follows:
old-name: mssql-jdbc_auth-10.2.0.x64.dll
new-name: sqljdbc_auth.dll
And then it worked!
I looked up for this case to understand it more, apparently for Windows operating systems, the driver looks for sqljdbc_auth.dll by default.
Here is a useful link I've found:
https://learn.microsoft.com/en-us/sql/connect/jdbc/feature-dependencies-of-microsoft-jdbc-driver-for-sql-server?view=sql-server-ver15

A: Here are the steps if you want to do this from Eclipse :
1) Create a folder 'sqlauth' in your C: drive, and copy the dll file sqljdbc_auth.dll to the folder
1) Go to Run> Run Configurations
2) Choose the 'Arguments' tab for your class
3) Add the below code in VM arguments:
-Djava.library.path="C:\\sqlauth"

4) Hit 'Apply' and click 'Run'
Feel free to try other methods .

A: For easy fix follow these steps:

*

*goto: https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url#Connectingintegrated

*Download the JDBC file and extract to your preferred location

*open the auth folder matching your OS x64 or x86

*copy sqljdbc_auth.dll file

*paste in: C:\Program Files\Java\jdk_version\bin

*restart either eclipse or netbeans

A: To resolve I did the following:

*

*Copied sqljdbc_auth.dll into dir: C:\Windows\System32

*Restarted my application

A: I resolved the issue by:

*

*Upgrading com.microsoft.sqlserver from 6.1.0.jre8 to 10.1.0.jre8-preview:
<dependency>
     <groupId>com.microsoft.sqlserver</groupId>
     <artifactId>mssql-jdbc</artifactId>
     <version>10.1.0.jre8-preview</version>
</dependency>

*Adding missing dependency:
 <dependency>
     <groupId>net.sourceforge.jtds</groupId>
     <artifactId>jtds</artifactId>
     <version>1.3.1</version>
 </dependency>

*Using the following jdbc connection:

jdbc:sqlserver://;authenticationScheme=NTLM;integratedSecurity=true;domain=;databasename=;encrypt=true;trustServerCertificate=true;user=;password=


text:
Q: How can I set a custom font for the action bar text, and make it happen from startup? I can't get it done. My App starts with the standard font, the custom activity layout is inflated, and just then my font changes. As far as I know, I cannot directly code a custom font into the xml file of the layout I intend to inflate onto the action bar, so I got a code from another topic on the net about doing the change by referencing the TextView in the action bar and setting it in the class. Is there actually a way to make the font "standard", so that the app will already startup showing my custom font?
Here is the relevant code for the main activity, which I'm trying to change:
    public class Amd extends Activity {

    DatabaseHandler dh = new DatabaseHandler(this);
    public ProgressDialog mProgressDialog;
    public JSONObject jsonOb;
    public Filme m;
    public ArrayList<Genero> g;

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

    @SuppressLint("InflateParams") private void setActionBar(){
        this.getActionBar().setDisplayShowCustomEnabled(true);

        LayoutInflater inflator = LayoutInflater.from(this);
        View v = inflator.inflate(R.layout.custom_action_bar, null);

        Typeface font = Typeface.createFromAsset(this.getAssets(), "tcb.ttf");
        TextView textoActionBar = (TextView) getWindow().findViewById(Resources.getSystem().getIdentifier("action_bar_title", "id", "android"));
        textoActionBar.setTypeface(font);
        textoActionBar.setText("TESTE");
        this.getActionBar().setCustomView(v);
    }

Here is the styles xml, which I am also using to theme and color the action bar:
    <resources xmlns:android="http://schemas.android.com/apk/res/android">

    <!--
        Base application theme for API 14+. This theme completely replaces
        AppBaseTheme from BOTH res/values/styles.xml and
        res/values-v11/styles.xml on API 14+ devices.
    -->
    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <!-- API 14 theme customizations can go here. -->
        <item name="android:actionBarStyle">@style/PurpleActionBar</item>
    </style>

    <style name="PurpleActionBar" parent="@android:style/Widget.Holo.Light.ActionBar">
        <item name="android:background">#5D4480</item>
        <item name="android:titleTextStyle">@style/ActionText</item>
    </style>

    <style name="ActionText" parent="@android:style/TextAppearance">
        <item name="android:textColor">#975CE6</item>
    </style>

</resources>

Here is the manifest:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.virosys.amd"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme" >
        <activity
            android:name="com.virosys.amd.activities.Amd"
            android:label="AMD"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Here is the layout I'm inflating to the main activity:
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/Purple"
    tools:context="com.virosys.amd.activities.Amd" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/imageButton1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_marginLeft="4dp"
            android:layout_marginTop="4dp"
            android:layout_marginRight="2dp"
            android:layout_marginBottom="2dp"
            android:onClick="listasOuFilmes"
            android:scaleType="fitXY"
            android:background="@null"
            android:src="@drawable/filmes" />

        <ImageButton
            android:id="@+id/imageButton2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_marginRight="4dp"
            android:layout_marginTop="4dp"
            android:layout_marginLeft="2dp"
            android:layout_marginBottom="2dp"
            android:onClick="buscarFilme"
            android:scaleType="fitXY"
            android:background="@null"
            android:src="@drawable/busca" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="horizontal" >

        <ImageButton
            android:id="@+id/ImageButton3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_marginLeft="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="2dp"
            android:onClick="inserirFilme"
            android:scaleType="fitXY"
            android:background="@null"
            android:src="@drawable/noimage" />

        <ImageButton
            android:id="@+id/ImageButton4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_marginRight="4dp"
            android:layout_marginBottom="4dp"
            android:layout_marginLeft="2dp"
            android:layout_marginTop="2dp"
            android:scaleType="fitXY"
            android:background="@null"
            android:src="@drawable/config" />
    </LinearLayout>

</LinearLayout>

What else should I need to specify, or do you need any other code to understand what I'm trying to do?

A: Since Android ActionBar setTitle method receives a CharSequence as a parameter you can simply replace the call of your setActionBar() method with the next lines, that using span:
Typeface font = Typeface.createFromAsset(this.getAssets(), "tcb.ttf");
String actionBarTitle = "TESTE";
SpannableStringBuilder ssb = new SpannableStringBuilder(actionBarTitle);
ssb.setSpan(new CustomTypefaceSpan("", font), 0, actionBarTitle.length(), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
getActionBar().setTitle(ssb);

And don't forget to add this custom typeface span class into your project.
public class CustomTypefaceSpan extends TypefaceSpan {

    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }

        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(tf);
    }
}

A: What you want to do is create a custom class that extends TextView, then within the constructor set your default font. Then reference that custom textview in your xml instead of Androids TextView.


text:
Q: Filtering the distinct rows from Table I have a table with two columns schema as:
ID1,ID2

Values are as:
x y
y x
a b
b a

I just want resultset  as a whole like:
x y
a b

I want to remove duplicate
Need the sql query for the same.

A: One of the ways to achieve this is to use LEFT JOIN like this.
SQL Fiddle
Query
SELECT T1.ID1,T1.ID2
FROM YourTable T1
LEFT JOIN YourTable T2
ON T1.ID1 = T2.ID2
AND T1.ID2 = T2.ID1
AND T2.ID1 < T2.ID2
WHERE T2.ID1 IS NULL

Output
| ID1 | ID2 |
|-----|-----|
|   x |   y |
|   a |   b |

A: I suggest you to use EXISTS like this:
SELECT *
FROM yourTable t
WHERE NOT EXISTS(SELECT 1 FROM yourTable ti
                 WHERE t.ID1 = ti.ID2 AND t.ID2 = ti.ID1
                   AND ti.ID1 > ti.ID2)


text:
Q: Flask-SqlAlchemy query with order_by and pagination is very slow I use Python=2.7.3, PostgreSQL=9.3, Flask=0.10.0, SQLAlchemy=1.10.12, Flask-SQLAlchemy=2.1 and psycopg2=2.5.4
I have a 1 billion records table in PostgreSQL, and I have to paginate over it and provide search in it:
class MyTable(db.Model):
    """ My Table """
    id = db.Column(db.Integer, primary_key=True)
    code = db.Column(db.String(100), index=True, unique=True)
    name = db.Column(db.String(512), index=True)
    __tablename__ = 'my_table'

So i did the following in the code where i request data:
records = MyTable.query.filter(**filter_list).\
    order_by(asc('code')).paginate(page, per_page, False)

The point is it takes like 13 seconds to just select 10 last records for the last page if per_page=10 and page=1158960 even when there's no filtering at all.
From what i found in flask-sqlalchemy source, .paginate does it like this:
.order_by(asc('code')).limit(per_page).offset((page - 1) * per_page)

The resulting SQL query looks like this:
SELECT my_table.id, my_table.code, my_table.name
FROM my_table ORDER BY my_table.code ASC
LIMIT 10 OFFSET 1158960

When i fired it on a server console, i realized that the problem is in ORDER BY clause. Somehow it has to first sort the whole table with ORDER BY and only then LIMIT and OFFSET. But that's slow as hell.
EXPLAIN (ANALYZE):
"Limit  (cost=470520.26..470520.26 rows=1 width=178) (actual time=12460.060..12460.061 rows=8 loops=1)"
"  ->  Sort  (cost=467626.96..470520.26 rows=1157320 width=178) (actual time=11343.220..12424.686 rows=1158968 loops=1)"
"        Sort Key: code"
"        Sort Method: external merge  Disk: 218312kB"
"        ->  Seq Scan on my_table  (cost=0.00..42518.20 rows=1157320 width=178) (actual time=0.026..378.637 rows=1158968 loops=1)"
"Total runtime: 12475.160 ms"

If you just remove ORDER BY from that SQL request, it completes in 270ms!
"Limit  (cost=42518.20..42518.20 rows=1 width=178) (actual time=269.940..269.942 rows=8 loops=1)"
"  ->  Seq Scan on my_table  (cost=0.00..42518.20 rows=1157320 width=178) (actual time=0.030..246.200 rows=1158968 loops=1)"
"Total runtime: 269.992 ms"

Is there anything I can do about it?

A: Ok, I found a way to solve that.
When i do exactly the same query but with SET enable_seqscan=off; it forces PostgreSQL to use Index Scan instead of Sequence Scan, and it gets much faster!
SET enable_seqscan=off;
SELECT my_table.id, my_table.code, my_table.name
FROM my_table ORDER BY my_table.code ASC
LIMIT 10 OFFSET 1158960

**EXPLAIN (ANALYZE):**

"Limit  (cost=1814764.86..1814777.39 rows=8 width=131) (actual time=616.543..616.545 rows=8 loops=1)"
"  ->  Index Scan using ix_my_table_code on my_table  (cost=0.43..1814777.39 rows=1158968 width=131) (actual time=0.065..590.898 rows=1158968 loops=1)"
"Total runtime: 616.568 ms"

So now the point is - how do I set PostgreSQL config to make it use Index Scan without forcing it? I guess the answer is - "Planner Cost Constants". Any advices about them?
UPDATE 13.04.2016:
I finally figured out the situation and found a solution. In my case, everything is solved by setting Planner Cost Constants like this in postgresql.conf:
seq_page_cost = 1.0
random_page_cost = 1.0
cpu_tuple_cost = 0.01
cpu_index_tuple_cost = 0.0001
cpu_operator_cost = 0.0025
effective_cache_size = 1024MB

Also, there're many advises to set effective_cache_size as 3/4 from a server entire RAM. Anyway, with these settings Planner always uses Index Scan on Huge tables. So timing is now 200-300ms.
Problem Solved.


text:
Q: Confusion over argument dependent lookup and friend function definition I have the following program:
struct Foo {
    friend void foo (int) {}
    operator int () const { return 0; }
};

int main() {
    foo(Foo());  // This compiles fine
    foo(0);      // This fails to find `foo()`
    return 0;
}

I could not figure out what part of the standard defines the ADL rule that says the call to foo(0) should fail, while the call to foo(Foo()) should succeed. Can someone shed some light?

A: Reopened over my own deletion, eh? Well, after some prompting from juanchopanza, I read over the relevant part of the standard, C++11 §3.4.2, more carefully. I browsed it way too quickly before. To wit, paragraph 2 spells out:

For each argument type T in the function call, there is a set of zero or more associated namespaces and a set of zero or more associated classes to be considered. The sets of namespaces and classes is determined entirely by the types of the function arguments (and the namespace of any template template argument). Typedef names and using-declarations used to specify the types do not contribute to this set. The sets of namespaces and classes are determined in the following way:

*

*If T is a fundamental type, its associated sets of namespaces and classes are both empty.

*If T is a class type (including unions), its associated classes are: the class itself; the class of which it is a member, if any; and its direct and indirect base classes. Its associated namespaces are the namespaces of which its associated classes are members. Furthermore, if T is a class template specialization, its associated namespaces and classes also include: the namespaces and classes associated with the types of the template arguments provided for template type parameters (excluding template template parameters); the namespaces of which any template template arguments are members; and the classes of which any member templates used as template template arguments are members.

  ...

The first bullet explains why passing in an int argument fails. The second bullet explains why passing in a Foo instance works.

A: Looking at your code:
int main() {
    foo(Foo());  // This declares a global function "foo" taking a "Foo" as an argument
    foo(0);      // "foo" takes a "Foo" above, and theres no way to convert an int to a Foo...


text:
Q: Grails and release plugin I'm trying to use the release 2.0.4 plugin to deploy my war through grails 2.1.1 to artifactory server.
My BuildConfig.groovy has:
grails.project.repos.snap.url = "http://server:8080/artifactory/apps-snapshot-local"
grails.project.repos.snap.username = "user"
grails.project.repos.snap.password = "password"

grails.project.repos.rel.url = "http://server:8080/artifactory/apps-release-local"
grails.project.repos.rel.username = "user"
grails.project.repos.rel.password = "password"

grails.project.repos.default = "rel"

When I just do the "grails maven-deploy" it works and deploys to my rel server as expected.  When I try to override the default target through the command line I get failures.
grails maven-deploy --repository=snap

I get this:
| Done creating WAR snap
| POM generated: C:\dev-git\DBUpdateWeb\target/pom.xml.
| Error Error deploying artifact: C:\dev-git\DBUpdateWeb\target\DBUpdateWeb.war (The system cannot find the file specified)
| Error Have you specified a configured repository to deploy to (--repository argument) or specified distributionManagement in your POM?

When I do specify the --repository tag it doesn't generate a war even though it says it did.  Any help is appreciated.  Thanks in advance.

A: Try grails maven-deploy "--repository=snap".
Also, specify app.version in application.properties so that the WAR will be standard compliant  (1.0-SNAPSHOT for publishing to the snapshots repository and 1.0 for releases), and comment out the grails.project.war.file line in BuildConfig.groovy.


text:
Q: Elasticsearch: Could not find Java SE Runtime Environment I am installing Elasticsearch using Docker on ubuntu 20.04 machine and stuck with the below error:
Timeout when waiting for :9200

When I look at log file in docker container it says:
{"log":"Error: could not find libjava.so\n","stream":"stderr","time":"2022-04-22T06:43:58.535576027Z"}
{"log":"Error: Could not find Java SE Runtime Environment.\n","stream":"stderr","time":"2022-04-22T06:43:58.536155015Z"}

My docker-compose-elk.yml file looks like:
version: '3.7'

services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.7.0
    container_name: kypo-elasticsearch
    restart: unless-stopped
    environment:
     - node.name=es01
     - bootstrap.memory_lock=true
     - discovery.type=single-node
     - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
     memlock:
       soft: -1
       hard: -1
   volumes:
      - data_elasticsearch:/usr/share/elasticsearch/data
 logstash:
   image: docker.elastic.co/logstash/logstash:7.7.0
   container_name: kypo-logstash
   restart: unless-stopped
   volumes:
  - ./configuration/logging-logstash/logstash-pipelines:/usr/share/logstash/pipeline/
  - ./configuration/logging-logstash/kypo-logstash.yml:/usr/share/logstash/config/logstash.yml
  - ./configuration/logging-logstash/kypo-logstash-pipelines.yml:/usr/share/logstash/config/pipelines.yml
depends_on:
  - elasticsearch
volumes:
  data_elasticsearch:
  name: data-elasticsearch

networks:
  default:
    external:
      name: "kypo-platform-net"


text:
Q: Discord Python v2.0 | Pre-Select in Selection Menu I am developing a DiscordBot in python with the Version 2.0
So, I have some Selection Menus, which I want to connect with a JSON.
Example:
file = open("./data/streamplan.json", "r")
data = json.load(file)
file.close()

list_monday = Select(placeholder="Montag:")
online_option = discord.SelectOption(label="Stream", value="online", emoji = "", description="Montag")
offline_option = discord.SelectOption(label="Stream", value="offline", emoji = "", description="Montag")
maybe_option = discord.SelectOption(label="Stream", value="maybe", emoji = "", description="Montag")
list_monday.callback = SelectionHandler.slc_streamplan_monday
list_monday.append_option(online_option)
list_monday.append_option(offline_option)
list_monday.append_option(maybe_option)

I want that my Bot already pre-Selects the option (online,offline,maybe) on start.
How can I do this?

A: SelectOption has a default attribute that you can set/pass as well.
Docs: https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=selectoption#discord.SelectOption.default

Whether this option is selected by default.

Also, consider subclassing instead of manually overwriting the callback attribute. This is a really ugly way to go about it. There's an example on GitHub.


text:
Q: How do I write a SQL query to select rows from an ODBC source? I'm fairly new to SQL, and MSSQL in particular. I'm looking for a way to select certain rows from an ODBC data source I have already set up into a table.  Something along the lines of:
SELECT
<somecolumns>
INTO
<target_table>
FROM
[ODBC_data_source].sourcetable

I should also mention that the data source is properly configured, and I can import from it with the Import Wizard. Is what I have above possible, or do I need to look for other solutions?

A: Are you going to be accessing this data source a lot? If so, you might want to look into using a linked server: http://msdn.microsoft.com/en-us/library/ms188279.aspx
If it's just a one time or very infrequent thing then you can use OPENROWSET assuming the ODBC exists on the server itself: http://msdn.microsoft.com/en-us/library/aa276850(v=sql.80).aspx

A: SELECT column1, column2
INTO new_table_name [IN externaldatabase]
FROM old_tablename

Ok, but you want to pull certain ROWS into a new table.  For that just add a WHERE clause:
SELECT column1, column2
INTO new_table_name [IN externaldatabase]
FROM old_tablename
WHERE Name in('Mark','Luke',etc)


text:
Q: How can I stop execution of remainder of code on a frame? AS3 Using the goto command does not stop the current execution
for example if I have
gotoAndStop(2);
trace("1");

The application will still perform trace command and then move to frame 2. I would like to know if there is any such command that immediately ceases the execution of any code left in the frame?

A: You can use the
return;

instruction to break the execution of the frame script.


text:
Q: Firefox Download limit I know you can queue up all the downloads in firefox and if you keep adding them, they just keep downloading.
I know I can pause a download and let one finish and then start the other one.
But is there a way, maybe an entry in about:config that can help me limit how many downloads to allow going on.
I know I can use a download manager but I'm just curious about this.
I am not asking for a bandwidth limit tip but instead a download number limit tip.
Thanks.

A: Try finding network.http.max-connections-per-server in about:config and reducing the value.

A: There are two limits in Firefox (and all XulRunner apps) - Maximum number of connections overall, and max connections per server.
see network.http.max-connections and network.http.max-connections-per-server in about:config
(Adding to Damian's answer; will vote his up once I have some rep...)

A: I'd use a download manager - something like download them all - this will give you the control you're after, and a bunch more.
Limiting your max-connections will do the job, but if I understand correctly will also limit how many files you can download when browsing and slow down web-pages (probably not the effect you're after).


text:
Q: How to send email from Windows Mobile 5.0 i am trying to create a simple email sending application for windows phone in visual studio 2008, so please tell me which classes or methods do i have to use.
i tried this but it didn't work:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Configuration;
using System.Xml;

      try
        {
            Application.DoEvents();
            // setup mail message
            MailMessage message = new MailMessage();
            message.From = new MailAddress(textBox1.Text);
            message.To.Add(new MailAddress(textBox2.Text));
            message.Subject = textBox3.Text;
            message.Body = textBox5.Text;

            // setup mail client
            SmtpClient mailClient = new SmtpClient("smtp.gmail.com");
            mailClient.Credentials = new NetworkCredential(textBox1.Text, textBox4.Text);
            mailClient.Send(message);

            MessageBox.Show("Sent");

        }
        catch (Exception)
        {
            MessageBox.Show("Error");
        }

I am getting these errors:
Error   1   The type or namespace name 'MailMessage' could not be found (are you missing a using directive or an assembly reference?)
Error   2   The type or namespace name 'MailMessage' could not be found (are you missing a using directive or an assembly reference?)
Error   3   The type or namespace name 'MailAddress' could not be found (are you missing a using directive or an assembly reference?)
Error   4   The type or namespace name 'MailAddress' could not be found (are you missing a using directive or an assembly reference?)
Error   5   The type or namespace name 'SmtpClient' could not be found (are you missing a using directive or an assembly reference?)
Error   6   The type or namespace name 'SmtpClient' could not be found (are you missing a using directive or an assembly reference?)
Error   7   The type or namespace name 'SmtpClient' could not be found (are you missing a using directive or an assembly reference?)
Error   8   The type or namespace name 'SmtpClient' could not be found (are you missing a using directive or an assembly reference?)

A: The .NET Compact framework doesn't support System.Net.Mail or System.Web.Mail. You can use an extension such as http://www.opennetcf.com/library/sdf/html/7e16eccb-dc9e-4559-c79c-cfaad631ac15.htm or call out to a service that will send the e-mail on your behalf.

A: To send mail etc on windows mobile you have to start a VisualStudio C#/VB SmartDevice Project.
Mail etc can be accessed via the namespace microsoft.windowsmobile.pocketoutlook. You have to add a reference to your Windows Mobile 5 (or higher) SDK directory containing the WindowsMobile assemblies.
http://msdn.microsoft.com/en-us/library/microsoft.windowsmobile.pocketoutlook.aspx
Here is a bare snippet without the needed stuff to first open a poom account etc.:
http://cjcraft.com/blog/2008/10/02/how-to-open-a-mail-in-inbox-using-pocket-outlook/


text:
Q: Keras Lstm predicting next item, taking whole sequences or sliding window. Will sliding window need stateful LSTM? I have a sequence prediction problem in which, given the last n items in a sequence I need to predict next item.
I have more than 2 million  sequences  each with different timesteps (length of sequence), like some are just 5 and some are 50/60/100/200 upto 500.
    seq_inputs = [
    ["AA1", "BB3", "CC4",…,"DD5"], #length/timeteps 5
    ["FF1", "DD3", "FF6","KK8","AA5", "CC8",…, "AA2"]   #length/timeteps 50
   ["AA2", "CC8", "CC11","DD3", "FF6","AA1", "BB3",……,"DD11"]#length/timesteps 200
    ..
    ..
    ] # there are 2million + of them

For prediction next item in sequence, I trim sequences to 60 maximum length with post/pre padding and just take last element of all sequences
for e.g, X's will be
[[0,0,0,….,'AA1', 'BB3', 'CC4'],#lenght 60
 [0,0,0,….,'FF1', 'DD3', 'FF6', 'KK8', 'AA5', 'CC8'],#lenght 60
 [0,0,0,….,'AA2', 'CC8', 'CC11', 'DD3', 'FF6', 'AA1', 'BB3']#lenght 60
 ....
 ]

and y is last element
['DD5', 'AA2', 'DD11',...]

First I tokenise them and convert them in numeric form using keras tokenizer.text_to_sequence()and reshape them to 60 time steps and one feature for every sequence:**
X = [
    [[0],[0],[0],[0],[1], ..., [10], [200], [5], [3], [90] ],
    [[0],[0],[0],[0],[95],...,  [15], [4],[11],[78], [43]]
    ..
    ..
    ]
y = [40,3, ... , ... ]

I am using LSTMs with embedding like below
model = Sequential()
model.add(Embedding(vocabulary_size, 32, input_length=seq_len)) #seq_length
model.add(LSTM(80,return_sequences=True))
..
..
model.fit(train_inputs,train_targets,epochs=50,verbose=1,batch_size=32)

For my problem of predicting next item in sequence, should  this approach (of trimming sequences to 60 max length with post/pre padding and just taking last item as target) good?
As target will be different timestep for each like 5th,50th,200th and so on , in my example.
Should I make every sequence n-gram/sliding window? For example for this first sequence of of my dataset
   ["AA1", "BB3", "CC4",…,"DD5"]

Sliding window of 5 , first example will be will be converted as
seq_inputs = [
   [0,0,0,0,"AA1"]
   [0,0,0,"AA1", "BB3"]
   [0,0,"AA1", "BB3","CC4"],
…,
...
]

And similarly others will also be converted to sliding windows.
To summarise the problem and questions again:
With current approach, taking last element as y, I am struck at 30 validation accuracy, but my concern is not performance, my concern is if I am doing it right. So, Need guidance on following

*

*Since I need to predict next item in sequence, is taking last item  as output for each sequence right approach?

*Since my input length varies (from 5 to 500) and I am restricting it to 60 timesteps, should I increase or decrease it?

*Instead of taking whole sequence should I take sliding window approach like I shared?

*Will I need to have stateful LSTM in case of sliding windows?


text:
Q: How to print all functions of JavaScript non-objects? If I have var foo = 'bar';, how do I get all the functions callable on foo, such as toUpperCase? It's not an object, so Object.getOwnPropertyNames(foo) doesn't work:
$ node
> var foo = 'bar';
undefined
> console.log(Object.getOwnPropertyNames(foo));
TypeError: Object.getOwnPropertyNames called on non-object
    at Function.getOwnPropertyNames (native)
    at repl:1:20
    at REPLServer.eval (repl.js:80:21)
    at repl.js:190:20
    at REPLServer.eval (repl.js:87:5)
    at Interface.<anonymous> (repl.js:182:12)
    at Interface.emit (events.js:67:17)
    at Interface._onLine (readline.js:162:10)
    at Interface._line (readline.js:426:8)
    at Interface._ttyWrite (readline.js:603:14)

katspaugh's simple, elegant solution:
> console.log(Object.getOwnPropertyNames(foo.constructor.prototype));
[ 'constructor',
  'length',
  'toLowerCase',
  ... ]
undefined

A: The methods you want are on the String.prototype, the prototype of all strings, ruler of Valindor.
Object.getOwnPropertyNames('baz'.constructor.prototype)

A: use can use the below:
$(document).ready(function () {
    var foo = 'bar';
    var div = '';
    var ob = Object.getOwnPropertyNames(foo.constructor.prototype);
    for (var i = 0; i < ob.length; i++) {
        div += ob[i] + "<br/>";
    }
    $(selector).html(div);
});

A: Use eclipse :)
Or just look here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String


text:
Q: How can I receive gps broadcast from a pc on ipad? I want to build a app with openstreetmap which can receive the position through a flight simulator.
I have prepar3d flight sim that broadcasts gps signal on local network i.e 192.168.1.10:5555 . I have other flight sim apps that can read these broadcast and use it in their apps. If I were to build it from scratch how can I do it ? I am using flutter


text:
Q: property_exists() to check if static property exists inside class method I have a class with static properties and methods. One of my methods is a dynamic property grabber. I want to do this dynamically to prevent having a method for each property that I want to return. A single method would be nicer.
My problem is the method returns "Undefined Property". I have tried various solutions on the internet, but nothing seems to fit or work.
Class example:
class Generic
{
    public static $propA = "A";
    private static $propB = "B";
    protected static $propC = "C";

    public static function getProperty(string $property): string
    {
        if (!property_exists('Generic', $property)) :
            return "Undefined Property";
        endif;

        return self::$$property;
    }
}

Usage:
print_r(Generic::getProperty('propA'));

This returns as if the property does not exist. In fact, the visibility doesn't matter as they all return as if they don't exist. Additionally, I know this works when not using static variables. I would rather continue to use static variables.

A: Updating my code from above to include namespaces. This was the problem that was causing the method to return undefined.
The updated code is as follows:
class Generic
{
    public static $propA = "A";
    private static $propB = "B";
    protected static $propC = "C";

    public static function getProperty(string $property): string
    {
        if (!property_exists('JLDN\Generic', $property)) :
            return "Undefined Property";
        endif;

        return self::$$property;
    }
}

foreach (['propA', 'propB', 'propC', 'nonProperty'] as $prop) :
    printf("
Property: %s::%s - %s
\n", 'Generic', $prop, print_r(Generic::getProperty($prop), true));
endforeach;

Output:
Property: Generic::propA - A

Property: Generic::propB - B

Property: Generic::propC - C

Property: Generic::nonProp - Undefined Property


text:
Q: trimming String when specific char found on String, is it possible? let's say I have this String:
String myString = "violet are blue|roses are red|this is a terrible poet";

I would like to trim the String whenever it found the char '|'. So when the code is executed, myString would be:
myString = "roses are red|this is a terrible poet";

and finally
myString = "this is a terrible poet";

is it possible?

A: private string trimString(string s)
{
   int index = s.IndexOf("|");
   return s.Substring(index+1); //returns string from this index to the end of string
}

usage
String myString = "violet are blue|roses are red|this is a terrible poet";

myString = trimString(myString);

A: You can do as below:
 string [] stringparts mystring.spilt('|');

stringsparts can be used to print whatever you want from it.

A: Using String.Split() Method;
//Single Line Solution
string newString1 = myString.Split('|').Last();

//Another way
string[] arr = myString.Split('|');   //Split the string by | into an array
string newString2 = arr[arr.Length-1]; //Get the last element of the splited array

Console.WriteLine(newString1);

A: You can use Substring method for this, perhaps you may want to use it as extension method. Code including trimming to first (left) and trimming to last (right) |:
public static class StringExtensions
{
    public static string TrimToFirst(this string s)
    {
        int index = s.IndexOf('|');
        if(index >= 0)
        {
            s = s.Substring(index + 1);
        }
        return s;
    }

    public static string TrimToLast(this string s)
    {
        int index = s.LastIndexOf('|');
        if(index >= 0)
        {
            s = s.Substring(index + 1);
        }
        return s;
    }
}

// usage
string myString = "violet are blue|roses are red|this is a terrible poet";
Console.WriteLine(myString.TrimToLast());
// outpus: this is a terrible poet

A: string myString = "violet are blue|roses are red|this is a terrible poet";
var elements = myString.Split(new char[] { '|' }).Skip(1);

StringBuilder sb = new StringBuilder();
foreach (var element in elements)
{
    sb.Append(element);
    sb.Append("|");
}

string result = sb.Remove(sb.Length - 1, 1).ToString();

Console.WriteLine(result);

A: Here is one of the 100,000000 ways to do this
string myString = "violet are blue|roses are red|this is a terrible poet";
string result = myString.Contains('|') ? myString.Substring(myString.IndexOf('|')).TrimStart('|') : myString;

A: A short way of implementing it:-
myString = myString.Substring(myString.LastIndexOf("|") + 1);


text:
Q: Macbook SSD Formatting Problem I just got my Macbook here, and I got a USB with Yosemite 10.10.
I opened up the Macbook, took out the old one, and put the SSD inside.
My SSD fits perfectly (Samsung SSD 850 EVO 250GB).
Then I plug the USB thumb drive in, and then boot the computer up, and holding the ALT (OPTION) key down. Then I came into the drives that I can boot from. I couldn't see my SSD there, then I took the thumb drive(8GB), and then I began to install Yosemite, after I choose the language, I need to choose where I need to install Yosemite. The hard drive, didn't show up there either.
I get in Disk Utility and find out that my hard drive, isn't formatted, I just want to format it to Mac OS Extended Journaled, I chose it, and clicked erase and when I did that, I got this error:

Erasing the disk failed, Erasing the disk failed with error:
Formatting the file system failed.

I translated the error from Danish, so it could be worded differently on the English version of Disk Utility.
Note: The Mac is not new, the SSD is new and never used.

A: You have to format the SSD without using it as your primary disk.
If you're able to run Mac with the old disk, connect the SSD via external enclosure and format it (or make a clone of the running HDD).
After this swap the disks, boot form installer and install OS on SSD.


text:
Q: Logging the client IP with Nginx/Varnish/Apache I have Nginx listening on port 443 as an SSL terminator, and proxying unencrypted traffic to Varnish on the same server. Varnish 3 is handling this traffic, and traffic coming in directly on port 80. All traffic is passed, unencrypted, to Apache instances on other servers in the cluster. The Apache instances use mod_rpaf to replace the logged client IP with the contents of the X-Forwarded-For header.
My problem is that if the traffic is coming via Nginx, while the 'correct' client IP is getting logged in the VarnishNCSA logs, it looks as if Varnish is (understandably) replacing Nginx's X-Forwarded-For header with 127.0.0.1 downstream, and this is getting logged with Apache. Is there a nice simple way to stop Varnish rewriting X-Forwarded-For if it's already populated?

A: Absolutely; the Varnish handling of X-Forwarded-For is actually just defined in the default vcl_recv function.
if (req.restarts == 0) {
    if (req.http.x-forwarded-for) {
        set req.http.X-Forwarded-For =
    req.http.X-Forwarded-For + ", " + client.ip;
    } else {
        set req.http.X-Forwarded-For = client.ip;
    }
}

The default definition of a function is always appended to one you've defined in your active VCL file, but if your defined function always handles a request, then the default logic will never execute.
Set a vcl_recv along these lines:
sub vcl_recv {
    /* Your existing logic goes here */
    /* After that, we'll insert the default logic, with the X-Forwarded-For handling removed */
    /* The return (lookup); at the end ensures that the default append behavior won't have an impact */

    if (req.request != "GET" &&
      req.request != "HEAD" &&
      req.request != "PUT" &&
      req.request != "POST" &&
      req.request != "TRACE" &&
      req.request != "OPTIONS" &&
      req.request != "DELETE") {
        /* Non-RFC2616 or CONNECT which is weird. */
        return (pipe);
    }
    if (req.request != "GET" && req.request != "HEAD") {
        /* We only deal with GET and HEAD by default */
        return (pass);
    }
    if (req.http.Authorization || req.http.Cookie) {
        /* Not cacheable by default */
        return (pass);
    }
    return (lookup);
}

Edit:
Since Varnish handles some connections directly as well, a better approach might be to have it selectively set the header.  You'll still want include the full vcl_recv so that the default doesn't apply its own header, but include this at the top:
if (req.restarts == 0) {
    if (!req.http.x-forwarded-for) {
        set req.http.X-Forwarded-For = client.ip;
    }
}


text:
Q: Are setState callbacks NOT invoked then the update itself is overridden by a different update? I have a slider that invokes a function when onChange is called.
The function changes an 'expensive' state that many components depend on, and calls additional state dependent functions in it's callback block.
I assume that due to asynchronous nature of setState is it possible that
dragging the slider can result in seemingly simultaneous setState updates, such that only one of the update is accepted.
If that is the case, can I guarantee that only the callback of the accepted newState is invoked? It is important that the callback matches the current state.
Edit: An example
class Example extends React.Component {
  constructor() {
   super();
   this.state = {
     v: 0,
     w: 0
   };
  }

  onChange = v => {
   this.setState(
    () => {
     return { v: v };
    },
    () => {
     this.stateDependentFunction();
    }
   );
  };

  stateDependentFunction = () => {
   let v = this.state.v;
   this.setState({ w: 5 * v + 1 });
  };

  render() {
    return (

      <Slider
       disabled={false}
       min={0}
       max={1000}
       defaultValue={0}
       onChange={this.onChange}
      />
      Value: {this.state.v}

      Value2: {this.state.w}

   );
  }
}

A:
I assume that due to asynchronous nature of setState is it possible that dragging the slider can result in seemingly simultaneous setState updates, such that only one of the update is accepted.

All state updates will be accepted even if they have no visible effect, because they are triggered asynchronously. A way to not cause excessive amount of state updates is to debounce event listener, e.g. with Lodash debounce.
stateDependentFunction doesn't need to be executed after previous setState has ended, this will result in 2 state updates, while this could be handled with single update. Updater function allows to queue state updates. stateDependentFunction is an antipattern, this.state shouldn't be used with setState because this may result in race conditions, this is what updater function is for.
It can be:
  onChange = debounce(v => {
   this.setState({ v }); // doesn't need updater function
   this.stateDependentFunction();
  }, 50);

  stateDependentFunction = () => {
   this.setState(({ v }) => ({ w: 5 * v + 1 })); // needs updater function
  };


text:
Q: why input element doesn't regain the focus after the component re-renders? Below is the code:
export class Editor extends Component {
   constructor(props) {
      super(props);
      this.state = {
         name: ""
      }
   }

   handleChange = (event) => {
        event.persist();
        this.setState({ name: event.target.value });
   }

   render() {
      ...
       <input name="name" autoFocus={true} value={this.state.name} onChange={this.handleChange} />
       <button onClick={this.handleAdd}>
          Add
       </button>
   }
}

So the first time the component renders, the input element did have focus since I use autoFocus={true}. But after I clicked the button, the focus didn't go back to the input but stayed on the button. My question is:
Why the input didn't regain the focus? Since onClick handler updated the component's state, which makes the component re-render again, when the component re-renders, isn't that autoFocus={true} will re-apply as well?

A: If you use autoFocus, only the initial render will have focus. Since React intelligently only re-renders elements that have changed, the autofocus attribute isn't reliable in all cases.
It would be easier if you used a functional component, but you can do the following in the class component.
export class Editor extends Component {
   constructor(props) {
      super(props);
      this.state = {
         name: ""
      }
      this.nameInput = React.createRef();
   }

   handleChange = (event) => {
        event.persist();
        this.setState({ name: event.target.value });
   }

   handleAdd = () => {
       this.nameInput.current.focus();
   }

   render() {
      ...
       <input ref={this.nameInput} name="name" autoFocus={true} value={this.state.name} onChange={this.handleChange} />
       <button onClick={this.handleAdd}>
          Add
       </button>
   }
}

If you want to see another approach you can look here: https://stackoverflow.com/a/54159564/5562701
and
https://davidwalsh.name/react-autofocus

A: No, it does not because react only re-renders elements that have changed, David Walsh explains this very well, you may want to check this. Happy coding!


text:
Q: How to define Models for Serverless Api functions in CloudFormation template See below for related part of my template. I don't know how to set Models for Api. If I leave the Models part out from MyApi, 'sam deploy' says: "the related API does not define any Models". So how do I add models for Api and as function request models?
Secondary questions:
Can the models be defined in external json/yaml files?
How can I define model for the response?
Can I introduce models in separate template file?
Thanks.
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: test
      Models:
        ???

  PostNewItem:
    Type: AWS::ApiGateway::Model
    Properties:
      RestApiId: !Ref MyApi
      Name: PostNewItem
      ContentType: application/json
      Schema:
        $schema: 'http://json-schema.org/draft-04/schema#'
        title: NewItemModel
        type: object
        properties:
          name:
            type: string
          description:
            type: string
          ....

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      ...
      Events:
        AddItem:
          Type: Api
          Properties:
            Path: /item
            Method: post
            RestApiId:
              !Ref MyApi
            RequestModel:
              Model: !Ref PostNewItem
              Required: true

A: To answer my own question, with Serverless, there is no need for AWS::ApiGateway::Models but instead you define them with Api.
 MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: test
      Models:
        PostPointModel:
          type: object
          required:
            - name
          properties:
            name:
              type: string
            description:
              type: string


text:
Q: What is the use of Id in spring cloud gateway routes? Spring cloud gateway accepts id in route builder. I am not able to figure it out what is the use of id in route builder.
spring:
  cloud:
    gateway:
      routes:
      - id: my_route
        uri: http://localhost:8081
        predicates:
        - Cookie=mycookie,mycookievalue
      - id: my_route
        uri: http://localhost:8081
        predicates:
        - Cookie=mycookie,mycookievalue1

both of the above routes work properly. I am not sure what`s the use of id then? my assumption was id should be unique across routes.


text:
Q: Magento 2 : Phpunit test for catalog module, mock error for setExtensionAttributes() Magento 2 phpunit test for catalog module error display below:
I want to run test for catalog model folder files,
Run phptest using command like:
var/www/html/magento2/vendor/phpunit/phpunit$ php phpunit /var/www/html/magento2/vendor/magento/module-catalog/Test/Unit/Model/

Result for above command display error:
Magento\Catalog\Test\Unit\Model\CustomOptions\CustomOptionProcessorTest::testConvertToBuyRequest
PHPUnit_Framework_MockObject_RuntimeException: Cannot mock Magento\Quote\Api\Data\CartItemInterface::setExtensionAttributes() because a class or interface used in the signature is not loaded

i am using magento catalog native module for phpunit test and error are display after run test.

A: It looks like you run this command line without phpunit.xml.dist:
Try to use this command line:
var/www/html/magento2/vendor/phpunit/phpunit$ php phpunit -c dev/tests/unit/phpunit.xml.dist /var/www/html/magento2/vendor/magento/module-catalog/Test/Unit/Model/
I've included here explicit declaration of phpunit config file
-c dev/tests/unit/phpunit.xml.dist.
Be sure that you always include a phpunit config file for appropriate tests, when invoke them. It's applicable for unit tests , integration tests, etc., cause phpunit config files contains code, that set up a test environment.


text:
Q: Closing a Task Tray app I have a set of server apps that run in the task tray.  I'm trying to write a little server management app in c# that can gracefully close the applications.  However I'm having trouble figuring out how to do it.
I can get the process (an instance of the Process class).  Calling Process.CloseMainWindow() doesn't work.  You don't get a Process.MainWindowHandle for a task tray process (it's zero, and is documented that this is the case), so I can't send, say, a WM_SYSCOMMAND, SC_CLOSE message.
I can Kill() it, but that's not graceful.  Any ideas?  The server apps are written in Delphi Win32.  I can modify them.

A: You could use pipes to send them messages.

A: You could iterate the windows with EnumWindows to find the hidden window that is associated with the tray icon.  That's all rather fugly and error prone.  Do this cleanly, have these 'server apps' create a named pipe.  You can connect to them in your manager app by using the well-known name and then send them a command.  System.IO.Pipes namespace.


text:
Q: jbpm Error while creating JAXB Marshaller due to 580 counts of IllegalAnnotationExceptions I am getting an error while I add external jars in JBPM KIE Work Bench and while I try to create a process. If I don't add the external jars, everything is working fine.

2019-08-30 21:19:37,718 ERROR [org.kie.server.api.marshalling.jaxb.JaxbMarshaller] (default task-9) Error while creating JAXB Marshaller due to 580 counts of IllegalAnnotationExceptions: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 580 counts of IllegalAnnotationExceptions
  org.apache.activemq.transport.tcp.TcpTransport$2 is a non-static inner class, and JAXB can't handle those.
      this problem is related to the following location:
          at org.apache.activemq.transport.tcp.TcpTransport$2
  org.apache.activemq.filter.Expression is an interface, and JAXB can't handle interfaces.
      this problem is related to the following location:
          at org.apache.activemq.filter.Expression
          at public org.apache.activemq.filter.Expression org.apache.activemq.filter.BinaryExpression.getLeft()
          at org.apache.activemq.filter.BinaryExpression
          at org.apache.activemq.filter.LogicExpression
          at org.apache.activemq.filter.LogicExpression$2
  Two classes have the same XML type name "". Use @XmlType.name and @XmlType.namespace to assign different names to them.
      this problem is related to the following location:
          at org.apache.activemq.transport.tcp.TcpTransport$2
      this problem is related to the following location:
          at org.apache.activemq.filter.LogicExpression$2
  Two classes have the same XML type name "baseDataStreamMarshaller". Use @XmlType.name and @XmlType.namespace to assign different names to them.

I am using JBPM 7.8.0


text:
Q: How do I store a SQL statement into a variable I am currently facing a problem here. I have a column called "DESC1" in a table called "Master". I'm trying to retrieve the value based on something along the lines of this...
"Select DESC1 FROM Master WHERE '" & TextBox1.Text & "' "

And I'm trying to display on the excel beside both correctString1 and correctString
 oWB.Sheets(1).Range("A2", "K2").Insert(Shift:=Excel.XlDirection.xlDown)
 oWB.Sheets(1).Range("E2").Value = " " & correctString1 & " : " &  correctString & " "

Hope you can help me out.

A: Dim sqlConnection1 As New SqlConnection("Your Connection String")
Dim cmd As New SqlCommand
Dim reader As SqlDataReader

cmd.CommandText = "Select DESC1 FROM Master WHERE '" & TextBox1.Text & "' "
cmd.CommandType = CommandType.Text
cmd.Connection = sqlConnection1

sqlConnection1.Open()
reader = cmd.ExecuteReader()
' Data is accessible through the DataReader object here.

If reader.HasRows Then
        Do While reader.Read()
            Console.WriteLine(reader.GetInt32(0) _
              & vbTab & reader.GetString(1))
        Loop
    Else
        Console.WriteLine("No rows found.")
    End If
sqlConnection1.Close()

Considering first column is NUMBER type and second column is VARCHAR
Read more
==Update==
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"

See more


text:
Q: java escape unicode to char php I am working on a webapp and need to display a string of text from the database.
Now I ran in to the problem that my sting contains unicodes like \u0099. I am using c# to put data in the database and thik it is an java escape unicode from doing my reserch.
\u0099 is the TM char when put in. How can I make it so that php makes the sttring so that it uses characters instead of an unicode.
String example:
$string = "This is my string :) company_name\u0099";

A: Try this one:
$string = "This is my string :) company_name\u0099";
$decoded = preg_replace('/\\\\u([a-fA-F0-9]{4})/', '&#x\\1;', $string);
echo mb_convert_encoding($decoded, 'UTF-8', 'HTML-ENTITIES');


text:
Q: Managing bitmaps and memory cache in android app We have an application that displays a lot of images in a grid at once
Lets say a grid of 50-60 pictures each one takes a 1/4 of a screen
We use picasso library to manage them.
My current understanding is:

*

*Once we load the picture it is stored in memory in ARGB8888 format, thus 4 bytes per pixel

*Each picture is 1/4 of the screen, so on 1080 screen this is 960x540x4 ~- 2MB per bitmap

*This means total memory needed to keep 60 pictures is 120MB, which is way more than what can be allocated for picasso memory cache from the app heap (and likely more than the app heap itself on many systems)

Which means that by the time we scroll the grid to the right, pictures on the left are being evicted from the memory cache so when we quickly scroll back to the left we see them being loaded again from disk cache (placeholder is seen for a moment). This is bad user experience, the user expects them to be loaded already.
Somehow on iphone (using SDWebImage library) this was never a problem. I assume iPhone doesn't keep the UIImage in ARGB8888 format, but rather keeps it either compressed as JPEG in memory or uses some internal compressed format their GPU/graphic system can understand.
What am I missing? How are large collections of images usually handled/displayed on Android?
Thanks

A: have you tried to set a large heap in the AndroidManifest? This feature is available only from Honeycomb SDK
<application
    android:largeHeap="true"/>


text:
Q: Showing that a function is affine in $\mathbb{R}^{n}$ I'm reading an analysis book, and I'm struggling with a question. First, here is the definition for an affine function:

A function is said to be affine if it is defined by
$$g(u) = c + \sum_{i=1}^{n}a_{i}u_{i}$$
where $c$ and the $a_{i}'s$ are prescribed values. If $c = 0,$ the
  function is linear.

Now, here's the problem:

Fix a point $x$ in $\mathbb{R}^{n}$ and let $c$ be a point in
  $\mathbb{R}^{n}$ and define $\phi : \mathbb{R}^{n} : \mathbb{R}$ by
  $$\phi(u) = \langle c, u - x \rangle .$$
(a) Show that $\phi : \mathbb{R}^{n} \rightarrow \mathbb{R}$ is
  affine.
(b) Show that given any nonconstant affine function $\phi :
 \mathbb{R}^{n} \rightarrow \mathbb{R}$, it is possible to choose
  points $x, c \in \mathbb{R}^{n}$ so that $\phi : \mathbb{R}^{n}
 \rightarrow \mathbb{R}$ has the above form.

For (a), I used the bilinearity property of the inner product as follows:
$$\langle c, u - x \rangle = \sum_{i=1}^{n} c_{i}u_{i}  - \sum_{i=1}^{n} c_{i}x_{i}.$$
I don't know how to get it into the form used in the definition, though. I also don't know how to get an arbitrary affine function into the form provided above. I'm guessing you start with $c + \sum_{i=1}^{n} a_{i}u_{i}$ and manipulate it into what we want. I tried a lot of things, but I couldn't get it.
Any help is appreciated.

A: The term $-\sum_{i=1}^{n} c_ix_i$ is just a constant since $<c,u-x>$ is only a function of $u$.  So, it does have the form of the affine function in the definition.
Part (b) follows from the fact that any number in $\mathbb{R}$ can be written as a linear combination of other numbers in $\mathbb{R}$ ($\mathbb{R}$ is closed under addition and scalar multiplication).

A: For b) take $x_0=(a_1,a_2,...,a_n)$ and $x =-\frac c {\|(a_1,a_2,...,a_n)\|^{2}} x_0$. Then $\langle x_0, (u-x) \rangle =c+\sum a_i u_i$.


text:
Q: Trademark Symbol not rendering in SQL Server 2014 On my SQL Server 2014 instance, if I run
select @@version
select 'None of your Business™'

I get:
----------------------------------------------------------------------------------------------------------------------------------------------------------

    ------------------------------------------------------------------------------------------------------
    Microsoft SQL Server 2014 (SP2) (KB3171021) - 12.0.5000.0 (X64)
        Jun 17 2016 19:14:09
        Copyright (c) Microsoft Corporation
        Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (Hypervisor)

(1 row affected)

    ----------------------
    None of your BusinessT

(1 row affected)
On my local SQL Server 2017 if I run
select @@version
select 'None of your Business™'

I get:
-----------------------------------------------------------------------------

    -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Microsoft SQL Server 2017 (RTM) - 14.0.1000.169 (X64)
        Aug 22 2017 17:04:49
        Copyright (C) 2017 Microsoft Corporation
        Developer Edition (64-bit) on Windows 10 Enterprise 10.0 <X64> (Build 17763: ) (Hypervisor)

(1 row affected)

----------------------
None of your Business™

(1 row affected)

Does SQL Server 2014 just not handle this character?  Other than upgrading to SQL Server 2014 is there a patch or anything to get it work with this?  Is there a way to modify a query to work with both versions?
select CHAR(0153)

renders as a ™ in SQL Server 2017, but as a Ö in SQL Server 2014.


text:
Q: T-SQL Multiple grouping I have follwing data :
Product Price   StartDate                   EndDate
Apples  4.9     2010-03-01 00:00:00.000     2010-03-01 00:00:00.000
Apples  4.9     2010-03-02 00:00:00.000     2010-03-02 00:00:00.000
Apples  2.5     2010-03-03 00:00:00.000     2010-03-03 00:00:00.000
Apples  4.9     2010-03-05 00:00:00.000     2010-03-05 00:00:00.000
Apples  4.9     2010-03-06 00:00:00.000     2010-03-06 00:00:00.000
Apples  4.9     2010-03-09 00:00:00.000     2010-03-09 00:00:00.000
Apples  2.5     2010-03-10 00:00:00.000     2010-03-10 00:00:00.000
Apples  4.9     2010-03-11 00:00:00.000     2010-03-11 00:00:00.000
Apples  4.9     2010-03-12 00:00:00.000     2010-03-12 00:00:00.000
Apples  4.9     2010-03-13 00:00:00.000     2010-03-13 00:00:00.000
Apples  4.9     2010-03-15 00:00:00.000     2010-03-15 00:00:00.000
Apples  4.9     2010-03-16 00:00:00.000     2010-03-16 00:00:00.000

want to group like product, price, min(startdate), max(startdate) but should have grouping in start date and end date as well........ something like below
Desired result
Apples  4.9     2010-03-01 00:00:00.000     2010-03-02 00:00:00.000
Apples  2.5     2010-03-03 00:00:00.000     2010-03-03 00:00:00.000
Apples  4.9     2010-03-05 00:00:00.000     2010-03-09 00:00:00.000
Apples  2.5     2010-03-10 00:00:00.000     2010-03-10 00:00:00.000
Apples  4.9     2010-03-11 00:00:00.000     2010-03-16 00:00:00.000

A: SELECT  product, price, MIN(start_date), MAX(end_date)
FROM    (
        SELECT  product, price, start_date, end_date,
                ROW_NUMBER() OVER (PARTITION BY product ORDER BY startDate) rn1,
                ROW_NUMBER() OVER (PARTITION BY product, price ORDER BY startDate) rn2
        FROM    mytable
        ) q
GROUP BY
        product, price, rn2 - rn1
ORDER BY
        product, MIN(start_date), price

A: Here is a SQLFiddle demo
with t2 as
(
select t1.*,
(select count(Price)
  from t
  where startdate<t1.startdate
        and Price<>t1.price
        and Product=t1.Product
)
rng
from t as t1
)
select Product,Price,min(startDate),max(EndDate)
from t2 group by Product,Price,RNG
order by 3

A: My approach.
Data:
create table t ( producte varchar(50),
                 price money,
                 start_date date,
                 end_date date);

insert into t values
( 'apple', 4.9, '2012-01-01', '2012-01-01' ),
( 'apple', 4.9, '2012-01-02', '2012-01-02' ),
( 'apple', 8, '2012-01-04', '2012-01-04' ),
( 'cat', 5, '2012-01-01', '2012-01-01' ),
( 'cat', 6, '2012-01-02', '2012-01-02' ),
( 'cat', 6, '2012-01-03', '2012-01-03' );

Query:
with start_dates as (
  select
    t.producte, t.price, t.start_date, t.end_date, t.start_date as gr_date
  from
    t left outer join
    t t1 on
        t.price = t1.price and                         --new
        t.producte = t1.producte and
        t.start_date = dateadd(day,1, t1.end_date )
  where t1.producte is null
  union all
  select
      t.producte, t.price, t.start_date,t. end_date, gr_date
  from
      t inner join
      start_dates t1 on
        t.price = t1.price and                         --new
        t.producte = t1.producte and
        t.start_date = dateadd(day,1, t1.end_date )
)
select t.producte, t.price , min( t.start_date ), max( t.end_date )
from start_dates t
group by  t.producte, gr_date  ,t.price

Results:
| PRODUCTE | PRICE |   COLUMN_2 |   COLUMN_3 |
----------------------------------------------
|    apple |   4.9 | 2012-01-01 | 2012-01-02 |
|    apple |     8 | 2012-01-04 | 2012-01-04 |
|      cat |     5 | 2012-01-01 | 2012-01-01 |
|      cat |     6 | 2012-01-02 | 2012-01-03 |

Explanation
This is a recursive CTE expression. Base query take inital dates for each group of prices. Recursive query looks for last data with this price.

A: Here's a suggestion: for each row, you must find the maximum previous date for which the price is different and you Group on that.  For example, for any line between 2010-03-11 and 2010-03-16, you must retrieve the date 2010-03-10 because this is the maximum previous date for which the price is different (2.5 versus 4.9).  The first row(s) will return a null date but that shouldn't be a problem.
However, for a very long table, this kind of query could become very slow.  Therefore, if you have some speed problem, you should look into the possibility of adding a column and use a cursor to fill it incrementally: you loop through it by date and each time you see a new price, you change its value.  The final Grouping is then trivial.
Here's something:
Select Product, Price, Min(StartDate) as StartDate, PreviousDate from (
    Select product, price, StartDate, (Select max (StartDate) from table_2 t3 where t3.price <> t2.price and t3.StartDate < t2.StartDate and t3.Product = t2.Product) as previousDate
    from table_2 t2) SQ

Group by Product, Price, PreviousDate
Order by PreviousDate

A: I believe this is the best-performing solution so far:
WITH Calc AS (
   SELECT *,
      Grp = DateAdd(day, -Row_Number()
         OVER (PARTITION BY Product, Price ORDER BY StartDate), StartDate
      )
   FROM dbo.PriceHistory
)
SELECT Product, Price, FromDate = Min(StartDate), ToDate = Max(StartDate)
FROM Calc
GROUP BY Product, Price, Grp
ORDER BY FromDate;

Try this out yourself


text:
Q: ASP.NET Core MVC app : I want to show the same view after submit and render the same data but having problems I am new to ASP.NET Core MVC but I do have some experience working with ASP.NET webforms. I am creating an ASP.NET Core MVC project for practice in this I have a controller which has [http post] Create and Http Get Create action methods.
When user is on the Create page after entering the data user can click the submit button and once the data is saved, the view for http post Create() is render (reloading same view) and I am trying to show the data that user has filled prior to submit but data is not binding to the input controls. I am passing the same model to the view which was sent to be saved. During the debug and I am able to see the expected value under the Locals window in Visual Studio.
I want to understand what I am doing wrong or what changes I should be doing in order to work. If I need to take the different approach then why this the approach (mentioned below in code) I am taking is not correct?
Below is the code and explanation in the comments.
    [HttpGet]
    public async Task<IActionResult> Create()
    {
        // I am creating a viewModel object because wanted to include the logic for List<users> for dropdown.
        var createView = await _chloramine.ChloramineSaveViewModel();
        return View(createView);
    }

    [HttpPost]
    // At page submit this Action method is called and data is saved.
    public  async Task<IActionResult> Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
    {
        _chloramine.CreateChloramineLog(clEditSaveViewModel);

        // After data is saved I am adding a user list to the model because I was getting Object null error.
        clEditSaveViewModel.User = await _chloramine.GetUser();

        // Passing the same model object which was received in order to show what was filled or selected by the user.
        return View(clEditSaveViewModel);
    }

Below is the Create view html.
@model EquipmentMVC.Models.ChloramineLogEditSaveViewModel

@{
     ViewData["Title"] = "Create";
}

<form  asp-action="Create">

        @foreach (var item in Model.User)
        {
            @Html.HiddenFor(model => item)
        }

            <input asp-for="TimeDue" value="" class="form-control" />

                    <input class="form-check-input" asp-for="PostPrimaryCarbanTankTp1" />

            <input asp-for="Comments" class="form-control" />

                <input class="form-check-input" asp-for="IsCompleted" />

        Technician

            <select asp-for="Selected" asp-items=@(new SelectList(Model.User,"Id","Name"))>
                <option value="">Select...</option>
            </select>
            @**@

        RN

            <select asp-for="RnSelected" asp-items=@(new SelectList(Model.User,"Id","Name"))>
                <option value="">Select...</option>
            </select>

            <input type="submit" value="Create" class="btn btn-secondary" />

</form>

A: I tested your code and found that it runs very well in my project.
Except for TimeDue, the field is not successfully bound, the rest of the fields are bound successfully.
I don't know if you have the same problem. The TimeDue is not successful binding is because you set the Value in the view.
Please delete the value in this field in the view:
 <input asp-for="TimeDue" class="form-control" />

Result:

By the way,your User is null only because your User is not successfully bound, you can modify your loop code as follows:
 @for (int i = 0; i < Model.User.Count(); i++)
    {
        <input type="hidden" name="User[@i].Id" value=@Model.User[i].Id />
        <input type="hidden" name="User[@i].Name" value=@Model.User[i].Name />
    }

Then in your Create action:
[HttpPost]
    public IActionResult Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
    {

        return View(clEditSaveViewModel);
    }

Result:

Edit:
My codes:
Controller:
  public IActionResult Create()
    {
        var model = new ChloramineLogEditSaveViewModel
        {
            Id = 1,
            Comments = "aaaa",
            PostPrimaryCarbanTankTp1 = "fjsdgk",
            TimeDue = "bbbbbb",
            IsCompleted=true,
            RnSelected="gggg",
            Selected="sgs",
            User=new List<User>
            {
                new User{
                Id=1,
                Name="aa"
                },
                new User
                {
                   Id=2,
                   Name="bb"
                }
            }
        };
        return View(model);
    }
    [HttpPost]
    public IActionResult Create(ChloramineLogEditSaveViewModel clEditSaveViewModel)
    {

        return View(clEditSaveViewModel);
    }

View:
<form asp-action="Create">

    @for (int i = 0; i < Model.User.Count(); i++)
    {
        <input type="hidden" name="User[@i].Id" value=@Model.User[i].Id />
        <input type="hidden" name="User[@i].Name" value=@Model.User[i].Name />
    }

        <input asp-for="TimeDue" class="form-control" />

                <input class="form-check-input" asp-for="PostPrimaryCarbanTankTp1" />

        <input asp-for="Comments" class="form-control" />

            <input class="form-check-input" asp-for="IsCompleted" />

    Technician

        <select asp-for="Selected" asp-items=@(new SelectList(Model.User,"Id","Name"))>
            <option value="">Select...</option>
        </select>

    RN

        <select asp-for="RnSelected" asp-items=@(new SelectList(Model.User,"Id","Name"))>
            <option value="">Select...</option>
        </select>

        <input type="submit" value="Create" class="btn btn-secondary" />

</form>


text:
Q: mount_smbfs inconsistent behavior mac osx I can use "mount_smbfs //$uname:$passwd@$ip/$share mountpoint/"
This command works by itself, or when run in a plain bash script.
I have a bash script in which I call a python script (using selenium) to configure a server. Once the python script completes, I try to mount the newly created smb share and write to it. I keep getting this error: "mount_smbfs: server connection failed: invalid arguement". Exit code is 68.
Again, this command works fine when used everywhere else, except in this script. I can see the syntax is exactly the same when the command runs.
I know that this is not a problem with my server, I mount through AFP before SMB, so I know it's not a timing issue.
Is there some problem I'm unaware of when mixing languages in a script? Any insight is appreciated.
Edit:
I am not sure why, but I just added a loop condition and to retry after failure and it works fine on the second try.


text:
Q: Add wording with a line to a number in a matrix I'm writing some notes in LaTeX and I would like to do it as I have in the next figure:

Does anyone know of a tutorial I check on how to do it?
All best and thank you.

A: Of course NiceMatrix environment is absolutely useful and versatile, and I strongly recommend it. However, if you want to do those things a bit more manually, there's alway the tikzmark library.

\documentclass{article}
\usepackage{tikz,amsmath}
\usetikzlibrary{tikzmark}

\begin{document}

    \[
    \begin{pmatrix}
    \tikzmarknode{A1}{1} & 2 & 1 \\
    3 & \tikzmarknode{A2}{8} & 1 \\
    0 & 4 & 1
    \end{pmatrix}
    \]

    \begin{tikzpicture}[remember picture,overlay]

        \node[draw,red,inner sep=1pt] (B1) at (A1) {\phantom{1}};
        \draw[red] (B1)  --++ (-1,0) node [left] {pivot};

        \node[draw,blue,inner sep=1pt] (B2) at (A2) {\phantom{8}};
        \path (B2) --++ (2,1) node[blue] (C2) {second pivot};
        \draw[blue] (B2) edge[out=45,in=180] (C2);

    \end{tikzpicture}

\end{document}

A: The environments of the package nicematrix creates PGF/Tikz nodes under the cells, rows and columns of the arrays which are constructed.
Thus, it's possible to use these nodes with Tikz to draw whatever you want with Tikz.
\documentclass{article}
\usepackage{nicematrix,tikz}
\usetikzlibrary{fit}

\begin{document}

$\begin{pNiceMatrix}[margin=3pt]
1 & 2 & 1 \\
3 & 8 & 1 \\
0 & 4 & 1
\CodeAfter
  \begin{tikzpicture} [red]
    \node [draw,fit=(1-1),inner sep=2pt] {} ;
    \draw (1-1.west) -- ++ (-1cm,0) node [left] {\color{red} pivot} ;
  \end{tikzpicture}
\end{pNiceMatrix}$

\end{document}

You need several compilations (because of the nodes PGF/Tikz nodes).


text: Q: How did people estimate the speed of light before modern technology? I just read a wikipedia page on the speed of light. Apparently people have made pretty accurate estimates for almost 200 years. How did they do this? How did they measure any fundamental constant accurately before they had modern technology?


text:
Q: finite covering  I am trying to understand the following example, which I came across in a research article. I am posting it as a question below.
$\bf{Question}$. Let $\Sigma$ be a curve of genus two with the automorphism group $G$, and $p_1$, $p_2$, and $p_3$ are three points on $\Sigma$. Let $a_{1}$, $b_{1}$, $a_{2}$, $b_{2}$ denote the generators of $\pi_{1}(\Sigma)$ and $\gamma_{1}$, $\gamma_{2}$, $\gamma_{3}$ are simple loops about the points $p_{1}$, $p_{2}$, and $p_{3}$. Consider the following map $f$ from $\pi_{1} (\Sigma \setminus p_{1}, p_{2}, p_{3})$ to $\mathbb{Z}_{3}$ given by $\gamma_i \rightarrow 1$ and $a_{i}, b_{i} \rightarrow 0$. What it means the covering (unramified) $\Pi_{f} :\Sigma' \rightarrow \Sigma$ associated to the stabilizer of $f$? How one can think of such covering map in terms of the automorphism group $G$ of $\Sigma$? What one can say about the degree of $\Pi_{f}$?

A: By Riemann Existence Theorem, the surjection $f \colon \pi_1(\Sigma \setminus p_1, p_2, p_3) \to \mathbb{Z}_3$ gives a Galois cover with Galois group $\mathbb{Z}_3$ branched only at the points $p_1, p_2, p_3$.
This cover is precisely your covering $\Pi_f \colon \Sigma' \to \Sigma$. Then $\deg \Pi_f = |\mathbb{Z}_3|=3$. (By the way, here I do not understand why you wrote that the cover is "unramified", which is false. Maybe you meant "ramified"?)
The Galois group of $\Pi_f$ acts naturally on $\Sigma'$, and the action is free outside the preimages of $p_1$, $p_2$, $p_3$. At these preimages the stabilizer is obviously $\mathbb{Z}_3$ itself, so the cover $\Pi_f$ is totally ramified over $p_1$, $p_2$, $p_3$.
Then the genus of $\Sigma'$ can be computed by Riemann-Hurwitz formula, obtaining
$$2g(\Sigma')-2= |\mathbb{Z}_3| \bigg(2g(\Sigma)-2 + 3 \bigg(1-\frac{1}{3} \bigg) \bigg),$$
that is $g(\Sigma')=7$.


text:
Q: Reloading same page in Angular 4/5 & TypeScript I am developing a one page application with the help of routes:
this.router.navigate(['/customer-home'], { skipLocationChange: true });

When I am at the above page, I am adding a customer using a REST call. After the customer gets updated, I want my page to refresh and reload the /customer-home page view.
My method looks like below :
  addNewCustomer(customer) {
    this.dataService.postEntity('customers', customer);
    location.reload();
  }

The problem is that location.reload refreshes the page and redirects to home page.
I have done a console log for the location:
Location {replace: ƒ, assign: ƒ, href: "http://localhost:4200/", ancestorOrigins: DOMStringList, origin: "http://localhost:4200", …}

Is there any way, I can reload my page and data using routes, and I do not want to show the URL in address bar.
PS I have already tried redirecting to some other component and then coming back to current component, but it does not reloads the data and does not shows latest added customer.

A: Using Location.reload in a Single Page Application does the opposite of what a SPA intends to do.
It seems you're trying to reload the page for getting the new data from your server.
Loading the data shouldn't be the Router job. Instead of reloading the page, you should request the data after the insertion or on the callback of your postEntity method.
Although, better than requesting data again, you should simply add the Entity to the latest added customers array or whatever you use to hold the data.

A: You could use the router service to redirect/reload to your customer page if that is what you are looking to do for some reason.
addNewCustomer(customer) {
    this.dataService.postEntity('customers', customer);
    this.router.navigate(['/customer-home']);
}

But I would suggest taking everyone else's suggestions and use Observables or Promises to reload your data instead of the entire page.
The Observable should look something like so, provided below and I would suggest having your Post method return the customer after updating it.
addNewCustomer(customer) {
    this.dataService
        .postEntity('customers', customer)
        .subscribe(
            update => this.customer = update;
            err => console.log(err);
        )
}


text:
Q: Daily time limitations from Google Scripts in Google Forms I have a google form ready but I wish to set a time limit on it so that it goes live everyday from 8am (it starts accepting responses) to 5pm (it stops accepting responses). I managed to find something close to what I wanted here https://www.labnol.org/internet/schedule-google-forms/20707/.
I am not a programmer with no knowledge of JS but have a little knowledge on C++ (mandatory university unit).
I have tried to tweak the sourced code to my wishes by researching online.
here is my script in google scripts.
function oc() {

  ScriptApp.newTrigger('openForm')
     .timeBased()
     .everyDays(1)
     .atHour(8)
     .create();

  ScriptApp.newTrigger('closeForm')
     .timeBased()
     .everyDays(1)
     .atHour(16)
     .create();
}

function openForm() {
  var form = FormApp.getActiveForm();
  form.setAcceptingResponses(true);
}

function closeForm() {
  var form = FormApp.getActiveForm();
  form.setAcceptingResponses(false);
  deleteTriggers_();
}

A: How about this sample script?
Flow :

*

*In order to launch oc(), please at first, run initTrigger(). By this, oc() is launched at AM 0:00 every day. Please at first run this only one time.

*

*After initTrigger() was run, you can confirm this trigger on your script editor.

*When oc() is launched at AM 0:00, existing triggers for launching openForm() and closeForm() are removed.

*And then, the triggers for launching openForm() and closeForm() are installed as new trigger. At this time, the trigger days for openForm() and closeForm() are today's AM 8:00 and PM 5:00, respectively.

Scripts :
function initTrigger(){
  ScriptApp.newTrigger('oc').timeBased().atHour(0).everyDays(1).create();
}

function oc() {
  ScriptApp.getProjectTriggers().forEach(function(e){
    if(e.getHandlerFunction() == "openForm" || e.getHandlerFunction() == "closeForm") {
      ScriptApp.deleteTrigger(e)
    }
  });

  var time = new Date()
  time.setHours(8);
  time.setMinutes(0);
  ScriptApp.newTrigger("openForm").timeBased().at(time).create();

  time.setHours(17);
  time.setMinutes(0);
  ScriptApp.newTrigger("closeForm").timeBased().at(time).create();
}

function openForm() {
  var form = FormApp.getActiveForm();
  form.setAcceptingResponses(true);
}

function closeForm() {
  var form = FormApp.getActiveForm();
  form.setAcceptingResponses(false);
  // deleteTriggers_();
}


text:
Q: Displaying a list of string in report I am a bit new to JasperReports. I am trying to print a list of names in one of the columns in a sample report using iReport. Although the list is getting displayed correctly yet it is not giving the output format as desired.
Output Received:
Merchant Name                              Fruits Sold
Marx                                       [Fiji apple,  Kashmir apple, Shimla apple]
Stalin                                     [Fiji apple,  Kashmir apple, Shimla apple]

Whereas the Expected output should be:
Merchant Name                             Fruits Sold
Marx                                      Fiji apple
                                          Kashmir apple
                                          Shimla apple

Stalin                                    Fiji apple
                                          Kashmir apple
                                          Shimla apple

I am using a List element in report for the "fruits sold" column. And in the list frame I am putting the text field element ${fruitsForSale} from the Javabean. The List element is having the connection expression as $P{REPORT_CONNECTION} to use the same connection as the main dataset.
The Javabean class is as below:
import java.util.ArrayList;
import java.util.List;

public class FruitSeller {
  private String merchantName;
  private List<String> fruitsForSale;

  public String getMerchantName() {
    return this.merchantName;
  }

  public void setMerchantName(String merchantName) {
    this.merchantName = merchantName;
  }

  public List<String> getFruitsForSale() {
    return this.fruitsForSale;
  }
  public void setFruitsForSale(List<String> fruitsForSale) {
    this.fruitsForSale = fruitsForSale;
  }
  public static List<FruitSeller> prepareReport() {
    List fruitSellerList = new ArrayList();

    FruitSeller fruitSeller = new FruitSeller();
    fruitSeller.setMerchantName("Marx");
    List fruitsForSale = new ArrayList();
    fruitsForSale.add("Fiji apple");
    fruitsForSale.add("Kashmir apple");
    fruitsForSale.add("Shimla apple");
    fruitSeller.setFruitsForSale(fruitsForSale);
    fruitSellerList.add(fruitSeller);

    FruitSeller fruitSeller2 = new FruitSeller();
    List fruitsForSale2 = new ArrayList();
    fruitSeller2.setMerchantName("Stalin");
    fruitsForSale2.add("Fiji apple");
    fruitsForSale2.add("Kashmir apple");
    fruitsForSale2.add("Shimla apple");
    fruitSeller2.setFruitsForSale(fruitsForSale2);
    fruitSellerList.add(fruitSeller2);
    return fruitSellerList;
  }
}

And the jrxml file is as below:
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="TaskReport" language="groovy" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="fe637f77-a273-4977-a964-127a514b9844">
    <subDataset name="dataset1" uuid="d4eb79c1-9e33-42d2-ae15-a8416f7c1cb4"/>
    <subDataset name="New Dataset 1" uuid="18df23e8-0545-4bef-aef8-804e425d990f"/>
    <subDataset name="dataset6" uuid="09a35364-9d98-4c70-9246-de2759b0d421"/>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="fruitsForSale" class="java.util.List">
        <fieldDescription><![CDATA[fruitsForSale]]></fieldDescription>
    </field>
    <field name="merchantName" class="java.lang.String">
        <fieldDescription><![CDATA[merchantName]]></fieldDescription>
    </field>
    <columnHeader>
        <band height="34" splitType="Stretch">
            <staticText>
                <reportElement uuid="8dbb8a02-6cb2-404a-af92-34c129fdae11" stretchType="RelativeToBandHeight" x="0" y="0" width="262" height="34"/>
                <box>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Merchant Name]]></text>
            </staticText>
            <staticText>
                <reportElement uuid="389f9247-f6d9-43b7-86e7-ad6aed456117" x="262" y="0" width="293" height="34"/>
                <box>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement verticalAlignment="Middle">

                </textElement>
                <text><![CDATA[Fruits Sold]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="44" splitType="Stretch">
            <textField>
                <reportElement uuid="94bef980-1315-418a-96f8-4a5f6bf21e9a" x="0" y="0" width="262" height="44"/>
                <box>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement>

                </textElement>
                <textFieldExpression><![CDATA[$F{merchantName}]]></textFieldExpression>
            </textField>
            <componentElement>
                <reportElement uuid="e3c1916e-8785-4517-9f99-132edd759cc7" x="262" y="1" width="293" height="43"/>
                <jr:list xmlns:jr="http://jasperreports.sourceforge.net/jasperreports/components" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports/components http://jasperreports.sourceforge.net/xsd/components.xsd" printOrder="Vertical">
                    <datasetRun subDataset="dataset6" uuid="8bcd4e11-7efd-48bf-9314-fd84812879d7">
                        <connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
                    </datasetRun>
                    <jr:listContents height="43" width="293"/>
                </jr:list>
            </componentElement>
            <textField>
                <reportElement uuid="1fe0b910-b7f8-48e9-aa21-5b0073d8b6f5" x="262" y="0" width="293" height="44"/>
                <box>
                    <topPen lineWidth="0.5"/>
                    <leftPen lineWidth="0.5"/>
                    <bottomPen lineWidth="0.5"/>
                    <rightPen lineWidth="0.5"/>
                </box>
                <textElement/>
                <textFieldExpression><![CDATA[$F{fruitsForSale}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
</jasperReport>

Can anybody advice where I maybe going wrong?


text:
Q: Resolvent bounds for non-normal operators Let $A$ be a bounded non-normal operator on a separable Hilbert space and $z\in\mathbb{C}$ such that $\delta:=\mathrm{dist}(z,\sigma(A))>0$.
Is it true, like the case of self-adjoint operators, that:
1) $$ \|(A-zI)^{-1}\|\leq \frac{1}{\delta} $$
2) If $B$ is a bounded operator such that $\|B\|<\delta$, then $$ \|(A+B-zI)^{-1}\| < \frac{1}{\delta-\|B\|}$$
If it is false, please provide a counter-example.

A: Look at the case of a $2 \times 2$ nilpotent matrix to disprove your conjecture. Such a matrix has spectrum consisting of one point, namely 0. More explicitly, look at
$$
     A := \begin{pmatrix}0 & 1 \\ 0 & 0\end{pmatrix}.
$$
Then $A^2=0$, which gives a truncated geometric series for the resolvent:
$$
     (\lambda I-A)^{-1}= \frac{1}{\lambda}I+\frac{1}{\lambda^2}A.
$$
You cannot bound the norm of the above by a constant times $1/|\lambda|$ near $\lambda=0$ because of the $1/\lambda^2$ term.